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
181,254
<p>If I have a style defined</p> <pre><code>.style1 { width: 140px; } </code></pre> <p>can I reference it from a second style?</p> <pre><code>.style2 { ref: .style1; } </code></pre> <p>Or is there a way via javascript/jQuery?</p> <p>--- Edit</p> <p>To clarify the problem, I am trying to apply whatever style is defined for a #x and #c to .x and .c without altering the CSS as the CSS is going to have updates that are out of my control.</p> <p>I used width but really the style would be something more complex with font, border and other style elements being specified.</p> <p>Specifying multiple class names does work when the style is being applied to a class so I'll mark existing responses as answers, but I need to take the style being applied to an id and also apply it to a class style ... if that makes any sense. </p>
[ { "answer_id": 181269, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 5, "selected": true, "text": "<p>There's no way to do it with CSS -- it's an oft-requested feature, but not included in the spec yet. You also can't do it directly with JS, but there's sort of a hacky workaround:</p>\n\n<pre><code>$('.style2').addClass ('style1');\n</code></pre>\n" }, { "answer_id": 181271, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 3, "selected": false, "text": "<p>you can achieve the same functionality by allowing elements to inherit multiple styles. ex.</p>\n\n<pre><code>&lt;p class=\"style1 style2\"&gt;stuff&lt;/p&gt;\n</code></pre>\n\n<p>and then your css would include, for example:</p>\n\n<pre><code>.style1 {width:140px;}\n.style2 {height:140px;}\n</code></pre>\n\n<p>edit: actually robert's answer might better approximate the method you are trying to achieve</p>\n\n<pre><code>.style1, .style2 {width: 140px;}\n.style2 {height: 140px;}\n\n&lt;p class=\"style2\"&gt;i will have both width and height applied&lt;/p&gt;\n</code></pre>\n" }, { "answer_id": 181273, "author": "Robert Elwell", "author_id": 23102, "author_profile": "https://Stackoverflow.com/users/23102", "pm_score": 3, "selected": false, "text": "<p>One way to use the same code for multiple blocks is the following:</p>\n\n<pre><code> .style1, .style2 { width: 140px; }\n</code></pre>\n" }, { "answer_id": 181317, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 1, "selected": false, "text": "<p>Some options:</p>\n\n<ol>\n<li><p>Generate your CSS dynamically, either on the fly or as you're authoring your style sheets (I use a Visual Studio macros to implement constants for fonts, numbers, and colors - and to calculate light/dark tints of colors). This topic has been much discussed elsewhere on this site.</p></li>\n<li><p>If you have a number of styles that are 140px wide and you want to have the flexibility of changing that dimension for all of those styles, you could do this: </p>\n\n<pre><code>div.FixedWidth {width:140px;}\ndiv.Style1 {whatever}\ndiv.Style2 {whatever}\n</code></pre></li>\n</ol>\n\n<p>and</p>\n\n<pre><code> &lt;div class=\"Style1 FixedWidth\"&gt;...&lt;/div&gt;\n &lt;div class=\"Style2 FixedWidth\"&gt;...&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 865161, "author": "ajm", "author_id": 78738, "author_profile": "https://Stackoverflow.com/users/78738", "pm_score": 1, "selected": false, "text": "<p>Are you talking about getting all of the computed styles set on a particular Element and applying those to a second Element?</p>\n\n<p>If that's the case, I think you're going to need to iterate through one Element's computed styles using and then apply those to your other Elements' cssText properties to set them as inline styles.</p>\n\n<p>Something like:</p>\n\n<pre><code>el = document.getElementById('someId');\nvar cStyle = '';\nfor(var i in el.style){\n if(el.style[i].length &gt; 0){ cStyle += i + ':' + el.style[i] + ';';\n}\n$('.someClass').each(function(){ this.style.cssText = cStyle; });\n</code></pre>\n\n<p>If you know that you'll only be dealing with a finite set of CSS properties, you could simplify the above as:</p>\n\n<pre><code>el = $('#someId');\nvar styleProps = {'border-top':true,'width':true,'height':true};\nvar cStyle = '';\nfor(var i in styleProps){\n cStyle += styleProps[i] + ':' + el.style(styleProps[i]) + ';';\n}\n$('.someClass').each(function(){ this.style.cssText = cStyle; });\n</code></pre>\n\n<p>I'll caveat the above code with the fact that I'm not sure whether or not the IEs will return a CSSStyleDeclaration Object for an HTMLElement's style property like Mozilla will (the first example). I also haven't given the above a test, so rely on it as pseudo-code only.</p>\n" }, { "answer_id": 19171505, "author": "joydesigner", "author_id": 1362554, "author_profile": "https://Stackoverflow.com/users/1362554", "pm_score": 2, "selected": false, "text": "<p>Another way is use pre -processing tool, like less and sass. Then after you compile the less/sass file, it will result as normal css.</p>\n\n<p>Here is the documentation of <a href=\"http://lesscss.org/#usage\" rel=\"nofollow\">less</a> and <a href=\"http://sass-lang.com/\" rel=\"nofollow\">sass</a>.</p>\n\n<pre><code>// example of LESS\n\n#header {\nh1 {\n font-size: 26px;\n font-weight: bold;\n }\np { font-size: 12px;\n a { text-decoration: none;\n &amp;:hover { border-width: 1px }\n }\n }\n}\n\n\n/* Compiled CSS */\n\n#header h1 {\n font-size: 26px;\n font-weight: bold;\n}\n#header p {\n font-size: 12px;\n}\n#header p a {\n text-decoration: none;\n}\n#header p a:hover {\n border-width: 1px;\n}\n</code></pre>\n" }, { "answer_id": 30131315, "author": "Mark Manning", "author_id": 928121, "author_profile": "https://Stackoverflow.com/users/928121", "pm_score": 0, "selected": false, "text": "<p>I was trying this same thing and found this webpage (as well as some others). There isn't a DIRECT way to do this. IE:</p>\n\n<pre><code>&lt;html&gt;&lt;head&gt;&lt;title&gt;Test&lt;/title&gt;&lt;style&gt;\n.a { font-size: 12pt; }\n.b { font-size: 24pt; }\n.c { b }\n&lt;/style&gt;&lt;/head&gt;&lt;body&gt;\n&lt;span class='c'&gt;This is a test&lt;/span&gt;&lt;/body&gt;&lt;/html&gt;\n</code></pre>\n\n<p>Does <strong>NOT</strong> work. The problem here is you (like me) are trying to do things in a logical fashion. (ie: A-then-B-then-C)</p>\n\n<p>As others have pointed out - this just does not work. Although it SHOULD work and CSS SHOULD have a lot of other features too. It doesn't so you have to do a work around. Some have already posted the jQuery way to get around this but what you want CAN be achieved with a slight modification.</p>\n\n<pre><code>&lt;html&gt;&lt;head&gt;&lt;title&gt;Test&lt;/title&gt;&lt;style&gt;\n.a { font-size: 12pt; }\n.b,.c { font-size: 24pt; }\n&lt;/style&gt;&lt;/head&gt;&lt;body&gt;\n&lt;span class='c'&gt;This is a test&lt;/span&gt;&lt;/body&gt;&lt;/html&gt;\n</code></pre>\n\n<p>This achieves the same effect - just in a different way. Instead of trying to assign \"a\" or \"b\" to \"c\" - just assign \"c\" to \"a\" or \"b\". You get the same effect without it affecting the rest of your code.</p>\n\n<p>The next question that should pop into your mind is \"Can I do this for multiple CSS items. (Like font-size, font-weight, font-family?) The answer is YES. Just add the \",.c\" part onto each of the things you want it to be a part of and all of those \"parts\" will become a part of \".c\".</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;title&gt;Test&lt;/title&gt;\n&lt;style&gt;\n.a { font-size: 12pt; }\n.b,.c { font-size: 24pt; }\n.d { font-weight: normal; }\n.e,.c { font-weight: bold; }\n.f { font-family: times; }\n.g,.c { font-family: Arial; }\n&lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;span class='c'&gt;This is a test&lt;/span&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25372/" ]
If I have a style defined ``` .style1 { width: 140px; } ``` can I reference it from a second style? ``` .style2 { ref: .style1; } ``` Or is there a way via javascript/jQuery? --- Edit To clarify the problem, I am trying to apply whatever style is defined for a #x and #c to .x and .c without altering the CSS as the CSS is going to have updates that are out of my control. I used width but really the style would be something more complex with font, border and other style elements being specified. Specifying multiple class names does work when the style is being applied to a class so I'll mark existing responses as answers, but I need to take the style being applied to an id and also apply it to a class style ... if that makes any sense.
There's no way to do it with CSS -- it's an oft-requested feature, but not included in the spec yet. You also can't do it directly with JS, but there's sort of a hacky workaround: ``` $('.style2').addClass ('style1'); ```
181,268
<p>I have a simple iphone app that's based on the CrashLanding sample app. So basically you tap the title screen and do some stuff... all on the same "view". I want to add an "options" screen/page/view whatever with a few UISwitches. What's the easiest way to do this?</p> <p>Cheers!</p>
[ { "answer_id": 181327, "author": "fmsf", "author_id": 26004, "author_profile": "https://Stackoverflow.com/users/26004", "pm_score": 2, "selected": true, "text": "<p>Dunno if this will help I'm a bit new to objective-c and iPhone api.</p>\n\n<p>Maybe u can do something like this:\nUse the interface builder: just type \"Interface Builder\" on the Spotlight (top right corner) to generate like \"myOptions.xib\"</p>\n\n<p>And then just implement it: like</p>\n\n<pre><code>@implementation myOptions\n\n-(void)awakeFromNib\n{\n...\n</code></pre>\n\n<p>You can take a look at the QuartzDemo under the iPhone API to see how to load the interface list of objects. In the previous view controller you just need to add it to the object list.\nIt will look something like this:</p>\n\n<pre><code>@implementation previousController\n-(void)awakeFromNib\n{\n menuList = [[NSMutableArray alloc] init];\n QuartzViewController *controller;\n\n controller = [[QuartzViewController alloc] initWithTitle:@\"Options\"];\n controller.quartzViewDelegate = [[[myOptions alloc] init] autorelease];\n [menuList addObject:controller];\n [controller release];\n</code></pre>\n\n<p>Hope it helps</p>\n" }, { "answer_id": 181332, "author": "Parveen Kaler", "author_id": 26023, "author_profile": "https://Stackoverflow.com/users/26023", "pm_score": 0, "selected": false, "text": "<p>Use the Interface Builder to open MainWindow.xib. Add a new View to the XIB. Refer to the Interface Builder User Guide for more details.</p>\n\n<p><a href=\"http://developer.apple.com/documentation/DeveloperTools/InterfaceBuilder-date.html#doclist\" rel=\"nofollow noreferrer\">http://developer.apple.com/documentation/DeveloperTools/InterfaceBuilder-date.html#doclist</a></p>\n" }, { "answer_id": 186238, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 2, "selected": false, "text": "<p>There are numerous examples that show how to manage multiple full-screen views -- each view should typically be managed by a separate view controller. Check the Xcode templates for an example of how you can set up a \"flip\" view.</p>\n" }, { "answer_id": 204817, "author": "lfalin", "author_id": 28106, "author_profile": "https://Stackoverflow.com/users/28106", "pm_score": 0, "selected": false, "text": "<p>While everyone has mentioned ways and pointers for displaying an additional view, if you are trying to solve your original problem of displaying application settings, you may want to use a settings bundle instead as per the Apple HIG for the iPhone </p>\n\n<p><a href=\"http://developer.apple.com/iphone/library/documentation/UserExperience/Conceptual/MobileHIG/HandleTasks/chapter_6_section_4.html#//apple_ref/doc/uid/TP40006556-CH16-SW4\" rel=\"nofollow noreferrer\">http://developer.apple.com/iphone/library/documentation/UserExperience/Conceptual/MobileHIG/HandleTasks/chapter_6_section_4.html#//apple_ref/doc/uid/TP40006556-CH16-SW4</a></p>\n\n<p>For how to do this, see this:</p>\n\n<p><a href=\"http://developer.apple.com/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/ApplicationSettings/chapter_12_section_1.html#//apple_ref/doc/uid/TP40007072-CH13-SW10\" rel=\"nofollow noreferrer\">http://developer.apple.com/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/ApplicationSettings/chapter_12_section_1.html#//apple_ref/doc/uid/TP40007072-CH13-SW10</a></p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
I have a simple iphone app that's based on the CrashLanding sample app. So basically you tap the title screen and do some stuff... all on the same "view". I want to add an "options" screen/page/view whatever with a few UISwitches. What's the easiest way to do this? Cheers!
Dunno if this will help I'm a bit new to objective-c and iPhone api. Maybe u can do something like this: Use the interface builder: just type "Interface Builder" on the Spotlight (top right corner) to generate like "myOptions.xib" And then just implement it: like ``` @implementation myOptions -(void)awakeFromNib { ... ``` You can take a look at the QuartzDemo under the iPhone API to see how to load the interface list of objects. In the previous view controller you just need to add it to the object list. It will look something like this: ``` @implementation previousController -(void)awakeFromNib { menuList = [[NSMutableArray alloc] init]; QuartzViewController *controller; controller = [[QuartzViewController alloc] initWithTitle:@"Options"]; controller.quartzViewDelegate = [[[myOptions alloc] init] autorelease]; [menuList addObject:controller]; [controller release]; ``` Hope it helps
181,285
<p>Is it a problem if you use the global keyword on variables you don't end up using? Compare:</p> <pre><code>function foo() { global $fu; global $bah; if (something()) { $fu-&gt;doSomething(); } else { $bah-&gt;doSomething(); } } function bar() { if (something()) { global $fu; $fu-&gt;doSomething(); } else { global $bah; $bah-&gt;doSomething(); } } </code></pre> <p>I'm quite aware that using the second method makes maintaining this code much harder, and that it's generally preferred to put all your globals at the start of functions, so: <strong>Ignoring the difference in maintainability and code-styling of the two functions, is there a difference between these two in terms of overhead?</strong></p>
[ { "answer_id": 181290, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 4, "selected": true, "text": "<p>If there is, it won't be (humanly) measurable, unless you are literally calling this function millions of times. And even if it was a recursive function with that property, I still wouldn't use your second method for the maintainability aspects you already brought up.</p>\n\n<p><strong>Edit:</strong> For arguments sake, I actually went and benchmarked this, and <code>bar()</code> ended up slower by 0.1s over one million calls. Which means performance wise, you still have a reason to use the cleaner version.</p>\n" }, { "answer_id": 181349, "author": "dirtside", "author_id": 20903, "author_profile": "https://Stackoverflow.com/users/20903", "pm_score": 1, "selected": false, "text": "<p>As monoxide said, there's no significant performance difference.</p>\n\n<p>However, I'd avoid using global if at all possible; it's a bad road to go down and you'll end up with spaghetti. Use a static class; it'll keep things much better organized.</p>\n" }, { "answer_id": 181472, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 0, "selected": false, "text": "<p>In case you don't know, you can do the following:</p>\n\n<pre><code>function foo() {\n global $fu, $bah;\n if (something()) {\n $fu-&gt;doSomething();\n } else {\n $bah-&gt;doSomething();\n }\n}\n</code></pre>\n\n<p>You can put both of the globals in the same line. Might even make it faster :)</p>\n" }, { "answer_id": 182123, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": -1, "selected": false, "text": "<p>Global variables are generally considered very bad style. I would claim that whenever you need to use the global keyword, or a static class property (And thus, including the infamous Singleton), you should seriously reconsider what you're doing. It may be slightly more work to avoid globals, but it's a huge bonus to code maintainability. This particular example, might be better expressed with:</p>\n\n<pre><code>function foo($fu, $bah) {\n if (something()) {\n $fu-&gt;doSomething();\n } else {\n $bah-&gt;doSomething();\n }\n}\n</code></pre>\n\n<p>If you don't like passing a lot of parameters around, you may use classes to encapsulate them, or perhaps it is a sign that you should factor your code differently.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
Is it a problem if you use the global keyword on variables you don't end up using? Compare: ``` function foo() { global $fu; global $bah; if (something()) { $fu->doSomething(); } else { $bah->doSomething(); } } function bar() { if (something()) { global $fu; $fu->doSomething(); } else { global $bah; $bah->doSomething(); } } ``` I'm quite aware that using the second method makes maintaining this code much harder, and that it's generally preferred to put all your globals at the start of functions, so: **Ignoring the difference in maintainability and code-styling of the two functions, is there a difference between these two in terms of overhead?**
If there is, it won't be (humanly) measurable, unless you are literally calling this function millions of times. And even if it was a recursive function with that property, I still wouldn't use your second method for the maintainability aspects you already brought up. **Edit:** For arguments sake, I actually went and benchmarked this, and `bar()` ended up slower by 0.1s over one million calls. Which means performance wise, you still have a reason to use the cleaner version.
181,309
<p>In a nutshell, there's a global stylesheet:</p> <pre><code>a { font-family: Arial; } </code></pre> <p>I want to use a different font family for a particular link:</p> <pre><code>&lt;a href="..." style="font-family: Helvetica;"&gt;...&lt;/a&gt; </code></pre> <p>or</p> <pre><code>&lt;span style="font-family: Helvetica;"&gt;&lt;a href="..."&gt;...&lt;/a&gt;&lt;/span&gt; </code></pre> <p>but nothing works. Is there an easy way to do this?</p> <p>P.S. I'm dynamically (via PHP) assign different fonts to different links, so creating a special class is not an option.</p>
[ { "answer_id": 181312, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": true, "text": "<p>Unless you have a specific font named Helvetica, you should realise that on some platforms (such as Windows, via <a href=\"http://technet.microsoft.com/en-us/library/cc757457.aspx\" rel=\"noreferrer\">FontSubstitutes</a>), Helvetica is aliased to Arial. That might be the source of the problem. Try another font and see.</p>\n" }, { "answer_id": 181328, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 1, "selected": false, "text": "<p>element styles override global styles, so Chris Jester-Young is probably right and you don't actually have a Helvetica font; try a different font e.g. Courier or Times New Roman that you're certain exists</p>\n" }, { "answer_id": 181336, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 3, "selected": false, "text": "<p>What you've written should work, unless the problem is what Chris pointed out,</p>\n\n<p>When you get a pair of fonts for which this works correctly, you might consider that a better way of doing this would be to declare a class for the special links that somehow reminds yourself of <strong>why</strong> they need a separate font (maybe because you want them to be especially noticed?)</p>\n\n<pre><code>a { font-family: Arial; }\na .noticed { font-family: Helvetica; }\n</code></pre>\n\n<p>Then in HTML:</p>\n\n<pre><code>&lt;a class=\"noticed\" href=\"...\"&gt;...&lt;/a&gt;\n</code></pre>\n\n<p>Changing the font by creating a span tag around the link, or adding inline style to the link just smacks of the old days of <code>&lt;font&gt;</code> tags.</p>\n" }, { "answer_id": 181358, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 3, "selected": false, "text": "<p>Your first attempt</p>\n<pre><code> &lt;a href=&quot;...&quot; style=&quot;font-family: Helvetica;&quot;&gt;...&lt;/a&gt;\n</code></pre>\n<p>should have worked. Agree that you're probably missing a font. Inline styles have precedence over any other styles beside a user-defined style sheet. Here's the order of priorities for style definitions:</p>\n<ol>\n<li>User defined style</li>\n<li>Embedded or inline style sheet</li>\n<li>Internal style sheet</li>\n<li>External style sheet</li>\n<li>Browser default style</li>\n</ol>\n<p>Within a style sheet the priorities are as follows:</p>\n<ol>\n<li>Anything marked !important</li>\n<li><h1>id</h1>\n</li>\n<li>.class</li>\n<li>element</li>\n</ol>\n<p>In addition, you have the rule of greater specificity: <code>div a</code> overrides <code>a</code>.</p>\n<p>Here's <a href=\"http://monc.se/kitchen/38/cascading-order-and-inheritance-in-css\" rel=\"noreferrer\">a good article with more detail on the subject</a>.</p>\n<p>@Kip's suggestion is your best bet.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17216/" ]
In a nutshell, there's a global stylesheet: ``` a { font-family: Arial; } ``` I want to use a different font family for a particular link: ``` <a href="..." style="font-family: Helvetica;">...</a> ``` or ``` <span style="font-family: Helvetica;"><a href="...">...</a></span> ``` but nothing works. Is there an easy way to do this? P.S. I'm dynamically (via PHP) assign different fonts to different links, so creating a special class is not an option.
Unless you have a specific font named Helvetica, you should realise that on some platforms (such as Windows, via [FontSubstitutes](http://technet.microsoft.com/en-us/library/cc757457.aspx)), Helvetica is aliased to Arial. That might be the source of the problem. Try another font and see.
181,342
<p>What is the best way to automatically install an MSI file or installer .exe? We want to do some automated testing from our build system on the installed copy of the product. Our installer has the usual license acceptance screen, install location, etc.</p> <hr> <p>As FryHard pointed out there are two options in particular that seem handy:</p> <ul> <li>"/quiet" - no use interaction</li> <li>"/passive" - process bar only, unattended mode</li> </ul>
[ { "answer_id": 181365, "author": "FryHard", "author_id": 231, "author_profile": "https://Stackoverflow.com/users/231", "pm_score": 4, "selected": false, "text": "<p>If you head over to one of your MSI packages in the command prompt and run a:</p>\n\n<pre><code>Myproduct.MSI /?\n</code></pre>\n\n<p>A screen will pop up with all the details of command line parameters that you can pass to the MSI. I am sure that in this way you could install your application via a command prompt and in this way automate it.</p>\n" }, { "answer_id": 181434, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 6, "selected": true, "text": "<p>To automate the installation of an MSI package, you can use the /I option, like this:</p>\n\n<pre><code>msiexec.exe /qn /i mypackage.msi\n</code></pre>\n\n<p>Keep in mind that you need to specify the properties the MSI package expect the user to specify through the UI, and for which it does not have a default value.</p>\n\n<p>You can use the <a href=\"http://msdn.microsoft.com/en-us/library/aa370557(v=vs.85).aspx\" rel=\"nofollow noreferrer\">Orca tool</a> to see the list of properties and fiddle around with MSI conditions, etc. And to set values for the properties, you can just specify it in command line; e.g. to set a property ISDEBUG:</p>\n\n<p><code>msiexec.exe /qn /i mypackage.msi ISDEBUG=1</code></p>\n\n<p><strong>Side note</strong>: To automate uninstall, use the /X option with the package or the product code:</p>\n\n<pre><code>msiexec.exe /qn /x mypackage.msi\n</code></pre>\n\n<p>or this (where you need to change the CLSID with your product code):</p>\n\n<pre><code>msiexec.exe /qn /x {B741B8A3-8DCB-44E0-B06F-2A11F56572DB}\n</code></pre>\n" }, { "answer_id": 9828896, "author": "hyeomans", "author_id": 122847, "author_profile": "https://Stackoverflow.com/users/122847", "pm_score": 0, "selected": false, "text": "<p>Is not released yet but could work for future references.</p>\n\n<p><a href=\"http://www.paulstovell.com/octopus/intro\" rel=\"nofollow\">http://www.paulstovell.com/octopus/intro</a></p>\n\n<p>Auto-deployment with nugget packages.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18437/" ]
What is the best way to automatically install an MSI file or installer .exe? We want to do some automated testing from our build system on the installed copy of the product. Our installer has the usual license acceptance screen, install location, etc. --- As FryHard pointed out there are two options in particular that seem handy: * "/quiet" - no use interaction * "/passive" - process bar only, unattended mode
To automate the installation of an MSI package, you can use the /I option, like this: ``` msiexec.exe /qn /i mypackage.msi ``` Keep in mind that you need to specify the properties the MSI package expect the user to specify through the UI, and for which it does not have a default value. You can use the [Orca tool](http://msdn.microsoft.com/en-us/library/aa370557(v=vs.85).aspx) to see the list of properties and fiddle around with MSI conditions, etc. And to set values for the properties, you can just specify it in command line; e.g. to set a property ISDEBUG: `msiexec.exe /qn /i mypackage.msi ISDEBUG=1` **Side note**: To automate uninstall, use the /X option with the package or the product code: ``` msiexec.exe /qn /x mypackage.msi ``` or this (where you need to change the CLSID with your product code): ``` msiexec.exe /qn /x {B741B8A3-8DCB-44E0-B06F-2A11F56572DB} ```
181,344
<p>We get sometimes the following error from our partner's database:</p> <pre><code>&lt;i&gt;ORA-01438: value larger than specified precision allows for this column&lt;/i&gt; </code></pre> <p>The full response looks like the following:</p> <pre><code>&lt;?xml version="1.0" encoding="windows-1251"?&gt; &lt;response&gt; &lt;status_code&gt;&lt;/status_code&gt; &lt;error_text&gt;ORA-01438: value larger than specified precision allows for this column ORA-06512: at &amp;quot;UMAIN.PAY_NET_V1_PKG&amp;quot;, line 176 ORA-06512: at line 1&lt;/error_text&gt; &lt;pay_id&gt;5592988&lt;/pay_id&gt; &lt;time_stamp&gt;&lt;/time_stamp&gt; &lt;/response&gt; </code></pre> <p>What can be the cause for this error?</p>
[ { "answer_id": 181355, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 2, "selected": false, "text": "<p>This indicates you are trying to put something too big into a column. For example, you have a VARCHAR2(10) column and you are putting in 11 characters. Same thing with number.</p>\n\n<p>This is happening at line 176 of package UMAIN. You would need to go and have a look at that to see what it is up to. Hopefully you can look it up in your source control (or from user_source). Later versions of Oracle report this error better, telling you which column and what value.</p>\n" }, { "answer_id": 181403, "author": "Thorsten", "author_id": 25320, "author_profile": "https://Stackoverflow.com/users/25320", "pm_score": 3, "selected": false, "text": "<p>The error seems not to be one of a character field, but more of a numeric one. (If it were a string problem like WW mentioned, you'd get a 'value too big' or something similar.) Probably you are using more digits than are allowed, e.g. 1,000000001 in a column defined as number (10,2).</p>\n\n<p>Look at the source code as WW mentioned to figure out what column may be causing the problem. Then check the data if possible that is being used there.</p>\n" }, { "answer_id": 181439, "author": "Robert Gould", "author_id": 15124, "author_profile": "https://Stackoverflow.com/users/15124", "pm_score": 1, "selected": false, "text": "<p>One issue I've had, and it was horribly tricky, was that the OCI call to describe a column attributes behaves diffrently depending on Oracle versions. Describing a simple NUMBER column created without any prec or scale returns differenlty on 9i, 1Og and 11g</p>\n" }, { "answer_id": 181588, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 2, "selected": false, "text": "<p>Further to previous answers, you should note that a column defined as VARCHARS(10) will store 10 <strong>bytes</strong>, not 10 characters unless you define it as VARCHAR2(10 CHAR)</p>\n\n<p>[The OP's question seems to be number related... this is just in case anyone else has a similar issue]</p>\n" }, { "answer_id": 182917, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 1, "selected": false, "text": "<p>From <a href=\"http://ora-01438.ora-code.com/\" rel=\"nofollow noreferrer\">http://ora-01438.ora-code.com/</a> (the definitive resource outside of Oracle Support):</p>\n\n<p><em>ORA-01438</em>: value larger than specified precision allowed for this column<br>\n<strong>Cause</strong>: When inserting or updating records, a numeric value was entered that exceeded the precision defined for the column.<br>\n<strong>Action</strong>: Enter a value that complies with the numeric column's precision, or use the MODIFY option with the ALTER TABLE command to expand the precision.</p>\n\n<p><a href=\"http://ora-06512.ora-code.com/\" rel=\"nofollow noreferrer\">http://ora-06512.ora-code.com/</a>:</p>\n\n<p><em>ORA-06512</em>: at stringline string<br>\n<strong>Cause</strong>: Backtrace message as the stack is unwound by unhandled exceptions.<br>\n<strong>Action</strong>: Fix the problem causing the exception or write an exception handler for this condition. Or you may need to contact your application administrator or DBA.</p>\n" }, { "answer_id": 2741455, "author": "Gary Myers", "author_id": 25714, "author_profile": "https://Stackoverflow.com/users/25714", "pm_score": 4, "selected": false, "text": "<p>The number you are trying to store is too big for the field. Look at the SCALE and PRECISION. The difference between the two is the number of digits ahead of the decimal place that you can store.</p>\n\n<pre><code>select cast (10 as number(1,2)) from dual\n *\nERROR at line 1:\nORA-01438: value larger than specified precision allowed for this column\n\nselect cast (15.33 as number(3,2)) from dual\n *\nERROR at line 1:\nORA-01438: value larger than specified precision allowed for this column\n</code></pre>\n\n<p>Anything at the lower end gets truncated (silently) </p>\n\n<pre><code>select cast (5.33333333 as number(3,2)) from dual;\nCAST(5.33333333ASNUMBER(3,2))\n-----------------------------\n 5.33\n</code></pre>\n" }, { "answer_id": 2741885, "author": "gokhant", "author_id": 48479, "author_profile": "https://Stackoverflow.com/users/48479", "pm_score": 1, "selected": false, "text": "<p>It might be a good practice to define variables like below:</p>\n\n<pre><code>v_departmentid departments.department_id%TYPE;\n</code></pre>\n\n<p>NOT like below:</p>\n\n<pre><code>v_departmentid NUMBER(4)\n</code></pre>\n" }, { "answer_id": 38057563, "author": "Priyome", "author_id": 5773913, "author_profile": "https://Stackoverflow.com/users/5773913", "pm_score": 2, "selected": false, "text": "<p>FYI:\nNumeric field size violations will give\nORA-01438: value larger than specified precision allowed for this column</p>\n\n<p>VARCHAR2 field length violations will give\nORA-12899: value too large for column...</p>\n\n<p>Oracle makes a distinction between the data types of the column based on the error code and message.</p>\n" }, { "answer_id": 70695612, "author": "David Gausmann", "author_id": 1800813, "author_profile": "https://Stackoverflow.com/users/1800813", "pm_score": 0, "selected": false, "text": "<p>It is also possible to get this error code, if you are using PHP and bound integer variables (oci_bind_by_name with SQLT_INT).\nIf you try to insert NULL via the bound variable, then you get this error or sometimes the value 2 is inserted (which is even more worse).</p>\n<p>To solve this issue, you must bind the variable as string (SQLT_CHR) with fixed length instead. Before inserting NULL must be converted into an empty string (equals to NULL in Oracle) and all other integer values must be converted into its string representation.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11104/" ]
We get sometimes the following error from our partner's database: ``` <i>ORA-01438: value larger than specified precision allows for this column</i> ``` The full response looks like the following: ``` <?xml version="1.0" encoding="windows-1251"?> <response> <status_code></status_code> <error_text>ORA-01438: value larger than specified precision allows for this column ORA-06512: at &quot;UMAIN.PAY_NET_V1_PKG&quot;, line 176 ORA-06512: at line 1</error_text> <pay_id>5592988</pay_id> <time_stamp></time_stamp> </response> ``` What can be the cause for this error?
The number you are trying to store is too big for the field. Look at the SCALE and PRECISION. The difference between the two is the number of digits ahead of the decimal place that you can store. ``` select cast (10 as number(1,2)) from dual * ERROR at line 1: ORA-01438: value larger than specified precision allowed for this column select cast (15.33 as number(3,2)) from dual * ERROR at line 1: ORA-01438: value larger than specified precision allowed for this column ``` Anything at the lower end gets truncated (silently) ``` select cast (5.33333333 as number(3,2)) from dual; CAST(5.33333333ASNUMBER(3,2)) ----------------------------- 5.33 ```
181,348
<p>Let me start with a specific example of what I'm trying to do.</p> <p>I have an array of year, month, day, hour, minute, second and millisecond components in the form <code>[ 2008, 10, 8, 00, 16, 34, 254 ]</code>. I'd like to instantiate a Date object using the following standard constructor:</p> <pre><code>new Date(year, month, date [, hour, minute, second, millisecond ]) </code></pre> <p>How can I pass my array to this constructor to get a new Date instance? <em>[ <strong>Update</strong>: My question actually extends beyond this specific example. I'd like a general solution for built-in JavaScript classes like Date, Array, RegExp, etc. whose constructors are beyond my reach. ]</em></p> <p>I'm trying to do something like the following:</p> <pre><code>var comps = [ 2008, 10, 8, 00, 16, 34, 254 ]; var d = Date.prototype.constructor.apply(this, comps); </code></pre> <p>I probably need a "<code>new</code>" in there somewhere. The above just returns the current time as if I had called "<code>(new Date()).toString()</code>". I also acknowledge that I may be completely in the wrong direction with the above :)</p> <p><strong><em>Note</strong>: No <code>eval()</code> and no accessing the array items one by one, please. I'm pretty sure I should be able to use the array as is.</em></p> <hr> <h2>Update: Further Experiments</h2> <p>Since no one has been able to come up with a working answer yet, I've done more playing around. Here's a new discovery.</p> <p>I can do this with my own class:</p> <pre><code>function Foo(a, b) { this.a = a; this.b = b; this.toString = function () { return this.a + this.b; }; } var foo = new Foo(1, 2); Foo.prototype.constructor.apply(foo, [4, 8]); document.write(foo); // Returns 12 -- yay! </code></pre> <p>But it doesn't work with the intrinsic Date class:</p> <pre><code>var d = new Date(); Date.prototype.constructor.call(d, 1000); document.write(d); // Still returns current time :( </code></pre> <p>Neither does it work with Number:</p> <pre><code>var n = new Number(42); Number.prototype.constructor.call(n, 666); document.write(n); // Returns 42 </code></pre> <p>Maybe this just isn't possible with intrinsic objects? I'm testing with Firefox BTW.</p>
[ { "answer_id": 181680, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 3, "selected": false, "text": "<p>This is how you might solve the specific case:-</p>\n\n<pre><code>function writeLn(s)\n{\n //your code to write a line to stdout\n WScript.Echo(s)\n}\n\nvar a = [ 2008, 10, 8, 00, 16, 34, 254 ]\n\nvar d = NewDate.apply(null, a)\n\nfunction NewDate(year, month, date, hour, minute, second, millisecond)\n{\n return new Date(year, month, date, hour, minute, second, millisecond);\n}\n\nwriteLn(d)\n</code></pre>\n\n<p>However you are looking for a more general solution. The recommended code for creating a constructor method is to have it <code>return this</code>.</p>\n\n<p>Hence:-</p>\n\n<pre><code>function Target(x , y) { this.x = x, this.y = y; return this; }\n</code></pre>\n\n<p>could be constructed :-</p>\n\n<pre><code>var x = Target.apply({}, [1, 2]);\n</code></pre>\n\n<p>However not all implementations work this way not least because the prototype chain would be wrong:-</p>\n\n<pre><code>var n = {};\nTarget.prototype = n;\nvar x = Target.apply({}, [1, 2]);\nvar b = n.isPrototypeOf(x); // returns false\nvar y = new Target(3, 4);\nb = n.isPrototypeOf(y); // returns true\n</code></pre>\n" }, { "answer_id": 181732, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": -1, "selected": false, "text": "<p>Edited</p>\n\n<p>Sorry, I was sure I made it that way years ago, right now I'll stick to:</p>\n\n<p>var d = new Date(comps[0],comps[1],comps[2],comps[3],comps[4],comps[5],comps[6]);</p>\n\n<p>Edit:</p>\n\n<p>But do remember that a javascript Date-object uses indexes for months, so the above array means</p>\n\n<p>November 8 2008 00:16:34:254</p>\n" }, { "answer_id": 184640, "author": "harley.333", "author_id": 26259, "author_profile": "https://Stackoverflow.com/users/26259", "pm_score": -1, "selected": false, "text": "<pre><code>var comps = [ 2008, 10, 8, 00, 16, 34, 254 ];\nvar d = eval(\"new Date(\" + comps.join(\",\") + \");\");\n</code></pre>\n" }, { "answer_id": 217042, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 7, "selected": true, "text": "<p>I've done more investigation of my own and came up with the conclusion that <strong>this is an impossible feat</strong>, due to how the Date class is implemented.</p>\n\n<p>I've inspected the <a href=\"http://www.mozilla.org/js/spidermonkey/\" rel=\"noreferrer\">SpiderMonkey</a> source code to see how Date was implemented. I think it all boils down to the following few lines:</p>\n\n<pre><code>static JSBool\nDate(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)\n{\n jsdouble *date;\n JSString *str;\n jsdouble d;\n\n /* Date called as function. */\n if (!(cx-&gt;fp-&gt;flags &amp; JSFRAME_CONSTRUCTING)) {\n int64 us, ms, us2ms;\n jsdouble msec_time;\n\n /* NSPR 2.0 docs say 'We do not support PRMJ_NowMS and PRMJ_NowS',\n * so compute ms from PRMJ_Now.\n */\n us = PRMJ_Now();\n JSLL_UI2L(us2ms, PRMJ_USEC_PER_MSEC);\n JSLL_DIV(ms, us, us2ms);\n JSLL_L2D(msec_time, ms);\n\n return date_format(cx, msec_time, FORMATSPEC_FULL, rval);\n }\n\n /* Date called as constructor. */\n // ... (from here on it checks the arg count to decide how to create the date)\n</code></pre>\n\n<p>When Date is used as a function (either as <code>Date()</code> or <code>Date.prototype.constructor()</code>, which are exactly the same thing), it defaults to returning the current time as a string in the locale format. This is regardless of any arguments that are passed in:</p>\n\n<pre><code>alert(Date()); // Returns \"Thu Oct 09 2008 23:15:54 ...\"\nalert(typeof Date()); // Returns \"string\"\n\nalert(Date(42)); // Same thing, \"Thu Oct 09 2008 23:15:54 ...\"\nalert(Date(2008, 10, 10)); // Ditto\nalert(Date(null)); // Just doesn't care\n</code></pre>\n\n<p>I don't think there's anything that can be done at the JS level to circumvent this. And this is probably the end of my pursuit in this topic.</p>\n\n<p>I've also noticed something interesting:</p>\n\n<pre><code> /* Set the value of the Date.prototype date to NaN */\n proto_date = date_constructor(cx, proto);\n if (!proto_date)\n return NULL;\n *proto_date = *cx-&gt;runtime-&gt;jsNaN;\n</code></pre>\n\n<p><code>Date.prototype</code> is a Date instance with the internal value of <code>NaN</code> and therefore,</p>\n\n<pre><code>alert(Date.prototype); // Always returns \"Invalid Date\"\n // on Firefox, Opera, Safari, Chrome\n // but not Internet Explorer\n</code></pre>\n\n<p>IE doesn't disappoint us. It does things a bit differently and probably sets the internal value to <code>-1</code> so that Date.prototype always returns a date slightly before epoch.</p>\n\n<hr>\n\n<h2>Update</h2>\n\n<p>I've finally dug into ECMA-262 itself and it turns out, what I'm trying to achieve (with the Date object) is -- by definition -- not possible:</p>\n\n<blockquote>\n <p><strong>15.9.2 The Date Constructor Called as a Function</strong></p>\n \n <p>When Date is called as a\n function rather than as a constructor,\n it returns a string representing the\n current time (UTC).</p>\n \n <p><strong>NOTE</strong> The function\n call <code>Date(…)</code> is not equivalent to the\n object creation expression <code>new Date(…)</code>\n with the same arguments.</p>\n \n <p><strong>15.9.2.1 Date ( [ year [, month [, date [, hours [, minutes [, seconds [,\n ms ] ] ] ] ] ] ] )</strong></p>\n \n <p>All of the\n arguments are optional; any arguments\n supplied are accepted but are\n completely ignored. A string is\n created and returned as if by the\n expression <code>(new Date()).toString()</code>.</p>\n</blockquote>\n" }, { "answer_id": 767062, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>It's less than elegant, but here's a solution:</p>\n\n<pre><code>function GeneratedConstructor (methodName, argumentCount) {\n var params = []\n\n for (var i = 0; i &lt; argumentCount; i++) {\n params.push(\"arguments[\" + i + \"]\")\n }\n\n var code = \"return new \" + methodName + \"(\" + params.join(\",\") + \")\"\n\n var ctor = new Function(code)\n\n this.createObject = function (params) {\n return ctor.apply(this, params)\n }\n}\n</code></pre>\n\n<p>The way this works should be pretty obvious. It creates a function through code generation. This example has a fixed number of parameters for each constructor you create, but that's useful anyway. Most of the time you have atleast a maximum number of arguments in mind. This also is better than some of the other examples here because it allows you to generate the code once and then re-use it. The code that's generated takes advantage of the variable-argument feature of javascript, this way you can avoid having to name each parameter (or spell them out in a list and pass the arguments in to the function you generate). Here's a working example:</p>\n\n<pre><code>var dateConstructor = new GeneratedConstructor(\"Date\", 3)\ndateConstructor.createObject( [ 1982, 03, 23 ] )\n</code></pre>\n\n<p>This will return the following:</p>\n\n<blockquote>\n <p>Fri Apr 23 1982 00:00:00 GMT-0800 (PST)</p>\n</blockquote>\n\n<p>It is indeed still...a bit ugly. But it atleast conveniently hides the mess and doesn't assume that compiled code itself can get garbage collected (since that may depend on the implementation and is a likely area for bugs).</p>\n\n<p>Cheers,\n Scott S. McCoy</p>\n" }, { "answer_id": 1168058, "author": "Cowboy Ben Alman", "author_id": 142339, "author_profile": "https://Stackoverflow.com/users/142339", "pm_score": 4, "selected": false, "text": "<p>I'd hardly call this elegant, but in my testing (FF3, Saf4, IE8) it works:</p>\n\n<p><code>var arr = [ 2009, 6, 22, 10, 30, 9 ];</code></p>\n\n<p>Instead of this:</p>\n\n<p><code>var d = new Date( arr[0], arr[1], arr[2], arr[3], arr[4], arr[5] );</code></p>\n\n<p>Try this:</p>\n\n<p><code>var d = new Date( Date.UTC.apply( window, arr ) + ( (new Date()).getTimezoneOffset() * 60000 ) );</code></p>\n" }, { "answer_id": 2278664, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 0, "selected": false, "text": "<p>You can do it with flagrant, <strong>flagrant</strong> abuse of eval:</p>\n\n<pre><code>var newwrapper = function (constr, args) {\n var argHolder = {\"c\": constr};\n for (var i=0; i &lt; args.length; i++) {\n argHolder[\"$\" + i] = args[i];\n }\n\n var newStr = \"new (argHolder['c'])(\";\n for (var i=0; i &lt; args.length; i++) {\n newStr += \"argHolder['$\" + i + \"']\";\n if (i != args.length - 1) newStr += \", \";\n }\n newStr += \");\";\n\n return eval(newStr);\n}\n</code></pre>\n\n<p>sample usage:</p>\n\n<pre><code>function Point(x,y) {\n this.x = x;\n this.y = y;\n}\nvar p = __new(Point, [10, 20]);\nalert(p.x); //10\nalert(p instanceof Point); //true\n</code></pre>\n\n<p>enjoy =). </p>\n" }, { "answer_id": 5556039, "author": "Michael Ficarra", "author_id": 693451, "author_profile": "https://Stackoverflow.com/users/693451", "pm_score": -1, "selected": false, "text": "<p>I know it's been a long time, but I have the real answer to this question. This is far from impossible. See <a href=\"https://gist.github.com/747650\" rel=\"nofollow\">https://gist.github.com/747650</a> for a generic solution.</p>\n\n<pre><code>var F = function(){};\nF.prototype = Date.prototype;\nvar d = new F();\nDate.apply(d, comps);\n</code></pre>\n" }, { "answer_id": 11762669, "author": "Quadroid", "author_id": 1279497, "author_profile": "https://Stackoverflow.com/users/1279497", "pm_score": -1, "selected": false, "text": "<p>Here is another solution:</p>\n\n<pre><code>function createInstance(Constructor, args){\n var TempConstructor = function(){};\n TempConstructor.prototype = Constructor.prototype;\n var instance = new TempConstructor;\n var ret = Constructor.apply(instance, args);\n return ret instanceof Object ? ret : instance;\n}\n\nconsole.log( createInstance(Date, [2008, 10, 8, 00, 16, 34, 254]) )\n</code></pre>\n" }, { "answer_id": 14376325, "author": "kybernetikos", "author_id": 412335, "author_profile": "https://Stackoverflow.com/users/412335", "pm_score": 2, "selected": false, "text": "<p>This is how you do it:</p>\n\n<pre><code>function applyToConstructor(constructor, argArray) {\n var args = [null].concat(argArray);\n var factoryFunction = constructor.bind.apply(constructor, args);\n return new factoryFunction();\n}\n\nvar d = applyToConstructor(Date, [2008, 10, 8, 00, 16, 34, 254]);\n</code></pre>\n\n<p>It will work with any constructor, not just built-ins or constructors that can double as functions (like Date).</p>\n\n<p>However it does require the Ecmascript 5 .bind function. Shims will probably not work correctly.</p>\n\n<p>By the way, one of the other answers suggests returning <code>this</code> out of a constructor. That can make it very difficult to extend the object using classical inheritance, so I would consider it an antipattern.</p>\n" }, { "answer_id": 31047577, "author": "ZERONETA", "author_id": 5048404, "author_profile": "https://Stackoverflow.com/users/5048404", "pm_score": 0, "selected": false, "text": "<pre><code>function gettime()\n{\n var q = new Date;\n arguments.length &amp;&amp; q.setTime( ( arguments.length === 1\n ? typeof arguments[0] === 'number' ? arguments[0] : Date.parse( arguments[0] )\n : Date.UTC.apply( null, arguments ) ) + q.getTimezoneOffset() * 60000 );\n return q;\n};\n\ngettime(2003,8,16)\n\ngettime.apply(null,[2003,8,16])\n</code></pre>\n" }, { "answer_id": 49437744, "author": "Wysher", "author_id": 9537039, "author_profile": "https://Stackoverflow.com/users/9537039", "pm_score": 1, "selected": false, "text": "<p>It will work with ES6 spread operator.\nYou simply:</p>\n\n<pre><code>const arr = [2018, 6, 15, 12, 30, 30, 500];\nconst date = new Date(...arr);\n\nconsole.log(date);\n</code></pre>\n" }, { "answer_id": 51645182, "author": "Scott Rudiger", "author_id": 8550747, "author_profile": "https://Stackoverflow.com/users/8550747", "pm_score": 2, "selected": false, "text": "<p>With ES6 syntax, there's at least 2 methods to achieve this:</p>\n\n<ul>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\">Spread Operator</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/construct\" rel=\"nofollow noreferrer\">Reflect.construct</a></li>\n</ul>\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 comps = [ 2008, 10, 8, 00, 16, 34, 254 ];\r\n\r\n// with the spread operator\r\nvar d1 = new Date(...comps);\r\n\r\n// with Reflect.construct\r\nvar d2 = Reflect.construct(Date, comps);\r\n\r\nconsole.log('d1:', d1, '\\nd2:', d2);\r\n// or more readable:\r\nconsole.log(`d1: ${d1}\\nd2: ${d2}`);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23501/" ]
Let me start with a specific example of what I'm trying to do. I have an array of year, month, day, hour, minute, second and millisecond components in the form `[ 2008, 10, 8, 00, 16, 34, 254 ]`. I'd like to instantiate a Date object using the following standard constructor: ``` new Date(year, month, date [, hour, minute, second, millisecond ]) ``` How can I pass my array to this constructor to get a new Date instance? *[ **Update**: My question actually extends beyond this specific example. I'd like a general solution for built-in JavaScript classes like Date, Array, RegExp, etc. whose constructors are beyond my reach. ]* I'm trying to do something like the following: ``` var comps = [ 2008, 10, 8, 00, 16, 34, 254 ]; var d = Date.prototype.constructor.apply(this, comps); ``` I probably need a "`new`" in there somewhere. The above just returns the current time as if I had called "`(new Date()).toString()`". I also acknowledge that I may be completely in the wrong direction with the above :) ***Note***: No `eval()` and no accessing the array items one by one, please. I'm pretty sure I should be able to use the array as is. --- Update: Further Experiments --------------------------- Since no one has been able to come up with a working answer yet, I've done more playing around. Here's a new discovery. I can do this with my own class: ``` function Foo(a, b) { this.a = a; this.b = b; this.toString = function () { return this.a + this.b; }; } var foo = new Foo(1, 2); Foo.prototype.constructor.apply(foo, [4, 8]); document.write(foo); // Returns 12 -- yay! ``` But it doesn't work with the intrinsic Date class: ``` var d = new Date(); Date.prototype.constructor.call(d, 1000); document.write(d); // Still returns current time :( ``` Neither does it work with Number: ``` var n = new Number(42); Number.prototype.constructor.call(n, 666); document.write(n); // Returns 42 ``` Maybe this just isn't possible with intrinsic objects? I'm testing with Firefox BTW.
I've done more investigation of my own and came up with the conclusion that **this is an impossible feat**, due to how the Date class is implemented. I've inspected the [SpiderMonkey](http://www.mozilla.org/js/spidermonkey/) source code to see how Date was implemented. I think it all boils down to the following few lines: ``` static JSBool Date(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { jsdouble *date; JSString *str; jsdouble d; /* Date called as function. */ if (!(cx->fp->flags & JSFRAME_CONSTRUCTING)) { int64 us, ms, us2ms; jsdouble msec_time; /* NSPR 2.0 docs say 'We do not support PRMJ_NowMS and PRMJ_NowS', * so compute ms from PRMJ_Now. */ us = PRMJ_Now(); JSLL_UI2L(us2ms, PRMJ_USEC_PER_MSEC); JSLL_DIV(ms, us, us2ms); JSLL_L2D(msec_time, ms); return date_format(cx, msec_time, FORMATSPEC_FULL, rval); } /* Date called as constructor. */ // ... (from here on it checks the arg count to decide how to create the date) ``` When Date is used as a function (either as `Date()` or `Date.prototype.constructor()`, which are exactly the same thing), it defaults to returning the current time as a string in the locale format. This is regardless of any arguments that are passed in: ``` alert(Date()); // Returns "Thu Oct 09 2008 23:15:54 ..." alert(typeof Date()); // Returns "string" alert(Date(42)); // Same thing, "Thu Oct 09 2008 23:15:54 ..." alert(Date(2008, 10, 10)); // Ditto alert(Date(null)); // Just doesn't care ``` I don't think there's anything that can be done at the JS level to circumvent this. And this is probably the end of my pursuit in this topic. I've also noticed something interesting: ``` /* Set the value of the Date.prototype date to NaN */ proto_date = date_constructor(cx, proto); if (!proto_date) return NULL; *proto_date = *cx->runtime->jsNaN; ``` `Date.prototype` is a Date instance with the internal value of `NaN` and therefore, ``` alert(Date.prototype); // Always returns "Invalid Date" // on Firefox, Opera, Safari, Chrome // but not Internet Explorer ``` IE doesn't disappoint us. It does things a bit differently and probably sets the internal value to `-1` so that Date.prototype always returns a date slightly before epoch. --- Update ------ I've finally dug into ECMA-262 itself and it turns out, what I'm trying to achieve (with the Date object) is -- by definition -- not possible: > > **15.9.2 The Date Constructor Called as a Function** > > > When Date is called as a > function rather than as a constructor, > it returns a string representing the > current time (UTC). > > > **NOTE** The function > call `Date(…)` is not equivalent to the > object creation expression `new Date(…)` > with the same arguments. > > > **15.9.2.1 Date ( [ year [, month [, date [, hours [, minutes [, seconds [, > ms ] ] ] ] ] ] ] )** > > > All of the > arguments are optional; any arguments > supplied are accepted but are > completely ignored. A string is > created and returned as if by the > expression `(new Date()).toString()`. > > >
181,354
<p>In a Test project in Visual Studio 2008 (Pro), I created a Test project, and I want to configure the project properties to give a command line argument to the tests. I set the properties, but then realized I have no idea how to actually use the argument. </p> <p>How do you get the arguments from MSTest?</p>
[ { "answer_id": 181375, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 0, "selected": false, "text": "<p>Perhaps you can use <a href=\"http://msdn.microsoft.com/en-us/library/ms683156(VS.85).aspx\" rel=\"nofollow noreferrer\">GetCommandLine</a>().</p>\n\n<p>Edit: GetCommandLine() is a win32-function, but there ought to be a corresponding .Net function for it.</p>\n" }, { "answer_id": 181404, "author": "JTew", "author_id": 25372, "author_profile": "https://Stackoverflow.com/users/25372", "pm_score": 2, "selected": true, "text": "<p>VS 2008 test are compiled into DLLs which can't directly receive command line arguments as far as I know. </p>\n\n<p>You could add a configuration file 'app.config' for the dll and use that instead.</p>\n\n<p>Just beware, mstest only copies .config files for the test container being run at the time. </p>\n\n<p>if you have the following...</p>\n\n<pre><code>mytest.dll\nmytest.dll.config\nlib.dll\nlib.dll.config\n</code></pre>\n\n<p>and you reference lib.dll from mytest.dll, when you run the tests lib.dll.config will not get copied and your test may fail because of this.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3279/" ]
In a Test project in Visual Studio 2008 (Pro), I created a Test project, and I want to configure the project properties to give a command line argument to the tests. I set the properties, but then realized I have no idea how to actually use the argument. How do you get the arguments from MSTest?
VS 2008 test are compiled into DLLs which can't directly receive command line arguments as far as I know. You could add a configuration file 'app.config' for the dll and use that instead. Just beware, mstest only copies .config files for the test container being run at the time. if you have the following... ``` mytest.dll mytest.dll.config lib.dll lib.dll.config ``` and you reference lib.dll from mytest.dll, when you run the tests lib.dll.config will not get copied and your test may fail because of this.
181,356
<p>What am I doing wrong here?</p> <pre><code>string q = "john s!"; string clean = Regex.Replace(q, @"([^a-zA-Z0-9]|^\s)", string.Empty); // clean == "johns". I want "john s"; </code></pre>
[ { "answer_id": 181362, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 2, "selected": false, "text": "<p>I suspect ^ doesn't work the way you think it does outside of a character class.</p>\n\n<p>What you're telling it to do is replace everything that isn't an alphanumeric with an empty string, OR any leading space. I think what you mean to say is that spaces are ok to not replace - try moving the \\s into the [] class.</p>\n" }, { "answer_id": 181367, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 2, "selected": false, "text": "<p>There appear to be two problems.</p>\n\n<ol>\n<li>You're using the ^ outside a [] which matches the start of the line</li>\n<li>You're not using a * or + which means you will only match a single character.</li>\n</ol>\n\n<p>I think you want the following regex @\"([^a-zA-Z0-9\\s])+\"</p>\n" }, { "answer_id": 181369, "author": "Windows programmer", "author_id": 23705, "author_profile": "https://Stackoverflow.com/users/23705", "pm_score": 0, "selected": false, "text": "<p>The circumflex inside the square brackets means all characters except the subsequent range. You want a circumflex outside of square brackets.</p>\n" }, { "answer_id": 181371, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 4, "selected": false, "text": "<p>I got it:</p>\n\n<pre><code>string clean = Regex.Replace(q, @\"[^a-zA-Z0-9\\s]\", string.Empty);\n</code></pre>\n\n<p>Didn't know you could put \\s in the brackets</p>\n" }, { "answer_id": 6628211, "author": "Evolved", "author_id": 766028, "author_profile": "https://Stackoverflow.com/users/766028", "pm_score": 5, "selected": false, "text": "<p>This:</p>\n\n<pre><code>string clean = Regex.Replace(dirty, \"[^a-zA-Z0-9\\x20]\", String.Empty);\n</code></pre>\n\n<blockquote>\n <blockquote>\n <p><strong>\\x20</strong> is ascii hex for 'space' character</p>\n </blockquote>\n</blockquote>\n\n<p>you can add more individual characters that you want to be allowed.\nIf you want for example <strong>\"?\"</strong> to be ok in the return string add <strong>\\x3f</strong>.</p>\n" }, { "answer_id": 6794263, "author": "Tim", "author_id": 181971, "author_profile": "https://Stackoverflow.com/users/181971", "pm_score": 7, "selected": true, "text": "<p>just a FYI</p>\n\n<pre><code>string clean = Regex.Replace(q, @\"[^a-zA-Z0-9\\s]\", string.Empty);\n</code></pre>\n\n<p>would actually be better like</p>\n\n<pre><code>string clean = Regex.Replace(q, @\"[^\\w\\s]\", string.Empty);\n</code></pre>\n" }, { "answer_id": 13050834, "author": "vivek", "author_id": 1771426, "author_profile": "https://Stackoverflow.com/users/1771426", "pm_score": 3, "selected": false, "text": "<p>The following regex is for space inclusion in textbox.</p>\n\n<pre><code>Regex r = new Regex(\"^[a-zA-Z\\\\s]+\");\nr.IsMatch(textbox1.text);\n</code></pre>\n\n<p>This works fine for me. </p>\n" }, { "answer_id": 50996740, "author": "zamoldar", "author_id": 1036639, "author_profile": "https://Stackoverflow.com/users/1036639", "pm_score": 1, "selected": false, "text": "<p>bottom regex with space, supports all keyboard letters from different culture</p>\n\n<pre><code> string input = \"78-selim güzel667.,?\";\n Regex regex = new Regex(@\"[^\\w\\x20]|[\\d]\");\n var result= regex.Replace(input,\"\");\n //selim güzel\n</code></pre>\n" }, { "answer_id": 69391878, "author": "Paramjot Singh", "author_id": 11849033, "author_profile": "https://Stackoverflow.com/users/11849033", "pm_score": 0, "selected": false, "text": "<p>This regex will help you to filter if there is at least one alphanumeric character and zero or more special characters i.e. _ (underscore), \\s whitespace, -(hyphen)</p>\n<pre><code>string comparer = &quot;string you want to compare&quot;;\nRegex r = new Regex(@&quot;^([a-zA-Z0-9]+[_\\s-]*)+$&quot;);\n\nif (!r.IsMatch(comparer))\n{\n return false;\n} \nreturn true;\n</code></pre>\n<p>Create a set using <code>[a-zA-Z0-9]+</code> for alphanumeric characters, &quot;+&quot; sign (a quantifier) at the end of the set will make sure that there will be at least one alphanumeric character within the <code>comparer</code>.</p>\n<p>Create another set <code>[_\\s-]*</code> for special characters, &quot;*&quot; quantifier is to validate that there can be special characters within <code>comparer</code> string.</p>\n<p>Pack these sets into a capture group <code>([a-zA-Z0-9]+[_\\s-]*)+</code> to say that the <code>comparer</code> string should occupy these features.</p>\n" }, { "answer_id": 71333785, "author": "Waseem Raja Khan", "author_id": 18361896, "author_profile": "https://Stackoverflow.com/users/18361896", "pm_score": 0, "selected": false, "text": "<pre><code>[RegularExpression(@&quot;^[A-Z]+[a-zA-Z&quot;&quot;'\\s-]*$&quot;)]\n</code></pre>\n<p>Above syntax also accepts space</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1786/" ]
What am I doing wrong here? ``` string q = "john s!"; string clean = Regex.Replace(q, @"([^a-zA-Z0-9]|^\s)", string.Empty); // clean == "johns". I want "john s"; ```
just a FYI ``` string clean = Regex.Replace(q, @"[^a-zA-Z0-9\s]", string.Empty); ``` would actually be better like ``` string clean = Regex.Replace(q, @"[^\w\s]", string.Empty); ```
181,374
<p>I have a .net app that I've written in c#. On some forms I frequent update the display fields. In some cases every field on the form (textboxes, labels, picturebox, etc) has its value changed. Plus the frequency of the changes could possibly be every second. However, currently there is a horrible flickering everytime the form is updated. How can I stop the flickering? Is there a way to maybe double buffer? Please help! </p>
[ { "answer_id": 181382, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 1, "selected": false, "text": "<p>You didn't research this well. There is a DoubleBuffered property in every Form. Try setting that to true. If you havn't overloaded anything on the form painting, then everything should work.</p>\n" }, { "answer_id": 181384, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 3, "selected": false, "text": "<p>the short answer is</p>\n\n<pre><code>SetStyle(ControlStyles.OptimizedDoubleBuffer, true);\n</code></pre>\n\n<p>the long answer is: see <a href=\"http://msdn.microsoft.com/en-us/library/3t7htc9c(VS.80).aspx?ppud=4\" rel=\"nofollow noreferrer\">MSDN</a> or <a href=\"http://www.google.com/search?hl=en&amp;q=C%23+form+double+buffer&amp;aq=f&amp;oq=\" rel=\"nofollow noreferrer\">google</a></p>\n\n<p>just for fun, try calling Application.DoEvents() after each element is updated, and see if the problem gets better or worse ;-)</p>\n" }, { "answer_id": 181385, "author": "DaveK", "author_id": 4244, "author_profile": "https://Stackoverflow.com/users/4244", "pm_score": 0, "selected": false, "text": "<p>The ghosting is usually caused because you're running in a single thread and it's being held up with the field updates so the paint event doesnt fire. One way to fix this would be to put the heavy lifting in asynchronous methods. This will allow the form to repaint itself and update whatever is needed when they async method calls back.</p>\n" }, { "answer_id": 181386, "author": "FryHard", "author_id": 231, "author_profile": "https://Stackoverflow.com/users/231", "pm_score": 2, "selected": false, "text": "<p>You could try to call <strong>this.SuspendLayout();</strong> before you start your update and <strong>this.ResumeLayout(false);</strong> when you have finished setting all the values in this way it should prevent the form from writing values one at a time.</p>\n" }, { "answer_id": 181387, "author": "Toji", "author_id": 25968, "author_profile": "https://Stackoverflow.com/users/25968", "pm_score": 1, "selected": false, "text": "<p>You can <a href=\"http://www.codeproject.com/KB/graphics/DoubleBuffering.aspx\" rel=\"nofollow noreferrer\">double buffer</a> almost every windows forms control, although most of the time it requires that you inherit from the desired control and override a protected property. Be cautioned, though, that I've spent quite a bit of time on the same issue and I've yet to fully remove flicker on my more complex forms. </p>\n\n<p>If you want truly flicker-free windows, I suggest looking at WPF.</p>\n" }, { "answer_id": 213017, "author": "Brian Hasden", "author_id": 28926, "author_profile": "https://Stackoverflow.com/users/28926", "pm_score": 3, "selected": false, "text": "<p>This worked for me. </p>\n\n<p><a href=\"http://www.syncfusion.com/faq/windowsforms/search/558.aspx\" rel=\"noreferrer\">http://www.syncfusion.com/faq/windowsforms/search/558.aspx</a></p>\n\n<p>Basically it involves deriving from the desired control and setting the following styles.</p>\n\n<pre><code>SetStyle(ControlStyles.UserPaint, true);\nSetStyle(ControlStyles.AllPaintingInWmPaint, true); \nSetStyle(ControlStyles.DoubleBuffer, true); \n</code></pre>\n" }, { "answer_id": 1028847, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>i had the same problem with OpenGLES, which is how i found this thread.\nof course i realize u are not using ogl, but maybe this helps u anyway ;) </p>\n\n<p><code>protected override void OnPaintBackground(PaintEventArgs e) \n{\n}\n</code></p>\n" }, { "answer_id": 6512181, "author": "John Suit", "author_id": 416752, "author_profile": "https://Stackoverflow.com/users/416752", "pm_score": 2, "selected": false, "text": "<p>I know this question is old, but may be it will others searching for it in the future.</p>\n\n<p>DoubleBuffering doesn't always work well. To force the form to never flicker at all (but sometimes causes drawing issues):</p>\n\n<pre><code>protected override CreateParams CreateParams\n{\n get\n {\n CreateParams cp = base.CreateParams;\n cp.ExStyle |= 0x02000000; //WS_EX_COMPOSITED\n return cp;\n }\n}\n</code></pre>\n\n<p>To stop flickering when a user resizes a form, but without messing up the drawing of controls (provided your form name is \"Form1\"):</p>\n\n<pre><code>int intOriginalExStyle = -1;\nbool bEnableAntiFlicker = true;\n\npublic Form1()\n{\n ToggleAntiFlicker(false);\n InitializeComponent();\n this.ResizeBegin += new EventHandler(Form1_ResizeBegin);\n this.ResizeEnd += new EventHandler(Form1_ResizeEnd);\n}\n\nprotected override CreateParams CreateParams\n{\n get\n {\n if (intOriginalExStyle == -1)\n {\n intOriginalExStyle = base.CreateParams.ExStyle;\n }\n CreateParams cp = base.CreateParams;\n\n if (bEnableAntiFlicker)\n {\n cp.ExStyle |= 0x02000000; //WS_EX_COMPOSITED\n }\n else\n {\n cp.ExStyle = intOriginalExStyle;\n }\n\n return cp;\n }\n} \n\nprivate void Form1_ResizeBegin(object sender, EventArgs e)\n{\n ToggleAntiFlicker(true);\n}\n\nprivate void Form1_ResizeEnd(object sender, EventArgs e)\n{\n ToggleAntiFlicker(false);\n}\n\nprivate void ToggleAntiFlicker(bool Enable)\n{\n bEnableAntiFlicker = Enable;\n //hacky, but works\n this.MaximizeBox = true;\n}\n</code></pre>\n" }, { "answer_id": 6724577, "author": "Josip Medved", "author_id": 144245, "author_profile": "https://Stackoverflow.com/users/144245", "pm_score": 2, "selected": false, "text": "<p>You can just replace original control with custom one which has protected DoubleBuffered property to true. E.g. for ListView it would be something like this:</p>\n\n<pre><code>internal class DoubleBufferedListView : ListView {\n\n public DoubleBufferedListView()\n : base() {\n this.DoubleBuffered = true;\n }\n\n}\n</code></pre>\n\n<p>After that you just visit *.Designer.cs file and replace all mentions of native control with this one.</p>\n\n<p>P.S. Instead of inheriting from control you can also set this property via reflection:</p>\n\n<pre><code>listView1.GetType().GetProperty(\"DoubleBuffered\", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(lsvReport, true, null);\n</code></pre>\n\n<p>It is not clean nor recommended but it requires no changes in *.Designer.cs files.</p>\n" }, { "answer_id": 7005438, "author": "Kind Contributor", "author_id": 887092, "author_profile": "https://Stackoverflow.com/users/887092", "pm_score": 2, "selected": false, "text": "<p>It could also be caused by your coding, not the absence of doublebuffering. I came here just now with a similar problem but realised it's because:</p>\n\n<ol>\n<li>I set a frame to invisible when an item is not selected.</li>\n<li>In between user selections, the index is cleared by the ListView control.</li>\n<li>I'm bound to the SelectedIndexChanged event</li>\n</ol>\n\n<p>In other words:</p>\n\n<ul>\n<li>User clicks item 1 <br/>\n~ SelectedIndexChanged(1) <br/> </li>\n<li>User clicks item 2 <br/>\n~ SelectedIndexChanged(-1) &lt;---- This causes the flicker <br/>\n~ SelectedIndexChanged(2) <br/></li>\n</ul>\n\n<p>So what's the solution? <a href=\"https://stackoverflow.com/questions/86793/how-to-avoid-thousands-of-needless-listview-selectedindexchanged-events\">How to avoid thousands of needless ListView.SelectedIndexChanged events?</a></p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a .net app that I've written in c#. On some forms I frequent update the display fields. In some cases every field on the form (textboxes, labels, picturebox, etc) has its value changed. Plus the frequency of the changes could possibly be every second. However, currently there is a horrible flickering everytime the form is updated. How can I stop the flickering? Is there a way to maybe double buffer? Please help!
the short answer is ``` SetStyle(ControlStyles.OptimizedDoubleBuffer, true); ``` the long answer is: see [MSDN](http://msdn.microsoft.com/en-us/library/3t7htc9c(VS.80).aspx?ppud=4) or [google](http://www.google.com/search?hl=en&q=C%23+form+double+buffer&aq=f&oq=) just for fun, try calling Application.DoEvents() after each element is updated, and see if the problem gets better or worse ;-)
181,406
<p>I have been using Ruby for a while now and I find, for bigger projects, it can take up a fair amount of memory. What are some best practices for reducing memory usage in Ruby?</p> <ul> <li>Please, let each answer have one "best practice" and let the community vote it up.</li> </ul>
[ { "answer_id": 181433, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 3, "selected": false, "text": "<p>Beware of C extensions which allocate large chunks of memory themselves.</p>\n\n<p>As an example, when you load an image using RMagick, the entire bitmap gets loaded into memory inside the ruby process. This may be 30 meg or so depending on the size of the image.<br>\n<strong>However</strong>, most of this memory has been allocated by RMagick itself. All ruby knows about is a wrapper object, which is tiny(1).<br>\nRuby only thinks it's holding onto a tiny amount of memory, so it won't bother running the GC. In actual fact it's holding onto 30 meg.<br>\nIf you loop over a say 10 images, you can run yourself out of memory really fast.</p>\n\n<p>The preferred solution is to manually tell the C library to clean up the memory itself - RMagick has a destroy! method which does this. If your library doesn't however, you may need to forcibly run the GC yourself, even though this is generally discouraged.</p>\n\n<p>(1): Ruby C extensions have callbacks which will get run when the ruby runtime decides to free them, so the memory will eventually be successfully freed at some point, just perhaps not soon enough.</p>\n" }, { "answer_id": 181438, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 5, "selected": false, "text": "<p>Don't abuse symbols.</p>\n\n<p>Each time you create a symbol, ruby puts an entry in it's symbol table. The symbol table is a global hash which <em>never</em> gets emptied.<br>\nThis is not technically a memory leak, but it behaves like one. Symbols don't take up much memory so you don't need to be too paranoid, but it pays to be aware of this.</p>\n\n<p>A general guideline: If you've actually typed the symbol in code, it's fine (you only have a finite amount of code after all), but don't call to_sym on dynamically generated or user-input strings, as this opens the door to a potentially ever-increasing number</p>\n" }, { "answer_id": 181445, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 5, "selected": true, "text": "<p>Don't do this:</p>\n\n<pre><code>def method(x)\n x.split( doesn't matter what the args are )\nend\n</code></pre>\n\n<p>or this:</p>\n\n<pre><code>def method(x)\n x.gsub( doesn't matter what the args are )\nend\n</code></pre>\n\n<p><a href=\"http://groups.google.com/group/god-rb/browse_thread/thread/1cca2b7c4a581c2/f0f040d41d7c49ea\" rel=\"nofollow noreferrer\">Both will permanently leak memory in ruby 1.8.5 and 1.8.6</a>. (not sure about 1.8.7 as I haven't tried it, but I really hope it's fixed.) The workaround is stupid and involves creating a local variable. You don't have to use the local, just create one...</p>\n\n<p>Things like this are why I have lots of love for the ruby language, but no respect for MRI</p>\n" }, { "answer_id": 3764991, "author": "Alex Kovshovik", "author_id": 115680, "author_profile": "https://Stackoverflow.com/users/115680", "pm_score": 5, "selected": false, "text": "<p>When working with huge arrays of ActiveRecord objects be very careful... When processing those objects in a loop if on each iteration you are loading their related objects using ActiveRecord's has_many, belongs_to, etc. - the memory usage grows a lot because each object that belongs to an array grows...</p>\n\n<p>The following technique helped us a lot (<em>simplified example</em>):</p>\n\n<pre><code>students.each do |student|\n cloned_student = student.clone\n ...\n cloned_student.books.detect {...}\n ca_teachers = cloned_student.teachers.detect {|teacher| teacher.address.state == 'CA'}\n ca_teachers.blah_blah\n ...\n # Not sure if the following is necessary, but we have it just in case...\n cloned_student = nil\nend\n</code></pre>\n\n<p>In the code above \"cloned_student\" is the object that grows, but since it is \"nullified\" at the end of each iteration this is not a problem for huge array of students. If we didn't do \"clone\", the loop variable \"student\" would have grown, but since it belongs to an array - the memory used by it is never released as long as array object exists.</p>\n\n<p>Different approach works too:</p>\n\n<pre><code>students.each do |student|\n loop_student = Student.find(student.id) # just re-find the record into local variable.\n ...\n loop_student.books.detect {...}\n ca_teachers = loop_student.teachers.detect {|teacher| teacher.address.state == 'CA'}\n ca_teachers.blah_blah\n ...\nend\n</code></pre>\n\n<p>In our production environment we had a background process that failed to finish once because 8Gb of RAM wasn't enough for it. After this small change it uses less than 1Gb to process the same amount of data...</p>\n" }, { "answer_id": 39688765, "author": "Joshua Arvin Lat", "author_id": 4765343, "author_profile": "https://Stackoverflow.com/users/4765343", "pm_score": 0, "selected": false, "text": "<p><strong>Measure and detect which parts of your code are creating objects that cause memory usage to go up</strong>. Improve and modify your code then measure again. Sometimes, you're using gems or libraries that use up a lot of memory and creating a lot of objects as well.</p>\n\n<p>There are many tools out there such as <a href=\"https://github.com/joshualat/busy-administrator\" rel=\"nofollow\">busy-administrator</a> that allow you to check the memory size of objects (including those inside hashes and arrays).</p>\n\n<pre><code>$ gem install busy-administrator\n</code></pre>\n\n<h2>Example # 1: MemorySize.of</h2>\n\n<pre><code>require 'busy-administrator'\n\ndata = BusyAdministrator::ExampleGenerator.generate_string_with_specified_memory_size(10.mebibytes)\n\nputs BusyAdministrator::MemorySize.of(data)\n# =&gt; 10 MiB\n</code></pre>\n\n<h2>Example # 2: MemoryUtils.profile</h2>\n\n<h3>Code</h3>\n\n<pre><code>require 'busy-administrator'\n\nresults = BusyAdministrator::MemoryUtils.profile(gc_enabled: false) do |analyzer|\n BusyAdministrator::ExampleGenerator.generate_string_with_specified_memory_size(10.mebibytes)\nend \n\nBusyAdministrator::Display.debug(results)\n</code></pre>\n\n<h3>Output:</h3>\n\n<pre><code>{\n memory_usage:\n {\n before: 12 MiB\n after: 22 MiB\n diff: 10 MiB\n }\n total_time: 0.406452\n gc:\n {\n count: 0\n enabled: false\n }\n specific:\n {\n }\n object_count: 151\n general:\n {\n String: 10 MiB\n Hash: 8 KiB\n BusyAdministrator::MemorySize: 0 Bytes\n Process::Status: 0 Bytes\n IO: 432 Bytes\n Array: 326 KiB\n Proc: 72 Bytes\n RubyVM::Env: 96 Bytes\n Time: 176 Bytes\n Enumerator: 80 Bytes\n }\n}\n</code></pre>\n\n<p>You can also try <strong>ruby-prof</strong> and <strong>memory_profiler</strong>. It is better if you test and experiment different versions of your code so you can measure the memory usage and performance of each version. This will allow you to check if your optimization really worked or not. You usually use these tools in development / testing mode and turn them off in production.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5004/" ]
I have been using Ruby for a while now and I find, for bigger projects, it can take up a fair amount of memory. What are some best practices for reducing memory usage in Ruby? * Please, let each answer have one "best practice" and let the community vote it up.
Don't do this: ``` def method(x) x.split( doesn't matter what the args are ) end ``` or this: ``` def method(x) x.gsub( doesn't matter what the args are ) end ``` [Both will permanently leak memory in ruby 1.8.5 and 1.8.6](http://groups.google.com/group/god-rb/browse_thread/thread/1cca2b7c4a581c2/f0f040d41d7c49ea). (not sure about 1.8.7 as I haven't tried it, but I really hope it's fixed.) The workaround is stupid and involves creating a local variable. You don't have to use the local, just create one... Things like this are why I have lots of love for the ruby language, but no respect for MRI
181,408
<p>What is the best way to write bytes in the middle of a file using Java?</p>
[ { "answer_id": 181416, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 3, "selected": false, "text": "<p>Use <code>RandomAccessFile</code></p>\n\n<ul>\n<li><a href=\"http://java.sun.com/docs/books/tutorial/essential/io/rafs.html\" rel=\"nofollow noreferrer\">Tutorial</a> </li>\n<li><a href=\"http://java.sun.com/javase/6/docs/api/java/io/RandomAccessFile.html\" rel=\"nofollow noreferrer\">Javadocs</a> </li>\n</ul>\n" }, { "answer_id": 181417, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 0, "selected": false, "text": "<p>Open the file in write mode without truncating it, seek to the desired offset, and write the desired data. Just be careful about text/binary mode.</p>\n" }, { "answer_id": 185076, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 6, "selected": true, "text": "<p>Reading and Writing in the middle of a file is as simple as using a <a href=\"http://java.sun.com/javase/6/docs/api/java/io/RandomAccessFile.html\" rel=\"noreferrer\"><code>RandomAccessFile</code></a> in Java.</p>\n\n<p><a href=\"http://java.sun.com/javase/6/docs/api/java/io/RandomAccessFile.html\" rel=\"noreferrer\"><code>RandomAccessFile</code></a>, despite its name, is more like an <code>InputStream</code> and <code>OutputStream</code> and less like a <code>File</code>. It allows you to read or seek through <code>bytes</code> in a file and then begin writing over whichever bytes you care to stop at.</p>\n\n<p>Once you discover this class, it is very easy to use if you have a basic understanding of regular file i/o.</p>\n\n<p>A small example:</p>\n\n<pre><code>public static void aMethod(){\n RandomAccessFile f = new RandomAccessFile(new File(\"whereDidIPutTHatFile\"), \"rw\");\n long aPositionWhereIWantToGo = 99;\n f.seek(aPositionWhereIWantToGo); // this basically reads n bytes in the file\n f.write(\"Im in teh fil, writn bites\".getBytes());\n f.close();\n}\n</code></pre>\n" }, { "answer_id": 58824918, "author": "Master", "author_id": 3421640, "author_profile": "https://Stackoverflow.com/users/3421640", "pm_score": 0, "selected": false, "text": "<p>I think it’s best to create file chunks every time. And when the file is downloaded, connect them together. Now I'm working on it.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]
What is the best way to write bytes in the middle of a file using Java?
Reading and Writing in the middle of a file is as simple as using a [`RandomAccessFile`](http://java.sun.com/javase/6/docs/api/java/io/RandomAccessFile.html) in Java. [`RandomAccessFile`](http://java.sun.com/javase/6/docs/api/java/io/RandomAccessFile.html), despite its name, is more like an `InputStream` and `OutputStream` and less like a `File`. It allows you to read or seek through `bytes` in a file and then begin writing over whichever bytes you care to stop at. Once you discover this class, it is very easy to use if you have a basic understanding of regular file i/o. A small example: ``` public static void aMethod(){ RandomAccessFile f = new RandomAccessFile(new File("whereDidIPutTHatFile"), "rw"); long aPositionWhereIWantToGo = 99; f.seek(aPositionWhereIWantToGo); // this basically reads n bytes in the file f.write("Im in teh fil, writn bites".getBytes()); f.close(); } ```
181,413
<p>Before I begin, I want to clarify that this is not a command-line tool, but an application that accepts commands through it's own command-line interface.</p> <p><strong>Edit:</strong> I must apologize about my explanation from before, apparently I didn't do a very good job at explaining it. One more time...</p> <p>I am building a command-line interface application that accepts commands from a user. I have a signal handler setup to catch the signals, which then sets a flag that I need to terminate the application. The problem I'm having is all of the console functions I can find are blocking, which means that I can't detect that I need to exit from my console processing loop until the user presses a key (or enter, depending on the function).</p> <p>Is there some standard way I can do either non-block console interaction, or is there an elegant way to structure the program so that if I just terminate from the signal thread, that everything will be handled and released properly (please don't mis-understand this, I know how this could be done using locking and releasing the resources from the signaling thread, but this could get messy, so I'd rather avoid it)</p> <p>Hopefully that explanation makes more sense...</p>
[ { "answer_id": 181423, "author": "Toji", "author_id": 25968, "author_profile": "https://Stackoverflow.com/users/25968", "pm_score": 2, "selected": false, "text": "<p>In Windows: <a href=\"http://msdn.microsoft.com/en-us/library/ms686016(VS.85).aspx\" rel=\"nofollow noreferrer\">SetConsoleCtrlHandler</a></p>\n" }, { "answer_id": 181428, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": false, "text": "<p>On *nix, you can use the <code>signal</code> function to register a signal handler:</p>\n<pre><code>\n#include &lt;signal.h&gt;\n\nvoid signal_handler(int sig)\n{\n // Handle the signal\n}\n\nint main(void)\n{\n // Register the signal handler for the SIGINT signal (Ctrl+C)\n signal(SIGINT, signal_handler);\n ...\n}\n</code></pre>\n<p>Now, whenever someone hits <kbd>Ctrl</kbd>+<kbd>C</kbd>, your signal handler will be called.</p>\n" }, { "answer_id": 181460, "author": "terson", "author_id": 22974, "author_profile": "https://Stackoverflow.com/users/22974", "pm_score": 1, "selected": false, "text": "<p>On a *nix based system you might not really need a signal handler for this to work. You could specify that you want to ignore the SIGINT call</p>\n\n<pre><code>int main(void)\n{\n // Register to ignore the SIGINT signal (Ctrl+C)\n signal(SIGINT, SIG_IGN);\n\n while(1)\n {\n retval = my_blocking_io_func();\n if(retval == -1 &amp;&amp; errno == EINTR)\n {\n // do whatever you want to do in case of interrupt\n }\n }\n}\n</code></pre>\n\n<p>The important way that this works is to recognize that non-blocking functions do get interrupted. Normally, you would realize that the blocking function failed (e.g. read()) and reattempt the function. If it was some other value you would take the appropriate error related action.</p>\n" }, { "answer_id": 181594, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 3, "selected": false, "text": "<p>OK - this is working for me on Windows &amp; is portable - notice the #ifdef SIGBREAK - this isn't a standard signal.</p>\n\n<pre><code>#include &lt;csignal&gt;\n#include &lt;iostream&gt;\n#include &lt;ostream&gt;\n#include &lt;string&gt;\nusing namespace std;\n\nnamespace\n{\n volatile sig_atomic_t quit;\n\n void signal_handler(int sig)\n {\n signal(sig, signal_handler);\n quit = 1;\n }\n}\n\nint main()\n{\n signal(SIGINT, signal_handler);\n signal(SIGTERM, signal_handler);\n#ifdef SIGBREAK\n signal(SIGBREAK, signal_handler);\n#endif\n /* etc */\n\n while (!quit)\n {\n string s;\n cin &gt;&gt; s;\n cout &lt;&lt; s &lt;&lt; endl;\n }\n cout &lt;&lt; \"quit = \" &lt;&lt; quit &lt;&lt; endl;\n}\n</code></pre>\n" }, { "answer_id": 18593683, "author": "KyleL", "author_id": 804775, "author_profile": "https://Stackoverflow.com/users/804775", "pm_score": 0, "selected": false, "text": "<p>A better *nix solution that is thread safe is to use <a href=\"http://linux.die.net/man/3/pthread_sigmask\" rel=\"nofollow\">pthread_sigmask()</a> instead of signal().<br>\nFor example, this is how you signore SIGINT, SIGTERM, and SIGPIPE in the current thread and future spawned threads:</p>\n\n<pre><code>sigset_t waitset;\nsigemptyset(&amp;waitset);\nsigaddset(&amp;waitset, SIGINT);\nsigaddset(&amp;waitset, SIGTERM);\nsigaddset(&amp;waitset, SIGPIPE);\npthread_sigmask(SIG_BLOCK, &amp;waitset, NULL); \n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16313/" ]
Before I begin, I want to clarify that this is not a command-line tool, but an application that accepts commands through it's own command-line interface. **Edit:** I must apologize about my explanation from before, apparently I didn't do a very good job at explaining it. One more time... I am building a command-line interface application that accepts commands from a user. I have a signal handler setup to catch the signals, which then sets a flag that I need to terminate the application. The problem I'm having is all of the console functions I can find are blocking, which means that I can't detect that I need to exit from my console processing loop until the user presses a key (or enter, depending on the function). Is there some standard way I can do either non-block console interaction, or is there an elegant way to structure the program so that if I just terminate from the signal thread, that everything will be handled and released properly (please don't mis-understand this, I know how this could be done using locking and releasing the resources from the signaling thread, but this could get messy, so I'd rather avoid it) Hopefully that explanation makes more sense...
On \*nix, you can use the `signal` function to register a signal handler: ``` #include <signal.h> void signal_handler(int sig) { // Handle the signal } int main(void) { // Register the signal handler for the SIGINT signal (Ctrl+C) signal(SIGINT, signal_handler); ... } ``` Now, whenever someone hits `Ctrl`+`C`, your signal handler will be called.
181,426
<p>I'm making a Stored Procedure that basically concatenates a long string with data from many records.</p> <p>I want to do:</p> <pre><code>set @output = @output + 'aaa' + LINEBREAK </code></pre> <p>How do I specify that line break?</p>
[ { "answer_id": 181430, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 6, "selected": true, "text": "<pre><code>DECLARE @LINEBREAK AS varchar(2)\nSET @LINEBREAK = CHAR(13) + CHAR(10)\n</code></pre>\n" }, { "answer_id": 181431, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 1, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>set @output = @output + 'aaa' + char(13)\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3314/" ]
I'm making a Stored Procedure that basically concatenates a long string with data from many records. I want to do: ``` set @output = @output + 'aaa' + LINEBREAK ``` How do I specify that line break?
``` DECLARE @LINEBREAK AS varchar(2) SET @LINEBREAK = CHAR(13) + CHAR(10) ```
181,427
<p>I am currently having a hardtime understanding and implementing events in C# using delagates. I am used to the Java way of doing things:</p> <ol> <li>Define an interface for a listener type which would contain a number of method definitions</li> <li>Define adapter class for that interface to make things easier if I'm not interested in all the events defined in a listener</li> <li>Define Add, Remove and Get[] methods in the class which raises the events</li> <li>Define protected fire methods to do the dirty work of looping through the list of added listeners and calling the correct method</li> </ol> <p>This I understand (and like!) - I know I could do this exactly the same in c#, but it seems that a new (better?) system is in place for c#. After reading countless tutorials explaining the use of delegates and events in c# I still am no closer to really understanding what is going on :S</p> <hr> <p>In short, for the following methods how would I implement the event system in c#:</p> <pre><code>void computerStarted(Computer computer); void computerStopped(Computer computer); void computerReset(Computer computer); void computerError(Computer computer, Exception error); </code></pre> <p>^ The above methods are taken from a Java application I once made which I'm trying to port over to c#.</p> <p>Many many thanks!</p>
[ { "answer_id": 181451, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 3, "selected": false, "text": "<p>You'll have to define a single delegate for that</p>\n\n<pre><code>public delegate void ComputerEvent(object sender, ComputerEventArgs e);\n</code></pre>\n\n<p>ComputerEventArgs would be defined like this:</p>\n\n<pre><code>public class ComputerEventArgs : EventArgs\n{\n // TODO wrap in properties\n public Computer computer;\n public Exception error;\n\n public ComputerEventArgs(Computer aComputer, Exception anError)\n {\n computer = aComputer;\n error = anError;\n }\n\n public ComputerEventArgs(Computer aComputer) : this(aComputer, null)\n {\n }\n}\n</code></pre>\n\n<p>The class that fires the events would have these:</p>\n\n<pre><code>public YourClass\n{\n ...\n public event ComputerEvent ComputerStarted;\n public event ComputerEvent ComputerStopped;\n public event ComputerEvent ComputerReset;\n public event ComputerEvent ComputerError;\n ...\n}\n</code></pre>\n\n<p>This is how you assign handlers to the events:</p>\n\n<pre><code>YourClass obj = new YourClass();\nobj.ComputerStarted += new ComputerEvent(your_computer_started_handler);\n</code></pre>\n\n<p>Your handler is:</p>\n\n<pre><code>private void ComputerStartedEventHandler(object sender, ComputerEventArgs e)\n{\n // do your thing.\n}\n</code></pre>\n" }, { "answer_id": 181452, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 2, "selected": false, "text": "<p>The main difference is that in C# the events are not interface-based. Instead, the event publisher declares the delegate which you can think of as a function pointer (although not exactly the same :-)). The subscriber then implements the event prototype as a regular method and adds a new instance of the delegate to the event handler chain of the publisher. Read more about <a href=\"http://msdn.microsoft.com/en-us/library/ms173171.aspx\" rel=\"nofollow noreferrer\">delegates</a> and <a href=\"http://msdn.microsoft.com/en-us/library/awbftdfh.aspx\" rel=\"nofollow noreferrer\">events</a>.</p>\n\n<p>You can also read short comparison of C# vs. Java events <a href=\"http://msdn.microsoft.com/en-us/library/ms228499.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 181454, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 1, "selected": false, "text": "<p>there are several ways to do what you want. The <em>most direct</em> way would be to define delegates for each event in the hosting class, e.g.</p>\n\n<pre><code>public delegate void ComputerStartedDelegate(Computer computer);\nprotected event ComputerStartedDelegate ComputerStarted;\npublic void OnComputerStarted(Computer computer)\n{\n if (ComputerStarted != null)\n {\n ComputerStarted.Invoke(computer);\n }\n}\nprotected void someMethod()\n{\n //...\n computer.Started = true; //or whatever\n OnComputerStarted(computer);\n //...\n}\n</code></pre>\n\n<p>any object may 'listen' for this event simply by:</p>\n\n<pre><code>Computer comp = new Computer();\ncomp.ComputerStarted += new ComputerStartedDelegate(\n this.ComputerStartedHandler);\n\nprotected void ComputerStartedHandler(Computer computer)\n{\n //do something\n}\n</code></pre>\n\n<p>The 'recommended standard way' of doing this would be to define a subclass of EventArgs to hold the Computer (and old/new state and exception) value(s), reducing 4 delegates to one. In this case that would be a cleaner solution, esp. with an Enum for the computer states in case of later expansion. But the basic technique remains the same:</p>\n\n<ul>\n<li>the delegate defines the signature/interface for the event handler/listener</li>\n<li>the event data member is a list of 'listeners'</li>\n</ul>\n\n<p>listeners are removed using the -= syntax instead of +=</p>\n" }, { "answer_id": 181455, "author": "Andrew Kennan", "author_id": 22506, "author_profile": "https://Stackoverflow.com/users/22506", "pm_score": 1, "selected": false, "text": "<p>In c# events are delegates. They behave in a similar way to a function pointer in C/C++ but are actual classes derived from System.Delegate.</p>\n\n<p>In this case, create a custom EventArgs class to pass the Computer object.</p>\n\n<pre><code>public class ComputerEventArgs : EventArgs\n{\n private Computer _computer;\n\n public ComputerEventArgs(Computer computer) {\n _computer = computer;\n }\n\n public Computer Computer { get { return _computer; } }\n}\n</code></pre>\n\n<p>Then expose the events from the producer:</p>\n\n<pre><code>public class ComputerEventProducer\n{\n public event EventHandler&lt;ComputerEventArgs&gt; Started;\n public event EventHandler&lt;ComputerEventArgs&gt; Stopped;\n public event EventHandler&lt;ComputerEventArgs&gt; Reset;\n public event EventHandler&lt;ComputerEventArgs&gt; Error;\n\n /*\n // Invokes the Started event */\n private void OnStarted(Computer computer) {\n if( Started != null ) {\n Started(this, new ComputerEventArgs(computer));\n }\n }\n\n // Add OnStopped, OnReset and OnError\n\n}\n</code></pre>\n\n<p>The consumer of the events then binds a handler function to each event on the consumer.</p>\n\n<pre><code>public class ComputerEventConsumer\n{\n public void ComputerEventConsumer(ComputerEventProducer producer) {\n producer.Started += new EventHandler&lt;ComputerEventArgs&gt;(ComputerStarted);\n // Add other event handlers\n }\n\n private void ComputerStarted(object sender, ComputerEventArgs e) {\n }\n}\n</code></pre>\n\n<p>When the ComputerEventProducer calls OnStarted the Started event is invoked which in turn will call the ComputerEventConsumer.ComputerStarted method.</p>\n" }, { "answer_id": 181462, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "<p>You'd create four events, and methods to raise them, along with a new EventArgs-based class to indicate the error:</p>\n\n<pre><code>public class ExceptionEventArgs : EventArgs\n{\n private readonly Exception error;\n\n public ExceptionEventArgs(Exception error)\n {\n this.error = error;\n }\n\n public Error\n {\n get { return error; }\n }\n}\n\npublic class Computer\n{\n public event EventHandler Started = delegate{};\n public event EventHandler Stopped = delegate{};\n public event EventHandler Reset = delegate{};\n public event EventHandler&lt;ExceptionEventArgs&gt; Error = delegate{};\n\n protected void OnStarted()\n {\n Started(this, EventArgs.Empty);\n }\n\n protected void OnStopped()\n {\n Stopped(this, EventArgs.Empty);\n }\n\n protected void OnReset()\n {\n Reset(this, EventArgs.Empty);\n }\n\n protected void OnError(Exception e)\n {\n Error(this, new ExceptionEventArgs(e));\n }\n}\n</code></pre>\n\n<p>Classes would then subscribe to the event using either a method or a an anonymous function:</p>\n\n<pre><code>someComputer.Started += StartEventHandler; // A method\nsomeComputer.Stopped += delegate(object o, EventArgs e)\n{ \n Console.WriteLine(\"{0} has started\", o);\n};\nsomeComputer.Reset += (o, e) =&gt; Console.WriteLine(\"{0} has been reset\");\n</code></pre>\n\n<p>A few things to note about the above:</p>\n\n<ul>\n<li>The OnXXX methods are protected so that derived classes can raise the events. This isn't always necessary - do it as you see fit.</li>\n<li>The <code>delegate{}</code> piece on each event declaration is just a trick to avoid having to do a null check. It's subscribing a no-op event handler to each event</li>\n<li>The event declarations are <em>field-like events</em>. What's actually being created is both a variable <em>and</em> an event. Inside the class you see the variable; outside the class you see the event.</li>\n</ul>\n\n<p>See my <a href=\"http://pobox.com/~skeet/csharp/events.html\" rel=\"noreferrer\">events/delegates</a> article for much more detail on events.</p>\n" }, { "answer_id": 181468, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 2, "selected": false, "text": "<p>First of all, there is a standard method signature in .Net that is typically used for events. The languages allow any sort of method signature at all to be used for events, and there are some experts who believe the convention is flawed (I mostly agree), but it is what it is and I will follow it for this example.</p>\n\n<ol>\n<li>Create a class that will contain the event’s parameters (derived from EventArgs).</li>\n</ol>\n\n<pre>\npublic class ComputerEventArgs : EventArgs \n{\n Computer computer; \n // constructor, properties, etc.\n}\n</pre>\n\n<ol start=\"2\">\n<li>Create a public event on the class that is to fire the event.</li>\n</ol>\n\n<pre>\n class ComputerEventGenerator // I picked a terrible name BTW.\n {\n public event EventHandler&lt;ComputerEventArgs&gt; ComputerStarted;\n public event EventHandler&lt;ComputerEventArgs&gt; ComputerStopped;\n public event EventHandler&lt;ComputerEventArgs&gt; ComputerReset;\n ...\n }\n</pre>\n\n<ol start=\"3\">\n<li>Call the events.</li>\n</ol>\n\n<pre>\n class ComputerEventGenerator\n {\n ...\n private void OnComputerStarted(Computer computer) \n {\n EventHandler&lt;ComputerEventArgs&gt; temp = ComputerStarted;\n if (temp != null) temp(this, new ComputerEventArgs(computer)); // replace \"this\" with null if the event is static\n }\n }\n</pre>\n\n<ol start=\"4\">\n<li>Attach a handler for the event.</li>\n</ol>\n\n<pre>\n void OnLoad()\n {\n ComputerEventGenerator computerEventGenerator = new ComputerEventGenerator();\n computerEventGenerator.ComputerStarted += new EventHandler&lt;ComputerEventArgs&gt;(ComputerEventGenerator_ComputerStarted);\n }\n</pre>\n\n<ol start=\"5\">\n<li>Create the handler you just attached (mostly by pressing the Tab key in VS).</li>\n</ol>\n\n<pre>\n private void ComputerEventGenerator_ComputerStarted(object sender, ComputerEventArgs args)\n {\n if (args.Computer.Name == \"HAL9000\")\n ShutItDownNow(args.Computer);\n }\n</pre>\n\n<ol start=\"6\">\n<li>Don't forget to detach the handler when you're done. (Forgetting to do this is the biggest source of memory leaks in C#!)</li>\n</ol>\n\n<pre>\n void OnClose()\n {\n ComputerEventGenerator.ComputerStarted -= ComputerEventGenerator_ComputerStarted;\n }\n</pre>\n\n<p>And that's it!</p>\n\n<p>EDIT: I honestly can't figure out why my numbered points all appear as \"1.\" I hate computers.</p>\n" }, { "answer_id": 181487, "author": "loudej", "author_id": 6056, "author_profile": "https://Stackoverflow.com/users/6056", "pm_score": 0, "selected": false, "text": "<p>The delegate declares a function signature, and when it's used as an event on a class it also acts as a collection of enlisted call targets. The += and -= syntax on an event is used to adding a target to the list.</p>\n\n<p>Given the following delegates used as events:</p>\n\n<pre><code>// arguments for events\npublic class ComputerEventArgs : EventArgs\n{\n public Computer Computer { get; set; }\n}\n\npublic class ComputerErrorEventArgs : ComputerEventArgs\n{\n public Exception Error { get; set; }\n}\n\n// delegates for events\npublic delegate void ComputerEventHandler(object sender, ComputerEventArgs e);\n\npublic delegate void ComputerErrorEventHandler(object sender, ComputerErrorEventArgs e);\n\n// component that raises events\npublic class Thing\n{\n public event ComputerEventHandler Started;\n public event ComputerEventHandler Stopped;\n public event ComputerEventHandler Reset;\n public event ComputerErrorEventHandler Error;\n}\n</code></pre>\n\n<p>You would subscribe to those events with the following:</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n var thing = new Thing();\n thing.Started += thing_Started;\n }\n\n static void thing_Started(object sender, ComputerEventArgs e)\n {\n throw new NotImplementedException();\n }\n}\n</code></pre>\n\n<p>Although the arguments could be anything, the object sender and EventArgs e is a convention that's used very consistently. The += thing_started will first create an instance of the delegate pointing to target method, then add it to the event.</p>\n\n<p>On the component itself you would typically add methods to fire the events:</p>\n\n<pre><code>public class Thing\n{\n public event ComputerEventHandler Started;\n\n public void OnStarted(Computer computer)\n {\n if (Started != null)\n Started(this, new ComputerEventArgs {Computer = computer});\n }\n}\n</code></pre>\n\n<p>You must test for null in case no delegates have been added to the event. When you make the method call however all delegates which have been added will be called. This is why for events the return type is void - there is no single return value - so to feed back information you would have properties on the EventArgs which the event handlers would alter.</p>\n\n<p>Another refinement would be to use the generic EventHandler delegate rather than declaring a concrete delegate for each type of args.</p>\n\n<pre><code>public class Thing\n{\n public event EventHandler&lt;ComputerEventArgs&gt; Started;\n public event EventHandler&lt;ComputerEventArgs&gt; Stopped;\n public event EventHandler&lt;ComputerEventArgs&gt; Reset;\n public event EventHandler&lt;ComputerErrorEventArgs&gt; Error;\n}\n</code></pre>\n" }, { "answer_id": 183077, "author": "Richard Walton", "author_id": 15075, "author_profile": "https://Stackoverflow.com/users/15075", "pm_score": 0, "selected": false, "text": "<p>Thank you all so much for your answers! Finally I'm starting to understand what is going on. Just one thing; It seems that if each event had a different number/type of arguments I'd need to create a different :: EventArgs class to deal with it:</p>\n\n<pre><code>public void computerStarted(Computer computer);\npublic void computerStopped(Computer computer);\npublic void computerReset(Computer computer);\npublic void breakPointHit(Computer computer, int breakpoint);\npublic void computerError(Computer computer, Exception exception);\n</code></pre>\n\n<p>This would require three classses to deal with the events!? (Well two custom, and one using the default EventArgs.Empty class)</p>\n\n<p>Cheers!</p>\n" }, { "answer_id": 183703, "author": "Richard Walton", "author_id": 15075, "author_profile": "https://Stackoverflow.com/users/15075", "pm_score": 0, "selected": false, "text": "<p>Ok, FINAL clarification!: So this is pretty much the best I can do code-wise to implement those events?</p>\n\n<pre><code> public class Computer {\n\n public event EventHandler Started;\n\n public event EventHandler Stopped;\n\n public event EventHandler Reset;\n\n public event EventHandler&lt;BreakPointEvent&gt; BreakPointHit;\n\n public event EventHandler&lt;ExceptionEvent&gt; Error;\n\n public Computer() {\n Started = delegate { };\n Stopped = delegate { };\n Reset = delegate { };\n BreakPointHit = delegate { };\n Error = delegate { };\n }\n\n protected void OnStarted() {\n Started(this, EventArgs.Empty);\n }\n\n protected void OnStopped() {\n Stopped(this, EventArgs.Empty);\n }\n\n protected void OnReset() {\n Reset(this, EventArgs.Empty);\n }\n\n protected void OnBreakPointHit(int breakPoint) {\n BreakPointHit(this, new BreakPointEvent(breakPoint));\n }\n\n protected void OnError(System.Exception exception) {\n Error(this, new ExceptionEvent(exception));\n }\n }\n}\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15075/" ]
I am currently having a hardtime understanding and implementing events in C# using delagates. I am used to the Java way of doing things: 1. Define an interface for a listener type which would contain a number of method definitions 2. Define adapter class for that interface to make things easier if I'm not interested in all the events defined in a listener 3. Define Add, Remove and Get[] methods in the class which raises the events 4. Define protected fire methods to do the dirty work of looping through the list of added listeners and calling the correct method This I understand (and like!) - I know I could do this exactly the same in c#, but it seems that a new (better?) system is in place for c#. After reading countless tutorials explaining the use of delegates and events in c# I still am no closer to really understanding what is going on :S --- In short, for the following methods how would I implement the event system in c#: ``` void computerStarted(Computer computer); void computerStopped(Computer computer); void computerReset(Computer computer); void computerError(Computer computer, Exception error); ``` ^ The above methods are taken from a Java application I once made which I'm trying to port over to c#. Many many thanks!
You'd create four events, and methods to raise them, along with a new EventArgs-based class to indicate the error: ``` public class ExceptionEventArgs : EventArgs { private readonly Exception error; public ExceptionEventArgs(Exception error) { this.error = error; } public Error { get { return error; } } } public class Computer { public event EventHandler Started = delegate{}; public event EventHandler Stopped = delegate{}; public event EventHandler Reset = delegate{}; public event EventHandler<ExceptionEventArgs> Error = delegate{}; protected void OnStarted() { Started(this, EventArgs.Empty); } protected void OnStopped() { Stopped(this, EventArgs.Empty); } protected void OnReset() { Reset(this, EventArgs.Empty); } protected void OnError(Exception e) { Error(this, new ExceptionEventArgs(e)); } } ``` Classes would then subscribe to the event using either a method or a an anonymous function: ``` someComputer.Started += StartEventHandler; // A method someComputer.Stopped += delegate(object o, EventArgs e) { Console.WriteLine("{0} has started", o); }; someComputer.Reset += (o, e) => Console.WriteLine("{0} has been reset"); ``` A few things to note about the above: * The OnXXX methods are protected so that derived classes can raise the events. This isn't always necessary - do it as you see fit. * The `delegate{}` piece on each event declaration is just a trick to avoid having to do a null check. It's subscribing a no-op event handler to each event * The event declarations are *field-like events*. What's actually being created is both a variable *and* an event. Inside the class you see the variable; outside the class you see the event. See my [events/delegates](http://pobox.com/~skeet/csharp/events.html) article for much more detail on events.
181,432
<p>The class method to create an index path with one or more nodes is:</p> <pre><code>+ (id)indexPathWithIndexes:(NSUInteger *)indexes length:(NSUInteger)length </code></pre> <p>How do we create the "indexes" required in the first parameter? </p> <p>The documentation listed it as <em>Array of indexes to make up the index path</em> but it is expecting a (NSUinteger *). </p> <p>To create an index path of 1.2.3.4, is it simply an array of [1,2,3,4] ?</p>
[ { "answer_id": 181440, "author": "Giao", "author_id": 14099, "author_profile": "https://Stackoverflow.com/users/14099", "pm_score": 3, "selected": false, "text": "<p>You assumption is correct. It's as simple as a C array of NSUInteger. The length parameter is the number of elements in the indexes array.</p>\n\n<p>Arrays in C are often identified as a pointer (in this case NSUInteger *) with a length parameter or a known terminator such as \\0 for C strings (which is just a char array).</p>\n" }, { "answer_id": 184463, "author": "Barry Wark", "author_id": 2140, "author_profile": "https://Stackoverflow.com/users/2140", "pm_score": 7, "selected": true, "text": "<p>You are correct. You might use it like this:</p>\n\n<pre><code>NSUInteger indexArr[] = {1,2,3,4};\n\nNSIndexPath *indexPath = [NSIndexPath indexPathWithIndexes:indexArr length:4];\n</code></pre>\n" }, { "answer_id": 829160, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>On iOS, you can also use this method from <a href=\"http://developer.apple.com/library/ios/documentation/uikit/reference/NSIndexPath_UIKitAdditions/\" rel=\"noreferrer\">NSIndexPath UIKit Additions</a> (declared in UITableView.h):</p>\n\n<pre><code>+ (NSIndexPath*) indexPathForRow:(NSUInteger)row inSection:(NSUInteger)section\n</code></pre>\n" }, { "answer_id": 32511059, "author": "jungledev", "author_id": 3634990, "author_profile": "https://Stackoverflow.com/users/3634990", "pm_score": 2, "selected": false, "text": "<p>I did this in 2 lines of code</p>\n\n<pre><code> NSMutableArray *indexPaths = [[NSMutableArray alloc] init]; \n for (int i = firstIndexYouWant; i &lt; totalIndexPathsYouWant; i++) [indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];\n</code></pre>\n\n<p>Short, clean, and readable. Free code, don't knock it.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1987/" ]
The class method to create an index path with one or more nodes is: ``` + (id)indexPathWithIndexes:(NSUInteger *)indexes length:(NSUInteger)length ``` How do we create the "indexes" required in the first parameter? The documentation listed it as *Array of indexes to make up the index path* but it is expecting a (NSUinteger \*). To create an index path of 1.2.3.4, is it simply an array of [1,2,3,4] ?
You are correct. You might use it like this: ``` NSUInteger indexArr[] = {1,2,3,4}; NSIndexPath *indexPath = [NSIndexPath indexPathWithIndexes:indexArr length:4]; ```
181,442
<p>Actually, I wanted a custom cell which contains 2 image objects and 1 text object, and I decided to make a container for those objects. </p> <p>So is it possible to hold a image in object and insert that object in any of the collection objects, and later use that object to display inside cell?</p>
[ { "answer_id": 181475, "author": "Dre", "author_id": 23033, "author_profile": "https://Stackoverflow.com/users/23033", "pm_score": 1, "selected": false, "text": "<p>There should be no problem with that. Just make sure you are properly retaining it and what not in your class.</p>\n" }, { "answer_id": 183750, "author": "lajos", "author_id": 3740, "author_profile": "https://Stackoverflow.com/users/3740", "pm_score": 3, "selected": true, "text": "<p>NSArray and NSDictionary both hold objects. These are most likely the collections you'll use with a table view.</p>\n\n<p>The best way to implement what you are trying to do is to use the UIImage class. UIImages wrap a CGImage and do all the memory management for you (if your app is running low on memory, the image data is purged and automatically reloaded when you draw it- pretty cool, huh?) You can also read images from files very easily using this class (a whole bunch of formats supported).</p>\n\n<p>Look at the documentation for NSArray, NSMutableArray, and UIImage for more information.</p>\n\n<pre><code>//create a UIImage from a jpeg image\nUIImage *myImage = [UIImage imageWithContentsOfFile:@\"myImage.jpg\"];\nNSArray *myArray = [NSMutableArray array]; // this will autorelease, so if you need to keep it around, retain it\n[myArray addObject:myImage];\n\n\n\n//to draw this image in a UIView's drawRect method\nCGContextRef context = UIGraphicsGetCurrentContext(); // you need to find the context to draw into\nUIImage *myImage = [myArray lastObject]; // this gets the last object from an array, use the objectAtIndex: method to get a an object with a specific index\nCGImageRef *myCGImage = [myImage CGImage];\nCGContextDrawImage(context, rect, myCGImage); //rect is passed to drawRect\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/451867/" ]
Actually, I wanted a custom cell which contains 2 image objects and 1 text object, and I decided to make a container for those objects. So is it possible to hold a image in object and insert that object in any of the collection objects, and later use that object to display inside cell?
NSArray and NSDictionary both hold objects. These are most likely the collections you'll use with a table view. The best way to implement what you are trying to do is to use the UIImage class. UIImages wrap a CGImage and do all the memory management for you (if your app is running low on memory, the image data is purged and automatically reloaded when you draw it- pretty cool, huh?) You can also read images from files very easily using this class (a whole bunch of formats supported). Look at the documentation for NSArray, NSMutableArray, and UIImage for more information. ``` //create a UIImage from a jpeg image UIImage *myImage = [UIImage imageWithContentsOfFile:@"myImage.jpg"]; NSArray *myArray = [NSMutableArray array]; // this will autorelease, so if you need to keep it around, retain it [myArray addObject:myImage]; //to draw this image in a UIView's drawRect method CGContextRef context = UIGraphicsGetCurrentContext(); // you need to find the context to draw into UIImage *myImage = [myArray lastObject]; // this gets the last object from an array, use the objectAtIndex: method to get a an object with a specific index CGImageRef *myCGImage = [myImage CGImage]; CGContextDrawImage(context, rect, myCGImage); //rect is passed to drawRect ```
181,459
<p>Is there a better way to do this?</p> <pre><code>-(NSDate *)getMidnightTommorow { NSCalendarDate *now = [NSCalendarDate date]; NSCalendarDate *tomorrow = [now dateByAddingYears:0 months:0 days:1 hours:0 minutes:0 seconds:0]; return [NSCalendarDate dateWithYear:[tomorrow yearOfCommonEra] month:[tomorrow monthOfYear] day:[tomorrow dayOfMonth] hour:0 minute:0 second:0 timeZone:[tomorrow timeZone]]; } </code></pre> <p>Note that I always want the next midnight, even if it happens to be midnight when I make that call, however if it happens to be 23:59:59, I of course want the midnight that is coming in one second.</p> <p>The natural language functions seem flaky, and I'm not sure what Cocoa would do if I pass 32 in the "day" field. (If that'd work I could drop the [now dateByAddingYears:...] call)</p>
[ { "answer_id": 181495, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 6, "selected": true, "text": "<p>From the <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSCalendarDate_Class/Reference/Reference.html\" rel=\"noreferrer\">documentation</a>:</p>\n\n<blockquote>\n <p>Use of NSCalendarDate strongly\n discouraged. It is not deprecated yet,\n however it may be in the next major OS\n release after Mac OS X v10.5. For\n calendrical calculations, you should\n use suitable combinations of\n NSCalendar, NSDate, and\n NSDateComponents, as described in\n Calendars in <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html\" rel=\"noreferrer\">Dates and Times\n Programming Topics for Cocoa</a>.</p>\n</blockquote>\n\n<p>Following that advice:</p>\n\n<pre><code>NSDate *today = [NSDate date];\n\nNSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];\n\nNSDateComponents *components = [[NSDateComponents alloc] init];\ncomponents.day = 1;\nNSDate *tomorrow = [gregorian dateByAddingComponents:components toDate:today options:0];\n[components release];\n\nNSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;\ncomponents = [gregorian components:unitFlags fromDate:tomorrow];\ncomponents.hour = 0;\ncomponents.minute = 0;\n\nNSDate *tomorrowMidnight = [gregorian dateFromComponents:components];\n\n[gregorian release];\n[components release];\n</code></pre>\n\n<p>(I'm not sure offhand if this is the most efficient implementation, but it should serve as a pointer in the right direction.)</p>\n\n<p>Note: In theory you can reduce the amount of code here by allowing a date components object with values greater than the range of normal values for the component (e.g. simply adding 1 to the day component, which might result in its having a value of 32). However, although <code>dateFromComponents:</code> <em>may</em> tolerate out-of-bounds values, it's not guaranteed to. You're strongly encouraged not to rely on it.</p>\n" }, { "answer_id": 181500, "author": "selwyn", "author_id": 16314, "author_profile": "https://Stackoverflow.com/users/16314", "pm_score": 0, "selected": false, "text": "<p>Convert your current date and time to a Unix date (seconds since 1970) or DOS style (since 1980), then add 24 hours and convert it back. Then reset the hours, minutes and seconds to zero to get to midnight.</p>\n" }, { "answer_id": 181508, "author": "loudej", "author_id": 6056, "author_profile": "https://Stackoverflow.com/users/6056", "pm_score": 3, "selected": false, "text": "<p>Nope - it'll be the same way you use to find midnight today.</p>\n" }, { "answer_id": 860379, "author": "user58338", "author_id": 58338, "author_profile": "https://Stackoverflow.com/users/58338", "pm_score": 1, "selected": false, "text": "<pre><code>[NSDate dateWithNaturalLanguageString:@\"midnight tomorrow\"];\n</code></pre>\n" }, { "answer_id": 1237402, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];\n\nNSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:(24 * 60 * 60)];\n\nNSDateComponents *components = [gregorian components:(NSYearCalendarUnit |\n NSMonthCalendarUnit |\n NSDayCalendarUnit)\n fromDate:tomorrow];\n\nNSDate *midnight = [gregorian dateFromComponents:components];\n</code></pre>\n" }, { "answer_id": 35535389, "author": "julia_v", "author_id": 3881449, "author_profile": "https://Stackoverflow.com/users/3881449", "pm_score": 0, "selected": false, "text": "<p>You could try this way:</p>\n\n<pre><code>NSCalendar *calendar = [NSCalendar currentCalendar];\nNSDateComponents *comps = [[NSDateComponents alloc] init];\n[comps setDay:1];\nNSDate *tomorrow = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0]; //it gives us tomorrow with current time\nNSDate *midnight = [calendar startOfDayForDate:tomorrow]; //here we get next midnight\n</code></pre>\n\n<p>It is also easy to retrieve the seconds interval if needed to set up an NSTimer:</p>\n\n<pre><code>double intervalToMidnight = midnight.timeIntervalSinceNow;\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23033/" ]
Is there a better way to do this? ``` -(NSDate *)getMidnightTommorow { NSCalendarDate *now = [NSCalendarDate date]; NSCalendarDate *tomorrow = [now dateByAddingYears:0 months:0 days:1 hours:0 minutes:0 seconds:0]; return [NSCalendarDate dateWithYear:[tomorrow yearOfCommonEra] month:[tomorrow monthOfYear] day:[tomorrow dayOfMonth] hour:0 minute:0 second:0 timeZone:[tomorrow timeZone]]; } ``` Note that I always want the next midnight, even if it happens to be midnight when I make that call, however if it happens to be 23:59:59, I of course want the midnight that is coming in one second. The natural language functions seem flaky, and I'm not sure what Cocoa would do if I pass 32 in the "day" field. (If that'd work I could drop the [now dateByAddingYears:...] call)
From the [documentation](http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSCalendarDate_Class/Reference/Reference.html): > > Use of NSCalendarDate strongly > discouraged. It is not deprecated yet, > however it may be in the next major OS > release after Mac OS X v10.5. For > calendrical calculations, you should > use suitable combinations of > NSCalendar, NSDate, and > NSDateComponents, as described in > Calendars in [Dates and Times > Programming Topics for Cocoa](http://developer.apple.com/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html). > > > Following that advice: ``` NSDate *today = [NSDate date]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *components = [[NSDateComponents alloc] init]; components.day = 1; NSDate *tomorrow = [gregorian dateByAddingComponents:components toDate:today options:0]; [components release]; NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit; components = [gregorian components:unitFlags fromDate:tomorrow]; components.hour = 0; components.minute = 0; NSDate *tomorrowMidnight = [gregorian dateFromComponents:components]; [gregorian release]; [components release]; ``` (I'm not sure offhand if this is the most efficient implementation, but it should serve as a pointer in the right direction.) Note: In theory you can reduce the amount of code here by allowing a date components object with values greater than the range of normal values for the component (e.g. simply adding 1 to the day component, which might result in its having a value of 32). However, although `dateFromComponents:` *may* tolerate out-of-bounds values, it's not guaranteed to. You're strongly encouraged not to rely on it.
181,471
<p>The new awesome <kbd>Ctrl</kbd> + <kbd>.</kbd> keyboard shortcut to show smart tags has suddenly stopped working, a week or so after I discovered it :( </p> <p>I am missing it badly, having had to revert back to <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>F10</kbd>, which really just isn't the same.</p> <p>I recently installed F# CTP 1.9.6.2</p> <p>Has anyone else</p> <ul> <li>installed this CTP and still has <kbd>Ctrl</kbd> + <kbd>.</kbd></li> <li>Lost <kbd>Ctrl</kbd> + <kbd>.</kbd> without installing F#</li> <li>Even better, found how to get it back again?</li> </ul> <p><strong>EDIT</strong> In attempting John Sheehan recommendation, I have noticed that my available mapping schemes only include <code>Visual C# 2005</code>, should I not have a 2008?</p> <p>Also the mapped shortcut to this is</p> <pre><code>OtherContextMenus.FSIConsoleContext.CancelEvaluation </code></pre>
[ { "answer_id": 181495, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 6, "selected": true, "text": "<p>From the <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSCalendarDate_Class/Reference/Reference.html\" rel=\"noreferrer\">documentation</a>:</p>\n\n<blockquote>\n <p>Use of NSCalendarDate strongly\n discouraged. It is not deprecated yet,\n however it may be in the next major OS\n release after Mac OS X v10.5. For\n calendrical calculations, you should\n use suitable combinations of\n NSCalendar, NSDate, and\n NSDateComponents, as described in\n Calendars in <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html\" rel=\"noreferrer\">Dates and Times\n Programming Topics for Cocoa</a>.</p>\n</blockquote>\n\n<p>Following that advice:</p>\n\n<pre><code>NSDate *today = [NSDate date];\n\nNSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];\n\nNSDateComponents *components = [[NSDateComponents alloc] init];\ncomponents.day = 1;\nNSDate *tomorrow = [gregorian dateByAddingComponents:components toDate:today options:0];\n[components release];\n\nNSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;\ncomponents = [gregorian components:unitFlags fromDate:tomorrow];\ncomponents.hour = 0;\ncomponents.minute = 0;\n\nNSDate *tomorrowMidnight = [gregorian dateFromComponents:components];\n\n[gregorian release];\n[components release];\n</code></pre>\n\n<p>(I'm not sure offhand if this is the most efficient implementation, but it should serve as a pointer in the right direction.)</p>\n\n<p>Note: In theory you can reduce the amount of code here by allowing a date components object with values greater than the range of normal values for the component (e.g. simply adding 1 to the day component, which might result in its having a value of 32). However, although <code>dateFromComponents:</code> <em>may</em> tolerate out-of-bounds values, it's not guaranteed to. You're strongly encouraged not to rely on it.</p>\n" }, { "answer_id": 181500, "author": "selwyn", "author_id": 16314, "author_profile": "https://Stackoverflow.com/users/16314", "pm_score": 0, "selected": false, "text": "<p>Convert your current date and time to a Unix date (seconds since 1970) or DOS style (since 1980), then add 24 hours and convert it back. Then reset the hours, minutes and seconds to zero to get to midnight.</p>\n" }, { "answer_id": 181508, "author": "loudej", "author_id": 6056, "author_profile": "https://Stackoverflow.com/users/6056", "pm_score": 3, "selected": false, "text": "<p>Nope - it'll be the same way you use to find midnight today.</p>\n" }, { "answer_id": 860379, "author": "user58338", "author_id": 58338, "author_profile": "https://Stackoverflow.com/users/58338", "pm_score": 1, "selected": false, "text": "<pre><code>[NSDate dateWithNaturalLanguageString:@\"midnight tomorrow\"];\n</code></pre>\n" }, { "answer_id": 1237402, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];\n\nNSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:(24 * 60 * 60)];\n\nNSDateComponents *components = [gregorian components:(NSYearCalendarUnit |\n NSMonthCalendarUnit |\n NSDayCalendarUnit)\n fromDate:tomorrow];\n\nNSDate *midnight = [gregorian dateFromComponents:components];\n</code></pre>\n" }, { "answer_id": 35535389, "author": "julia_v", "author_id": 3881449, "author_profile": "https://Stackoverflow.com/users/3881449", "pm_score": 0, "selected": false, "text": "<p>You could try this way:</p>\n\n<pre><code>NSCalendar *calendar = [NSCalendar currentCalendar];\nNSDateComponents *comps = [[NSDateComponents alloc] init];\n[comps setDay:1];\nNSDate *tomorrow = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0]; //it gives us tomorrow with current time\nNSDate *midnight = [calendar startOfDayForDate:tomorrow]; //here we get next midnight\n</code></pre>\n\n<p>It is also easy to retrieve the seconds interval if needed to set up an NSTimer:</p>\n\n<pre><code>double intervalToMidnight = midnight.timeIntervalSinceNow;\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5302/" ]
The new awesome `Ctrl` + `.` keyboard shortcut to show smart tags has suddenly stopped working, a week or so after I discovered it :( I am missing it badly, having had to revert back to `Ctrl` + `Alt` + `F10`, which really just isn't the same. I recently installed F# CTP 1.9.6.2 Has anyone else * installed this CTP and still has `Ctrl` + `.` * Lost `Ctrl` + `.` without installing F# * Even better, found how to get it back again? **EDIT** In attempting John Sheehan recommendation, I have noticed that my available mapping schemes only include `Visual C# 2005`, should I not have a 2008? Also the mapped shortcut to this is ``` OtherContextMenus.FSIConsoleContext.CancelEvaluation ```
From the [documentation](http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSCalendarDate_Class/Reference/Reference.html): > > Use of NSCalendarDate strongly > discouraged. It is not deprecated yet, > however it may be in the next major OS > release after Mac OS X v10.5. For > calendrical calculations, you should > use suitable combinations of > NSCalendar, NSDate, and > NSDateComponents, as described in > Calendars in [Dates and Times > Programming Topics for Cocoa](http://developer.apple.com/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html). > > > Following that advice: ``` NSDate *today = [NSDate date]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *components = [[NSDateComponents alloc] init]; components.day = 1; NSDate *tomorrow = [gregorian dateByAddingComponents:components toDate:today options:0]; [components release]; NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit; components = [gregorian components:unitFlags fromDate:tomorrow]; components.hour = 0; components.minute = 0; NSDate *tomorrowMidnight = [gregorian dateFromComponents:components]; [gregorian release]; [components release]; ``` (I'm not sure offhand if this is the most efficient implementation, but it should serve as a pointer in the right direction.) Note: In theory you can reduce the amount of code here by allowing a date components object with values greater than the range of normal values for the component (e.g. simply adding 1 to the day component, which might result in its having a value of 32). However, although `dateFromComponents:` *may* tolerate out-of-bounds values, it's not guaranteed to. You're strongly encouraged not to rely on it.
181,485
<p>I've incorporated Apple's Reachability sample into my own project so I know whether or not I have a network connection - if I don't have a network connection, I don't bother sending out and requests. I decided to go with the status notification implementation because it seemed easier to have the reachablity updated in the background and have the current results available immediately as opposed to kicking off a synchronous request whenever I want to make a network connection.</p> <p>My problem is that I start getting false negatives when on an EDGE network - the phone has connectivity, but the app thinks this isn't the case. My understanding is you don't get a notification when an EDGE connection, so my assumption is that I lost and regained the connection at some point. Restarting the app is usually sufficient to see the network connection.</p> <p>This isn't an optimal solution, so I was wondering if anybody else came across this problem and had any thoughts on a solutions.</p> <p>(I don't know whether this applies to 3G as well; I'm running a first gen iPhone).</p>
[ { "answer_id": 181529, "author": "Chris Lundie", "author_id": 20685, "author_profile": "https://Stackoverflow.com/users/20685", "pm_score": 5, "selected": true, "text": "<p>Reachability notificataions didn't seem to be reliable for me either, for detecting Wi-Fi. So I just use polling instead. Checking every 5 seconds seems to do no harm.</p>\n\n<pre><code>- (void) checkReachability {\n BOOL connected = ([[Reachability sharedReachability] localWiFiConnectionStatus] == ReachableViaWiFiNetwork);\n\n // Do something...\n\n [self performSelector:@selector(checkReachability) withObject:nil afterDelay:5.0];\n}\n</code></pre>\n" }, { "answer_id": 7036286, "author": "Abhijeet", "author_id": 782653, "author_profile": "https://Stackoverflow.com/users/782653", "pm_score": 1, "selected": false, "text": "<p>There is a nice reachability example on the net. it works wonderfully well:\n<a href=\"http://servin.com/iphone/iPhone-Network-Status.html\" rel=\"nofollow\">http://servin.com/iphone/iPhone-Network-Status.html</a></p>\n\n<p>But you see, when I try to use it my own way, it just bombs.</p>\n\n<p>Tried to implement it using:</p>\n\n<pre><code>NSString *sCellNetwork; \n NSString *sNetworkReachable; \n\nif (flags &amp; kSCNetworkFlagsReachable || flags &amp; kSCNetworkReachabilityFlagsIsWWAN)\n\n{do it} \n\n else {\n Network fail alert; \n}\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24168/" ]
I've incorporated Apple's Reachability sample into my own project so I know whether or not I have a network connection - if I don't have a network connection, I don't bother sending out and requests. I decided to go with the status notification implementation because it seemed easier to have the reachablity updated in the background and have the current results available immediately as opposed to kicking off a synchronous request whenever I want to make a network connection. My problem is that I start getting false negatives when on an EDGE network - the phone has connectivity, but the app thinks this isn't the case. My understanding is you don't get a notification when an EDGE connection, so my assumption is that I lost and regained the connection at some point. Restarting the app is usually sufficient to see the network connection. This isn't an optimal solution, so I was wondering if anybody else came across this problem and had any thoughts on a solutions. (I don't know whether this applies to 3G as well; I'm running a first gen iPhone).
Reachability notificataions didn't seem to be reliable for me either, for detecting Wi-Fi. So I just use polling instead. Checking every 5 seconds seems to do no harm. ``` - (void) checkReachability { BOOL connected = ([[Reachability sharedReachability] localWiFiConnectionStatus] == ReachableViaWiFiNetwork); // Do something... [self performSelector:@selector(checkReachability) withObject:nil afterDelay:5.0]; } ```
181,498
<p>I need to sort tuples according to the second element of each tuple but apparently usort/1 only works with the first element. So I have to swap the elements, usort them and swap back.Is there an easier way?Also is there a way to sort in descending order (I know sorting and reversing can be done, but just want to know).</p>
[ { "answer_id": 181520, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 0, "selected": false, "text": "<p>It shouldn't be too hard to write your own sort function (adapted from a common example):</p>\n\n<pre><code>qsort([]) -&gt; [];\nqsort([Pivot|Tail]) -&gt;\n {PivotFirst, PivotSecond} = Pivot,\n qsort([{FirstElement, SecondElement} || {FirstElement,SecondElement} &lt;- Tail, SecondElement &lt; PivotSecond])\n ++ [Pivot] ++\n qsort([{FirstElement, SecondElement} || {FirstElement,SecondElement} &lt;- Tail, SecondElement &gt;= PivotSecond]).\n</code></pre>\n" }, { "answer_id": 181548, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 2, "selected": false, "text": "<p>Actually, a better answer:</p>\n\n<p>There's a second version of sort that takes a sorting function:</p>\n\n<pre><code>lists:sort(Fun, List1) -&gt; List2\n</code></pre>\n\n<p>Here's an example that sorts on the second element in a tuple:</p>\n\n<pre><code>lists:sort(fun(A, B) -&gt;\n {A1, A2} = A,\n {B1, B2} = B,\n if\n A2 &gt; B2 -&gt;\n false;\n true -&gt;\n true\n end\n end, YourList).\n</code></pre>\n" }, { "answer_id": 181650, "author": "hcs42", "author_id": 17916, "author_profile": "https://Stackoverflow.com/users/17916", "pm_score": 2, "selected": false, "text": "<p>An improved version of bmdhacks' solution:</p>\n\n<pre><code>lists:sort(fun(A, B) -&gt;\n {_, A2} = A,\n {_, B2} = B,\n A2 =&lt; B2\n end, YourList).\n</code></pre>\n\n<p>Underscores are better then A1 and B1, because the compiler will give warnings\nfor those.</p>\n\n<p>To sort in descending order, just change &lt;= to >=.</p>\n" }, { "answer_id": 181673, "author": "Michał Kwiatkowski", "author_id": 21998, "author_profile": "https://Stackoverflow.com/users/21998", "pm_score": 3, "selected": true, "text": "<p>Have you tried <a href=\"http://www.erlang.org/doc/man/lists.html#keysort-2\" rel=\"nofollow noreferrer\">keysort/2</a> function (or its counterpart <a href=\"http://www.erlang.org/doc/man/lists.html#ukeysort-2\" rel=\"nofollow noreferrer\">ukeysort/2</a>)?</p>\n\n<pre><code>&gt; lists:reverse(lists:keysort(2, [{a,2}, {b,1}, {c, 3}])).\n[{c,3},{a,2},{b,1}]\n</code></pre>\n\n<p>If you don't sort very big lists this is probably the most readable solution you can get.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2727/" ]
I need to sort tuples according to the second element of each tuple but apparently usort/1 only works with the first element. So I have to swap the elements, usort them and swap back.Is there an easier way?Also is there a way to sort in descending order (I know sorting and reversing can be done, but just want to know).
Have you tried [keysort/2](http://www.erlang.org/doc/man/lists.html#keysort-2) function (or its counterpart [ukeysort/2](http://www.erlang.org/doc/man/lists.html#ukeysort-2))? ``` > lists:reverse(lists:keysort(2, [{a,2}, {b,1}, {c, 3}])). [{c,3},{a,2},{b,1}] ``` If you don't sort very big lists this is probably the most readable solution you can get.
181,530
<p>Sometimes I break long conditions in <code>if</code>s onto several lines. The most obvious way to do this is:</p> <pre><code> if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something </code></pre> <p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p> <p>For the moment I'm using:</p> <pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something </code></pre> <p>But this isn't very pretty. :-)</p> <p>Can you recommend an alternative way?</p>
[ { "answer_id": 181553, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 5, "selected": false, "text": "<p>This doesn't improve so much but...</p>\n\n<pre><code>allCondsAreOK = (cond1 == 'val1' and cond2 == 'val2' and\n cond3 == 'val3' and cond4 == 'val4')\n\nif allCondsAreOK:\n do_something\n</code></pre>\n" }, { "answer_id": 181557, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 11, "selected": true, "text": "<p>You don't need to use 4 spaces on your second conditional line. Maybe use:</p>\n\n<pre><code>if (cond1 == 'val1' and cond2 == 'val2' and \n cond3 == 'val3' and cond4 == 'val4'):\n do_something\n</code></pre>\n\n<p>Also, don't forget the whitespace is more flexible than you might think:</p>\n\n<pre><code>if ( \n cond1 == 'val1' and cond2 == 'val2' and \n cond3 == 'val3' and cond4 == 'val4'\n ):\n do_something\nif (cond1 == 'val1' and cond2 == 'val2' and \n cond3 == 'val3' and cond4 == 'val4'):\n do_something\n</code></pre>\n\n<p>Both of those are fairly ugly though.</p>\n\n<p>Maybe lose the brackets (the <a href=\"https://www.python.org/dev/peps/pep-0008/#multiline-if-statements\" rel=\"noreferrer\">Style Guide</a> discourages this though)?</p>\n\n<pre><code>if cond1 == 'val1' and cond2 == 'val2' and \\\n cond3 == 'val3' and cond4 == 'val4':\n do_something\n</code></pre>\n\n<p>This at least gives you some differentiation.</p>\n\n<p>Or even:</p>\n\n<pre><code>if cond1 == 'val1' and cond2 == 'val2' and \\\n cond3 == 'val3' and \\\n cond4 == 'val4':\n do_something\n</code></pre>\n\n<p>I think I prefer:</p>\n\n<pre><code>if cond1 == 'val1' and \\\n cond2 == 'val2' and \\\n cond3 == 'val3' and \\\n cond4 == 'val4':\n do_something\n</code></pre>\n\n<p>Here's the <a href=\"https://www.python.org/dev/peps/pep-0008/#multiline-if-statements\" rel=\"noreferrer\">Style Guide</a>, which (since 2010) recommends using brackets.</p>\n" }, { "answer_id": 181641, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 4, "selected": false, "text": "<p>I suggest moving the <code>and</code> keyword to the second line and indenting all lines containing conditions with two spaces instead of four:</p>\n\n<pre><code>if (cond1 == 'val1' and cond2 == 'val2'\n and cond3 == 'val3' and cond4 == 'val4'):\n do_something\n</code></pre>\n\n<p>This is exactly how I solve this problem in my code. Having a keyword as the first word in the line makes the condition a lot more readable, and reducing the number of spaces further distinguishes condition from action.</p>\n" }, { "answer_id": 181848, "author": "Deestan", "author_id": 6848, "author_profile": "https://Stackoverflow.com/users/6848", "pm_score": 6, "selected": false, "text": "<p>I prefer this style when I have a terribly large if-condition:</p>\n\n<pre><code>if (\n expr1\n and (expr2 or expr3)\n and hasattr(thingy1, '__eq__')\n or status==\"HappyTimes\"\n):\n do_stuff()\nelse:\n do_other_stuff()\n</code></pre>\n" }, { "answer_id": 182050, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 7, "selected": false, "text": "<p>I've resorted to the following in the degenerate case where it's simply AND's or OR's.</p>\n\n<pre><code>if all( [cond1 == 'val1', cond2 == 'val2', cond3 == 'val3', cond4 == 'val4'] ):\n\nif any( [cond1 == 'val1', cond2 == 'val2', cond3 == 'val3', cond4 == 'val4'] ):\n</code></pre>\n\n<p>It shaves a few characters and makes it clear that there's no subtlety to the condition.</p>\n" }, { "answer_id": 182067, "author": "Anders Waldenborg", "author_id": 24082, "author_profile": "https://Stackoverflow.com/users/24082", "pm_score": 2, "selected": false, "text": "<p>\"all\" and \"any\" are nice for the many conditions of same type case. BUT they always evaluates all conditions. As shown in this example:</p>\n\n<pre><code>def c1():\n print \" Executed c1\"\n return False\ndef c2():\n print \" Executed c2\"\n return False\n\n\nprint \"simple and (aborts early!)\"\nif c1() and c2():\n pass\n\nprint\n\nprint \"all (executes all :( )\"\nif all((c1(),c2())):\n pass\n\nprint\n</code></pre>\n" }, { "answer_id": 183206, "author": "Kevin Little", "author_id": 14028, "author_profile": "https://Stackoverflow.com/users/14028", "pm_score": 6, "selected": false, "text": "<p><em>Someone</em> has to champion use of vertical whitespace here! :)</p>\n\n<pre><code>if ( cond1 == val1\n and cond2 == val2\n and cond3 == val3\n ):\n do_stuff()\n</code></pre>\n\n<p>This makes each condition clearly visible. It also allows cleaner expression of more complex conditions:</p>\n\n<pre><code>if ( cond1 == val1\n or \n ( cond2_1 == val2_1\n and cond2_2 &gt;= val2_2\n and cond2_3 != bad2_3\n )\n ):\n do_more_stuff()\n</code></pre>\n\n<p>Yes, we're trading off a bit of vertical real estate for clarity. Well worth it IMO.</p>\n" }, { "answer_id": 183889, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 1, "selected": false, "text": "<p>Just a few other random ideas for completeness's sake. If they work for you, use them. Otherwise, you're probably better off trying something else.</p>\n\n<p>You could also do this with a dictionary:</p>\n\n<pre><code>&gt;&gt;&gt; x = {'cond1' : 'val1', 'cond2' : 'val2'}\n&gt;&gt;&gt; y = {'cond1' : 'val1', 'cond2' : 'val2'}\n&gt;&gt;&gt; x == y\nTrue\n</code></pre>\n\n<p>This option is more complicated, but you may also find it useful:</p>\n\n<pre><code>class Klass(object):\n def __init__(self, some_vars):\n #initialize conditions here\n def __nonzero__(self):\n return (self.cond1 == 'val1' and self.cond2 == 'val2' and\n self.cond3 == 'val3' and self.cond4 == 'val4')\n\nfoo = Klass()\nif foo:\n print \"foo is true!\"\nelse:\n print \"foo is false!\"\n</code></pre>\n\n<p>Dunno if that works for you, but it's another option to consider. Here's one more way:</p>\n\n<pre><code>class Klass(object):\n def __init__(self):\n #initialize conditions here\n def __eq__(self):\n return (self.cond1 == 'val1' and self.cond2 == 'val2' and\n self.cond3 == 'val3' and self.cond4 == 'val4')\n\nx = Klass(some_values)\ny = Klass(some_other_values)\nif x == y:\n print 'x == y'\nelse:\n print 'x!=y'\n</code></pre>\n\n<p>The last two I haven't tested, but the concepts should be enough to get you going if that's what you want to go with.</p>\n\n<p>(And for the record, if this is just a one time thing, you're probably just better off using the method you presented at first. If you're doing the comparison in lots of places, these methods may enhance readability enough to make you not feel so bad about the fact that they are kind of hacky.)</p>\n" }, { "answer_id": 185748, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 2, "selected": false, "text": "<p>What if we only insert an additional blank line between the condition and the body and do the rest in the canonical way?</p>\n\n<pre><code>if (cond1 == 'val1' and cond2 == 'val2' and\n cond3 == 'val3' and cond4 == 'val4'):\n\n do_something\n</code></pre>\n\n<p>p.s. I always use tabs, not spaces; I cannot fine-tune...</p>\n" }, { "answer_id": 3004525, "author": "psihodelia", "author_id": 215571, "author_profile": "https://Stackoverflow.com/users/215571", "pm_score": 0, "selected": false, "text": "<p>Pack your conditions into a list, then do smth. like:</p>\n\n<pre><code>if False not in Conditions:\n do_something\n</code></pre>\n" }, { "answer_id": 4689224, "author": "Fred Nurk", "author_id": 511601, "author_profile": "https://Stackoverflow.com/users/511601", "pm_score": 2, "selected": false, "text": "<p>(I've lightly modified the identifiers as fixed-width names aren't representative of real code – at least not real code that I encounter – and will belie an example's readability.)</p>\n\n<pre><code>if (cond1 == \"val1\" and cond22 == \"val2\"\nand cond333 == \"val3\" and cond4444 == \"val4\"):\n do_something\n</code></pre>\n\n<p>This works well for \"and\" and \"or\" (it's important that they're first on the second line), but much less so for other long conditions. Fortunately, the former seem to be the more common case while the latter are often easily rewritten with a temporary variable. (It's usually not hard, but it can be difficult or much less obvious/readable to preserve the short-circuiting of \"and\"/\"or\" when rewriting.)</p>\n\n<p>Since I found this question from <a href=\"http://eli.thegreenplace.net/2011/01/14/how-python-affected-my-cc-brace-style/\" rel=\"nofollow\">your blog post about C++</a>, I'll include that my C++ style is identical:</p>\n\n<pre><code>if (cond1 == \"val1\" and cond22 == \"val2\"\nand cond333 == \"val3\" and cond4444 == \"val4\") {\n do_something\n}\n</code></pre>\n" }, { "answer_id": 4690241, "author": "krawyoti", "author_id": 130961, "author_profile": "https://Stackoverflow.com/users/130961", "pm_score": 5, "selected": false, "text": "<p>Here's my very personal take: long conditions are (in my view) a code smell that suggests refactoring into a boolean-returning function/method. For example:</p>\n\n<pre><code>def is_action__required(...):\n return (cond1 == 'val1' and cond2 == 'val2'\n and cond3 == 'val3' and cond4 == 'val4')\n</code></pre>\n\n<p>Now, if I found a way to make multi-line conditions look good, I would probably find myself content with having them and skip the refactoring.</p>\n\n<p>On the other hand, having them perturb my aesthetic sense acts as an incentive for refactoring.</p>\n\n<p>My conclusion, therefore, is that multiple line conditions should look ugly and this is an incentive to avoid them.</p>\n" }, { "answer_id": 4692294, "author": "Marius Gedminas", "author_id": 110151, "author_profile": "https://Stackoverflow.com/users/110151", "pm_score": 2, "selected": false, "text": "<p>I'm surprised not to see my preferred solution,</p>\n\n<pre><code>if (cond1 == 'val1' and cond2 == 'val2'\n and cond3 == 'val3' and cond4 == 'val4'):\n do_something\n</code></pre>\n\n<p>Since <code>and</code> is a keyword, it gets highlighted by my editor, and looks sufficiently different from the do_something below it.</p>\n" }, { "answer_id": 4740630, "author": "Apalala", "author_id": 545637, "author_profile": "https://Stackoverflow.com/users/545637", "pm_score": 3, "selected": false, "text": "<p>Adding to what @krawyoti said... Long conditions smell because they are difficult to read and difficult to understand. Using a function or a variable makes the code clearer. In Python, I prefer to use vertical space, enclose parenthesis, and place the logical operators at the beginning of each line so the expressions don't look like \"floating\".</p>\n\n<pre><code>conditions_met = (\n cond1 == 'val1' \n and cond2 == 'val2' \n and cond3 == 'val3' \n and cond4 == 'val4'\n )\nif conditions_met:\n do_something\n</code></pre>\n\n<p>If the conditions need to be evaluated more than once, as in a <code>while</code> loop, then using a local function is best.</p>\n" }, { "answer_id": 7511872, "author": "xorsyst", "author_id": 386465, "author_profile": "https://Stackoverflow.com/users/386465", "pm_score": 0, "selected": false, "text": "<p>I find that when I have long conditions, I often have a short code body. In that case, I just double-indent the body, thus:</p>\n\n<pre><code>if (cond1 == 'val1' and cond2 == 'val2' and\n cond3 == 'val3' and cond4 == 'val4'):\n do_something\n</code></pre>\n" }, { "answer_id": 9682878, "author": "Dima Tisnek", "author_id": 705086, "author_profile": "https://Stackoverflow.com/users/705086", "pm_score": 0, "selected": false, "text": "<pre><code> if cond1 == 'val1' and \\\n cond2 == 'val2' and \\\n cond3 == 'val3' and \\\n cond4 == 'val4':\n do_something\n</code></pre>\n\n<p>or if this is clearer:</p>\n\n<pre><code> if cond1 == 'val1'\\\n and cond2 == 'val2'\\\n and cond3 == 'val3'\\\n and cond4 == 'val4':\n do_something\n</code></pre>\n\n<p>There is no reason indent should be a multiple of 4 in this case, e.g. see \"Aligned with opening delimiter\":</p>\n\n<p><a href=\"http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=Indentation#Indentation\" rel=\"nofollow\">http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=Indentation#Indentation</a></p>\n" }, { "answer_id": 15264532, "author": "rgenito", "author_id": 1418001, "author_profile": "https://Stackoverflow.com/users/1418001", "pm_score": 3, "selected": false, "text": "<p>Personally, I like to add meaning to long if-statements. I would have to search through code to find an appropriate example, but here's the first example that comes to mind: let's say I happen to run into some quirky logic where I want to display a certain page depending on many variables.</p>\n\n<p>English: \"If the logged-in user is NOT an administrator teacher, but is just a regular teacher, and is not a student themselves...\"</p>\n\n<pre><code>if not user.isAdmin() and user.isTeacher() and not user.isStudent():\n doSomething()\n</code></pre>\n\n<p>Sure this might look fine, but reading those if statements is a lot of work. How about we assign the logic to label that makes sense. The \"label\" is actually the variable name:</p>\n\n<pre><code>displayTeacherPanel = not user.isAdmin() and user.isTeacher() and not user.isStudent()\nif displayTeacherPanel:\n showTeacherPanel()\n</code></pre>\n\n<p>This may seem silly, but you might have yet another condition where you ONLY want to display another item if, and only if, you're displaying the teacher panel OR if the user has access to that other specific panel by default:</p>\n\n<pre><code>if displayTeacherPanel or user.canSeeSpecialPanel():\n showSpecialPanel()\n</code></pre>\n\n<p>Try writing the above condition without using variables to store and label your logic, and not only do you end up with a very messy, hard-to-read logical statement, but you also just repeated yourself. While there are reasonable exceptions, remember: Don't Repeat Yourself (DRY).</p>\n" }, { "answer_id": 25085957, "author": "tomekwi", "author_id": 2816199, "author_profile": "https://Stackoverflow.com/users/2816199", "pm_score": 2, "selected": false, "text": "<p>What I usually do is:</p>\n\n<pre><code>if (cond1 == 'val1' and cond2 == 'val2' and\n cond3 == 'val3' and cond4 == 'val4'\n ):\n do_something\n</code></pre>\n\n<p>this way the closing brace and colon visually mark the end of our condition.</p>\n" }, { "answer_id": 26414728, "author": "user1487551", "author_id": 1487551, "author_profile": "https://Stackoverflow.com/users/1487551", "pm_score": 0, "selected": false, "text": "<p>Here's another approach:</p>\n\n<pre><code>cond_list = ['cond1 == \"val1\"','cond2==\"val2\"','cond3==\"val3\"','cond4==\"val4\"']\nif all([eval(i) for i in cond_list]):\n do something\n</code></pre>\n\n<p>This also makes it easy to add another condition easily without changing the if statement by simply appending another condition to the list:</p>\n\n<pre><code>cond_list.append('cond5==\"val5\"')\n</code></pre>\n" }, { "answer_id": 27008512, "author": "zkanda", "author_id": 3171548, "author_profile": "https://Stackoverflow.com/users/3171548", "pm_score": 3, "selected": false, "text": "<p>Here's what I do, remember that \"all\" and \"any\" accepts an iterable, so I just put a long condition in a list and let \"all\" do the work.</p>\n\n<pre><code>condition = [cond1 == 'val1', cond2 == 'val2', cond3 == 'val3', cond4 == 'val4']\n\nif all(condition):\n do_something\n</code></pre>\n" }, { "answer_id": 27100017, "author": "ThorSummoner", "author_id": 1695680, "author_profile": "https://Stackoverflow.com/users/1695680", "pm_score": 3, "selected": false, "text": "<p>Plain and simple, also passes pep8 checks:</p>\n\n<pre><code>if (\n cond1 and\n cond2\n):\n print(\"Hello World!\")\n</code></pre>\n\n<hr>\n\n<p>In recent times I have been preferring the <code>all</code> and <code>any</code> functions, since I rarely mix And and Or comparisons this works well, and has the additional advantage of Failing Early with generators comprehension:</p>\n\n<pre><code>if all([\n cond1,\n cond2,\n]):\n print(\"Hello World!\")\n</code></pre>\n\n<p>Just remember to pass in a single iterable! Passing in N-arguments is not correct.</p>\n\n<p>Note: <code>any</code> is like many <code>or</code> comparisons, <code>all</code> is like many <code>and</code> comparisons.</p>\n\n<hr>\n\n<p>This combines nicely with generator comprehensions, for example:</p>\n\n<pre><code># Check if every string in a list contains a substring:\nmy_list = [\n 'a substring is like a string', \n 'another substring'\n]\n\nif all('substring' in item for item in my_list):\n print(\"Hello World!\")\n\n# or\n\nif all(\n 'substring' in item\n for item in my_list\n):\n print(\"Hello World!\")\n</code></pre>\n\n<p>More on: <a href=\"https://stackoverflow.com/q/364802/1695680\">generator comprehension</a></p>\n" }, { "answer_id": 27279883, "author": "El Ninja Trepador", "author_id": 2026122, "author_profile": "https://Stackoverflow.com/users/2026122", "pm_score": 1, "selected": false, "text": "<p>I've been struggling to find a decent way to do this as well, so I just came up with an idea (not a silver bullet, since this is mainly a matter of taste).</p>\n\n<pre><code>if bool(condition1 and\n condition2 and\n ...\n conditionN):\n foo()\n bar()\n</code></pre>\n\n<p>I find a few merits in this solution compared to others I've seen, namely, you get exactly an extra 4 spaces of indentation (bool), allowing all conditions to line up vertically, and the body of the if statement can be indented in a clear(ish) way. This also keeps the benefits of short-circuit evaluation of boolean operators, but of course adds the overhead of a function call that basically does nothing. You could argue (validly) that any function returning its argument could be used here instead of bool, but like I said, it's just an idea and it's ultimately a matter of taste.</p>\n\n<p>Funny enough, as I was writing this and thinking about the \"problem\", I came up with <em>yet another</em> idea, which removes the overhead of a function call. Why not indicate that we're about to enter a complex condition by using extra pairs of parentheses? Say, 2 more, to give a nice 2 space indent of the sub-conditions relative to the body of the if statement. Example:</p>\n\n<pre><code>if (((foo and\n bar and\n frob and\n ninja_bear))):\n do_stuff()\n</code></pre>\n\n<p>I kind of like this because when you look at it, a bell immediatelly rings in your head saying <em>\"hey, there's a complex thing going on here!\"</em>. Yes, I know that parentheses don't help readability, but these conditions should appear rarely enough, and when they do show up, you are going to have to stop and read them carefuly anyway (because they're <strong>complex</strong>).</p>\n\n<p>Anyway, just two more proposals that I haven't seen here. Hope this helps someone :)</p>\n" }, { "answer_id": 28867664, "author": "Artur Gaspar", "author_id": 286655, "author_profile": "https://Stackoverflow.com/users/286655", "pm_score": 0, "selected": false, "text": "<p>I usually use: </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if ((cond1 == 'val1' and cond2 == 'val2' and\n cond3 == 'val3' and cond4 == 'val4')):\n do_something()\n</code></pre>\n" }, { "answer_id": 31231248, "author": "Mark Amery", "author_id": 1709587, "author_profile": "https://Stackoverflow.com/users/1709587", "pm_score": 4, "selected": false, "text": "<p>It seems worth quoting <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP 0008</a> (Python's official style guide), since it comments upon this issue at modest length:</p>\n\n<blockquote>\n <p>When the conditional part of an <code>if</code> -statement is long enough to require that it be written across multiple lines, it's worth noting that the combination of a two character keyword (i.e. <code>if</code> ), plus a single space, plus an opening parenthesis creates a natural 4-space indent for the subsequent lines of the multiline conditional. This can produce a visual conflict with the indented suite of code nested inside the <code>if</code> -statement, which would also naturally be indented to 4 spaces. This PEP takes no explicit position on how (or whether) to further visually distinguish such conditional lines from the nested suite inside the <code>if</code> -statement. Acceptable options in this situation include, but are not limited to:</p>\n\n<pre><code># No extra indentation.\nif (this_is_one_thing and\n that_is_another_thing):\n do_something()\n\n# Add a comment, which will provide some distinction in editors\n# supporting syntax highlighting.\nif (this_is_one_thing and\n that_is_another_thing):\n # Since both conditions are true, we can frobnicate.\n do_something()\n\n# Add some extra indentation on the conditional continuation line.\nif (this_is_one_thing\n and that_is_another_thing):\n do_something()\n</code></pre>\n</blockquote>\n\n<p>Note the \"not limited to\" in the quote above; besides the approaches suggested in the style guide, some of the ones suggested in other answers to this question are acceptable too.</p>\n" }, { "answer_id": 34117413, "author": "Gautam", "author_id": 582421, "author_profile": "https://Stackoverflow.com/users/582421", "pm_score": 0, "selected": false, "text": "<p>if our if &amp; an else condition has to execute multiple statement inside of it than we can write like below.\nEvery when we have if else example with one statement inside of it .</p>\n\n<p>Thanks it work for me.</p>\n\n<pre><code>#!/usr/bin/python\nimport sys\nnumberOfArgument =len(sys.argv)\nweblogic_username =''\nweblogic_password = ''\nweblogic_admin_server_host =''\nweblogic_admin_server_port =''\n\n\nif numberOfArgument == 5:\n weblogic_username = sys.argv[1]\n weblogic_password = sys.argv[2]\n weblogic_admin_server_host =sys.argv[3]\n weblogic_admin_server_port=sys.argv[4]\nelif numberOfArgument &lt;5:\n print \" weblogic UserName, weblogic Password and weblogic host details are Mandatory like, defalutUser, passwordForDefaultUser, t3s://server.domainname:7001 .\"\n weblogic_username = raw_input(\"Enter Weblogic user Name\")\n weblogic_password = raw_input('Enter Weblogic user Password')\n weblogic_admin_server_host = raw_input('Enter Weblogic admin host ')\n weblogic_admin_server_port = raw_input('Enter Weblogic admin port')\n#enfelif\n#endIf\n</code></pre>\n" }, { "answer_id": 38775892, "author": "SarcasticSully", "author_id": 4318342, "author_profile": "https://Stackoverflow.com/users/4318342", "pm_score": 1, "selected": false, "text": "<p>You could split it into two lines</p>\n\n<pre><code>total = cond1 == 'val' and cond2 == 'val2' and cond3 == 'val3' and cond4 == val4\nif total:\n do_something()\n</code></pre>\n\n<p>Or even add on one condition at a time. That way, at least it separates the clutter from the <code>if</code>.</p>\n" }, { "answer_id": 40871775, "author": "SMGreenfield", "author_id": 516545, "author_profile": "https://Stackoverflow.com/users/516545", "pm_score": 2, "selected": false, "text": "<p>I know this thread is old, but I have some Python 2.7 code and PyCharm (4.5) still complains about this case:</p>\n\n<pre><code>if foo is not None:\n if (cond1 == 'val1' and cond2 == 'val2' and\n cond3 == 'val3' and cond4 == 'val4'):\n # some comment about do_something\n do_something\n</code></pre>\n\n<p>Even with the PEP8 warning \"visually indented line with same indent as next logical line\", the actual code is completely OK? It's not \"over-indenting?\"</p>\n\n<p>...there are times I wish Python would've bit the bullet and just gone with curly braces. I wonder how many bugs have been accidentally introduced over the years due to accidental mis-indentation...</p>\n" }, { "answer_id": 44601456, "author": "Stof", "author_id": 1490061, "author_profile": "https://Stackoverflow.com/users/1490061", "pm_score": 2, "selected": false, "text": "<p>All respondents that also provide multi-conditionals for the if statement is just as ugly as the problem presented. You don't solve this problem by doing the same thing.. </p>\n\n<p>Even the PEP 0008 answer is repulsive.</p>\n\n<p>Here is a far more readable approach</p>\n\n<pre><code>condition = random.randint(0, 100) # to demonstrate\nanti_conditions = [42, 67, 12]\nif condition not in anti_conditions:\n pass\n</code></pre>\n\n<p>Want me to eat my words? Convince me you need multi-conditionals and I'll literally print this and eat it for your amusement.</p>\n" }, { "answer_id": 45238436, "author": "ryanjdillon", "author_id": 943773, "author_profile": "https://Stackoverflow.com/users/943773", "pm_score": 2, "selected": false, "text": "<p>I think @zkanda's solution would be good with a minor twist. If you had your conditions and values in their own respective lists, you could use a list comprehension to do the comparison, which would make things a bit more general for adding condition/value pairs.</p>\n\n<pre><code>conditions = [1, 2, 3, 4]\nvalues = [1, 2, 3, 4]\nif all([c==v for c, v in zip(conditions, values)]):\n # do something\n</code></pre>\n\n<p>If I did want to hard-code a statement like this, I would write it like this for legibility:</p>\n\n<pre><code>if (condition1==value1) and (condition2==value2) and \\\n (condition3==value3) and (condition4==value4):\n</code></pre>\n\n<p>And just to throw another solution out there with an <a href=\"https://docs.python.org/3.5/library/operator.html#inplace-operators\" rel=\"nofollow noreferrer\"><code>iand</code> operator</a>:</p>\n\n<pre><code>proceed = True\nfor c, v in zip(conditions, values):\n proceed &amp;= c==v\n\nif proceed:\n # do something\n</code></pre>\n" }, { "answer_id": 58563138, "author": "Nader Belal", "author_id": 8533804, "author_profile": "https://Stackoverflow.com/users/8533804", "pm_score": 1, "selected": false, "text": "<p>Pardon my noobness, but it happens that I'm not as knowledgeable of #Python as anyone of you here, but it happens that I have found something similar when scripting my own objects in a 3D BIM modeling, so I will adapt my algorithm to that of python.</p>\n\n<p>The problem that I find here, is double sided:</p>\n\n<ol>\n<li>Values my seem foreign for someone who may try to decipher the script.</li>\n<li>Code maintenance will come at a high cost, if those values are changed (most probable), or if new conditions must be added (broken schema)</li>\n</ol>\n\n<p>Do to bypass all these problems, your script must go like this</p>\n\n<pre><code>param_Val01 = Value 01 #give a meaningful name for param_Val(i) preferable an integer\nparam_Val02 = Value 02\nparam_Val03 = Value 03\nparam_Val04 = Value 04 # and ... etc\n\nconditions = 0 # this is a value placeholder\n\n########\nAdd script that if true will make:\n\nconditions = conditions + param_Val01 #value of placeholder is updated\n########\n\n### repeat as needed\n\n\nif conditions = param_Val01 + param_Val02 + param_Val03 + param_Val04:\n do something\n</code></pre>\n\n<p>Pros of this method:</p>\n\n<ol>\n<li><p>Script is readable.</p></li>\n<li><p>Script can be easy maintained.</p></li>\n<li>conditions is a 1 comparison operation to a sum of values that represents the desired conditions.</li>\n<li>No need for multilevel conditions</li>\n</ol>\n\n<p>Hope it help you all</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
Sometimes I break long conditions in `if`s onto several lines. The most obvious way to do this is: ``` if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something ``` Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces. For the moment I'm using: ``` if ( cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something ``` But this isn't very pretty. :-) Can you recommend an alternative way?
You don't need to use 4 spaces on your second conditional line. Maybe use: ``` if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something ``` Also, don't forget the whitespace is more flexible than you might think: ``` if ( cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4' ): do_something if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something ``` Both of those are fairly ugly though. Maybe lose the brackets (the [Style Guide](https://www.python.org/dev/peps/pep-0008/#multiline-if-statements) discourages this though)? ``` if cond1 == 'val1' and cond2 == 'val2' and \ cond3 == 'val3' and cond4 == 'val4': do_something ``` This at least gives you some differentiation. Or even: ``` if cond1 == 'val1' and cond2 == 'val2' and \ cond3 == 'val3' and \ cond4 == 'val4': do_something ``` I think I prefer: ``` if cond1 == 'val1' and \ cond2 == 'val2' and \ cond3 == 'val3' and \ cond4 == 'val4': do_something ``` Here's the [Style Guide](https://www.python.org/dev/peps/pep-0008/#multiline-if-statements), which (since 2010) recommends using brackets.
181,532
<p>I have a text string value that I'd like to persist from one web page to another without using query strings or the session/view states. I've been trying to get the ASP http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hiddenfield.aspx">HiddenField control to pass information from one web form to a <i>different</i> form.<br><br> All the hiddenfield control examples that I've seen is to preserve round trips from the client to the server for the same form.<br><br> Is there way for a form to access the ASP controls (and their values) from the previously-rendered form? Or is the initial form simply disposed of in memory by the time the second form executes it's <i>OnLoad</i> method?</p>
[ { "answer_id": 181540, "author": "Mez", "author_id": 20010, "author_profile": "https://Stackoverflow.com/users/20010", "pm_score": 0, "selected": false, "text": "<p>I would presume that the Response.Redirect() sends a Location: HTTP header to do a redirect.</p>\n\n<p>As HTTP is stateless, I'd also presume that these variables are inaccessible.</p>\n\n<p>There are however, solutions.</p>\n\n<ol>\n<li>Print a form with hidden fields, and use javascript to submit it</li>\n<li>Redirect in the code internally (load up the thing it needs to get to manually)</li>\n<li>Store the data in some temporary database table somewhere, and pass along a unique ID</li>\n</ol>\n\n<p>However, from my experience, I can't understand why you might need to do this (other than re-submitting a form after a user authentication - which hopefully you should be able to use method 2 for</p>\n" }, { "answer_id": 181544, "author": "Damien_The_Unbeliever", "author_id": 15498, "author_profile": "https://Stackoverflow.com/users/15498", "pm_score": 0, "selected": false, "text": "<p>Remember, a Response.Redirect instructs the browser to issue another request to the server. So far as the server is concerned, this next request is indistinguishable from any other incoming request. It's certainly not connected to a previous form in any way.</p>\n\n<p>Could you explain your aversion to storage in the session, so we can propose some viable alternatives?</p>\n" }, { "answer_id": 181645, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 2, "selected": false, "text": "<p>If both pages live in the same application you can use Server.Transfer:</p>\n\n<p>firstpage.aspx:</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n Server.Transfer(\"~/secondpage.aspx\");\n}\n</code></pre>\n\n<p>secondpage.aspx:</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n Page previousPage = (Page) HttpContext.Current.PreviousHandler;\n Label previousPageControl = (Label) previousPage.FindControl(\"theLabel\");\n label.Text =previousPageControl.Text;\n}\n</code></pre>\n\n<p>A somewhat better solution would be implementing an interface on your first page where you expose properties for the values needed by the second page.</p>\n" }, { "answer_id": 181661, "author": "martin", "author_id": 8421, "author_profile": "https://Stackoverflow.com/users/8421", "pm_score": 2, "selected": false, "text": "<p>You can't get the previous page fields with Response.Redirect.\nYou can with <a href=\"http://msdn.microsoft.com/en-us/library/ms178139.aspx\" rel=\"nofollow noreferrer\">cross page posting</a> :</p>\n\n<pre><code>if (Page.PreviousPage != null)\n{\n TextBox SourceTextBox = \n (TextBox)Page.PreviousPage.FindControl(\"TextBox1\");\n if (SourceTextBox != null)\n {\n Label1.Text = SourceTextBox.Text;\n }\n}\n</code></pre>\n" }, { "answer_id": 181783, "author": "dwynne", "author_id": 26058, "author_profile": "https://Stackoverflow.com/users/26058", "pm_score": 2, "selected": false, "text": "<p>Quick answer is no. As others have noted, you can use Server.Transfer and then you can - however this is to be used with caution. It is a \"server side redirect\" eg.</p>\n\n<p>Your user is on <a href=\"http://mysite.com/Page1.aspx\" rel=\"nofollow noreferrer\">http://mysite.com/Page1.aspx</a> they click a button and you perform a Server.Transfer(\"Page2.aspx\"). Page2.aspx will be rendered in their browser, but the URL will still be Page1.aspx, this can cause confusion and mess up back/forward navigation.</p>\n\n<p>Personally I would only use Server.Transfer as a last resort - in the world of the web, sharing data across pages generally means you need to use a storage mechanism; Cookie, QueryString, Session, Database - take your pick.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26037/" ]
I have a text string value that I'd like to persist from one web page to another without using query strings or the session/view states. I've been trying to get the ASP http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hiddenfield.aspx">HiddenField control to pass information from one web form to a *different* form. All the hiddenfield control examples that I've seen is to preserve round trips from the client to the server for the same form. Is there way for a form to access the ASP controls (and their values) from the previously-rendered form? Or is the initial form simply disposed of in memory by the time the second form executes it's *OnLoad* method?
If both pages live in the same application you can use Server.Transfer: firstpage.aspx: ``` protected void Page_Load(object sender, EventArgs e) { Server.Transfer("~/secondpage.aspx"); } ``` secondpage.aspx: ``` protected void Page_Load(object sender, EventArgs e) { Page previousPage = (Page) HttpContext.Current.PreviousHandler; Label previousPageControl = (Label) previousPage.FindControl("theLabel"); label.Text =previousPageControl.Text; } ``` A somewhat better solution would be implementing an interface on your first page where you expose properties for the values needed by the second page.
181,537
<p>So basically we have lots of SharePoint usage log files generated by our SharePoint 2007 site and we would like to make sense of them. For that we're thinking of reading the log files and dumping into a database with the appropriate columns and all. Now I was going to make an SSIS package to read all the text files and extract the data when I came across LogParser. Is there a way to use LogParser to dump data into an Sql Server database or the SSIS way is better? Or is there any other better way to use the SharePoint usage logs?</p>
[ { "answer_id": 181771, "author": "massimogentilini", "author_id": 11673, "author_profile": "https://Stackoverflow.com/users/11673", "pm_score": 2, "selected": false, "text": "<p>This is the script we use to load IIS log files in a SQL Server database:</p>\n\n<pre><code>LogParser \"SELECT * INTO &lt;TABLENAME&gt; FROM &lt;LogFileName&gt;\" -o:SQL -server:&lt;servername&gt; -database:&lt;databasename&gt; -driver:\"SQL Server\" -username:sa -password:xxxxx -createTable:ON\n</code></pre>\n\n<p>The <code>&lt;tablename&gt;, &lt;logfilename&gt;, &lt;servername&gt;, &lt;databasename&gt;</code> and sa password need to be changed according to your specs.</p>\n\n<p>From my experience LogParser works really well to load data from IIS logs to SQL Server, so a mixed approach is the best:</p>\n\n<ul>\n<li>Load raw data from IIS log to SQL Server using LogParser</li>\n<li>Use SSIS to extract and manipulate data from the temporary table containing the raw data in the final table you'll use for reporting.</li>\n</ul>\n" }, { "answer_id": 181822, "author": "Malik Daud Ahmad Khokhar", "author_id": 1688440, "author_profile": "https://Stackoverflow.com/users/1688440", "pm_score": 1, "selected": false, "text": "<p>Sorry I found out that Sharepoint Logs are not the same as IIS logs. They are different. How can we parse them?</p>\n" }, { "answer_id": 182361, "author": "Nico", "author_id": 22970, "author_profile": "https://Stackoverflow.com/users/22970", "pm_score": 2, "selected": false, "text": "<p>You'll have to write a plugin to logparser. Here is what I did:</p>\n\n<blockquote>\n<pre><code>[Guid(\"1CC338B9-4F5F-4bf2-86AE-55C865CF7159\")]\npublic class SPUsageLogParserPlugin : ILogParserInputContext\n{\n private FileStream stream = null;\n private BinaryReader br = null;\n private object[] currentEntry = null;\n</code></pre>\n</blockquote>\n\n<pre><code> public SPUsageLogParserPlugin() { }\n\n #region LogParser\n\n protected const int GENERAL_HEADER_LENGTH = 300;\n protected const int ENTRY_HEADER_LENGTH = 50;\n protected string[] columns = {\"TimeStamp\",\n \"SiteGUID\",\n \"SiteUrl\",\n \"WebUrl\",\n \"Document\",\n \"User\",\n \"QueryString\",\n \"Referral\",\n \"UserAgent\",\n \"Command\"};\n\n protected string ReadString(BinaryReader br)\n {\n StringBuilder buffer = new StringBuilder();\n char c = br.ReadChar();\n while (c != 0) {\n buffer.Append(c);\n c = br.ReadChar();\n }\n return buffer.ToString();\n }\n\n #endregion\n\n #region ILogParserInputContext Members\n\n enum FieldType\n {\n Integer = 1,\n Real = 2,\n String = 3,\n Timestamp = 4\n }\n\n public void OpenInput(string from)\n {\n stream = File.OpenRead(from);\n br = new BinaryReader(stream);\n br.ReadBytes(GENERAL_HEADER_LENGTH);\n }\n\n public int GetFieldCount()\n {\n return columns.Length;\n }\n\n public string GetFieldName(int index)\n {\n return columns[index];\n }\n\n public int GetFieldType(int index)\n {\n if (index == 0) {\n // TimeStamp\n return (int)FieldType.Timestamp;\n } else {\n // Other fields\n return (int)FieldType.String;\n }\n }\n\n public bool ReadRecord()\n {\n if (stream.Position &lt; stream.Length) {\n br.ReadBytes(ENTRY_HEADER_LENGTH); // Entry Header\n\n string webappguid = ReadString(br);\n\n DateTime timestamp = DateTime.ParseExact(ReadString(br), \"HH:mm:ss\", null);\n string siteUrl = ReadString(br);\n string webUrl = ReadString(br);\n string document = ReadString(br);\n string user = ReadString(br);\n string query = ReadString(br);\n string referral = ReadString(br);\n string userAgent = ReadString(br);\n string guid = ReadString(br);\n string command = ReadString(br);\n\n currentEntry = new object[] { timestamp, webappguid, siteUrl, webUrl, document, user, query, referral, userAgent, command };\n return true;\n } else {\n currentEntry = new object[] { };\n return false;\n }\n }\n\n public object GetValue(int index)\n {\n return currentEntry[index];\n }\n\n public void CloseInput(bool abort)\n {\n br.Close();\n stream.Dispose();\n stream = null;\n br = null;\n }\n\n #endregion\n}\n</code></pre>\n" }, { "answer_id": 207738, "author": "Alex Angas", "author_id": 6651, "author_profile": "https://Stackoverflow.com/users/6651", "pm_score": 2, "selected": false, "text": "<p>If you want more in-depth reporting and have the cash and computer power you could look at <a href=\"http://www.nintex.com/Nproducts/Reporting.aspx\" rel=\"nofollow noreferrer\">Nintex Reporting</a>. I've seen a demo of it and it's very thorough, however it needs to continuously run on your system. Looks cool though.</p>\n" }, { "answer_id": 220561, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": 2, "selected": false, "text": "<p>This is the <a href=\"http://weblogs.asp.net/soever/archive/2005/05/29/409614.aspx\" rel=\"nofollow noreferrer\">blog post</a> I used to get all the info needed.\nIt is not necessary to go to the length of custom code.</p>\n\n<p>In brief, create table script:</p>\n\n<pre><code>CREATE TABLE [dbo].[STSlog](\n [application] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,\n [date] [datetime] NULL,\n [time] [datetime] NULL,\n [username] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,\n [computername] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,\n [method] [varchar](16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,\n [siteURL] [varchar](2048) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,\n [webURL] [varchar](2048) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,\n [docName] [varchar](2048) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,\n [bytes] [int] NULL,\n [queryString] [varchar](2048) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,\n [userAgent] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,\n [referer] [varchar](2048) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,\n [bitFlags] [smallint] NULL,\n [status] [smallint] NULL,\n [siteGuid] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL\n) ON [PRIMARY]\n</code></pre>\n\n<p>Call to make log parser load in the data for a file</p>\n\n<pre><code>\"C:\\projects\\STSLogParser\\STSLogParser.exe\" 2005-01-01 \"c:\\projects\\STSlog\\2005-01-01\\00.log\" c:\\projects\\logparsertmp\\stslog.csv\n\"C:\\Program Files\\Log Parser 2.2\\logparser.exe\" \"SELECT 'SharePointPortal' as application, TO_DATE(TO_UTCTIME(TO_TIMESTAMP(TO_TIMESTAMP(date, 'yyyy-MM-dd'), TO_TIMESTAMP(time, 'hh:mm:ss')))) AS date, TO_TIME( TO_UTCTIME( TO_TIMESTAMP(TO_TIMESTAMP(date, 'yyyy-MM-dd'), TO_TIMESTAMP(time, 'hh:mm:ss')))), UserName as username, 'SERVERNAME' as computername, 'GET' as method, SiteURL as siteURL, WebURL as webURL, DocName as docName, cBytes as bytes, QueryString as queryString, UserAgent as userAgent, RefURL as referer, TO_INT(bitFlags) as bitFlags, TO_INT(HttpStatus) as status, TO_STRING(SiteGuid) as siteGuid INTO STSlog FROM c:\\projects\\logparsertmp\\stslog.csv WHERE (username IS NOT NULL) AND (TO_LOWERCASE(username) NOT IN (domain\\serviceaccount))\" -i:CSV -headerRow:ON -o:SQL -server:localhost -database:SharePoint_SA_IN -clearTable:ON\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1688440/" ]
So basically we have lots of SharePoint usage log files generated by our SharePoint 2007 site and we would like to make sense of them. For that we're thinking of reading the log files and dumping into a database with the appropriate columns and all. Now I was going to make an SSIS package to read all the text files and extract the data when I came across LogParser. Is there a way to use LogParser to dump data into an Sql Server database or the SSIS way is better? Or is there any other better way to use the SharePoint usage logs?
This is the script we use to load IIS log files in a SQL Server database: ``` LogParser "SELECT * INTO <TABLENAME> FROM <LogFileName>" -o:SQL -server:<servername> -database:<databasename> -driver:"SQL Server" -username:sa -password:xxxxx -createTable:ON ``` The `<tablename>, <logfilename>, <servername>, <databasename>` and sa password need to be changed according to your specs. From my experience LogParser works really well to load data from IIS logs to SQL Server, so a mixed approach is the best: * Load raw data from IIS log to SQL Server using LogParser * Use SSIS to extract and manipulate data from the temporary table containing the raw data in the final table you'll use for reporting.
181,543
<p>There seems to be a lot of heated discussion on the net about the changes to the reduce() function in python 3.0 and how it should be removed. I am having a little difficulty understanding why this is the case; I find it quite reasonable to use it in a variety of cases. If the contempt was simply subjective, I cannot imagine that such a large number of people would care about it. </p> <p>What am I missing? What is the problem with reduce()?</p>
[ { "answer_id": 181593, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 3, "selected": false, "text": "<p>People worry it encourages an obfuscated style of programming, doing something that can be achieved with clearer methods.</p>\n\n<p>I'm not against reduce myself, I also find it a useful tool sometimes.</p>\n" }, { "answer_id": 181646, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 5, "selected": false, "text": "<p><code>reduce()</code> is not being removed -- it's simply being moved into the <code>functools</code> module. Guido's reasoning is that except for trivial cases like summation, code written using <code>reduce()</code> is usually clearer when written as an accumulation loop.</p>\n" }, { "answer_id": 181706, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 7, "selected": true, "text": "<p>As Guido says in his <a href=\"http://www.artima.com/weblogs/viewpost.jsp?thread=98196\" rel=\"noreferrer\">The fate of reduce() in Python 3000</a> post:</p>\n\n<blockquote>\n <p>So now reduce(). This is actually the one I've always hated most, because, apart from a few examples involving + or *, almost every time I see a reduce() call with a non-trivial function argument, I need to grab pen and paper to diagram what's actually being fed into that function before I understand what the reduce() is supposed to do. So in my mind, the applicability of reduce() is pretty much limited to associative operators, and in all other cases it's better to write out the accumulation loop explicitly. </p>\n</blockquote>\n\n<p>There is an excellent example of a confusing <code>reduce</code> in the <a href=\"http://www.amk.ca/python/writing/functional\" rel=\"noreferrer\">Functional Programming HOWTO</a> article:</p>\n\n<blockquote>\n <p>Quick, what's the following code doing?</p>\n\n<pre><code>total = reduce(lambda a, b: (0, a[1] + b[1]), items)[1]\n</code></pre>\n \n <p>You can figure it out, but it takes time to disentangle the expression to figure out \n what's going on. Using a short nested def statements makes things a little bit better:</p>\n\n<pre><code>def combine (a, b):\n return 0, a[1] + b[1]\n\ntotal = reduce(combine, items)[1]\n</code></pre>\n \n <p>But it would be best of all if I had simply used a for loop:</p>\n\n<pre><code>total = 0\nfor a, b in items:\n total += b\n</code></pre>\n \n <p>Or the sum() built-in and a generator expression:</p>\n\n<pre><code>total = sum(b for a,b in items)\n</code></pre>\n \n <p>Many uses of reduce() are clearer when written as for loops.</p>\n</blockquote>\n" }, { "answer_id": 43993022, "author": "Terminus", "author_id": 1186443, "author_profile": "https://Stackoverflow.com/users/1186443", "pm_score": 2, "selected": false, "text": "<p>The primary reason of reduce's existence is to avoid writing explicit for loops with accumulators. Even though python has some facilities to support the functional style, it is not encouraged. If you like the 'real' and not 'pythonic' functional style - use a modern Lisp (Clojure?) or Haskell instead.</p>\n" }, { "answer_id": 65202390, "author": "user1153980", "author_id": 1153980, "author_profile": "https://Stackoverflow.com/users/1153980", "pm_score": -1, "selected": false, "text": "<p>Using reduce to compute the value of a polynomial with Horner's method is both compact and expressive.</p>\n<p>Compute polynomial value at x.\na is an array of coefficients for the polynomial</p>\n<pre><code>def poynomialValue(a,x):\n return reduce(lambda value, coef: value*x + coef, a)\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24530/" ]
There seems to be a lot of heated discussion on the net about the changes to the reduce() function in python 3.0 and how it should be removed. I am having a little difficulty understanding why this is the case; I find it quite reasonable to use it in a variety of cases. If the contempt was simply subjective, I cannot imagine that such a large number of people would care about it. What am I missing? What is the problem with reduce()?
As Guido says in his [The fate of reduce() in Python 3000](http://www.artima.com/weblogs/viewpost.jsp?thread=98196) post: > > So now reduce(). This is actually the one I've always hated most, because, apart from a few examples involving + or \*, almost every time I see a reduce() call with a non-trivial function argument, I need to grab pen and paper to diagram what's actually being fed into that function before I understand what the reduce() is supposed to do. So in my mind, the applicability of reduce() is pretty much limited to associative operators, and in all other cases it's better to write out the accumulation loop explicitly. > > > There is an excellent example of a confusing `reduce` in the [Functional Programming HOWTO](http://www.amk.ca/python/writing/functional) article: > > Quick, what's the following code doing? > > > > ``` > total = reduce(lambda a, b: (0, a[1] + b[1]), items)[1] > > ``` > > You can figure it out, but it takes time to disentangle the expression to figure out > what's going on. Using a short nested def statements makes things a little bit better: > > > > ``` > def combine (a, b): > return 0, a[1] + b[1] > > total = reduce(combine, items)[1] > > ``` > > But it would be best of all if I had simply used a for loop: > > > > ``` > total = 0 > for a, b in items: > total += b > > ``` > > Or the sum() built-in and a generator expression: > > > > ``` > total = sum(b for a,b in items) > > ``` > > Many uses of reduce() are clearer when written as for loops. > > >
181,573
<p>I would like to be able to display <code>Notebook</code> and a <code>TxtCtrl</code> wx widgets in a single frame. Below is an example adapted from the wxpython wiki; is it possible to change their layout (maybe with something like <code>wx.SplitterWindow</code>) to display the text box below the <code>Notebook</code> in the same frame?</p> <pre><code>import wx import wx.lib.sheet as sheet class MySheet(sheet.CSheet): def __init__(self, parent): sheet.CSheet.__init__(self, parent) self.SetLabelBackgroundColour('#CCFF66') self.SetNumberRows(50) self.SetNumberCols(50) class Notebook(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(600, 600)) menubar = wx.MenuBar() file = wx.Menu() file.Append(101, 'Quit', '' ) menubar.Append(file, "&amp;File") self.SetMenuBar(menubar) wx.EVT_MENU(self, 101, self.OnQuit) nb = wx.Notebook(self, -1, style=wx.NB_BOTTOM) self.sheet1 = MySheet(nb) self.sheet2 = MySheet(nb) self.sheet3 = MySheet(nb) nb.AddPage(self.sheet1, "Sheet1") nb.AddPage(self.sheet2, "Sheet2") nb.AddPage(self.sheet3, "Sheet3") self.sheet1.SetFocus() self.StatusBar() def StatusBar(self): self.statusbar = self.CreateStatusBar() def OnQuit(self, event): self.Close() class MyFrame(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(450, 400)) self.text = wx.TextCtrl(self, -1, style = wx.TE_MULTILINE) self.Center() class MyApp(wx.App): def OnInit(self): frame = Notebook(None, -1, 'notebook.py') frame.Show(True) frame.Center() frame2 = MyFrame(None, -1, '') frame2.Show(True) self.SetTopWindow(frame2) return True app = MyApp(0) app.MainLoop() </code></pre>
[ { "answer_id": 181591, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 1, "selected": false, "text": "<p>You can use a splitter, yes.</p>\n\n<p>Also, it makes sense to create a Panel, place your widgets in it (with sizers), and add this panel to the Frame.</p>\n" }, { "answer_id": 181626, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 4, "selected": true, "text": "<p>Making two widgets appear on the same frame is easy, actually. You should use sizers to accomplish this.</p>\n\n<p>In your example, you can change your <code>Notebook</code> class implementation to something like this:</p>\n\n<pre><code>class Notebook(wx.Frame):\n def __init__(self, parent, id, title):\n wx.Frame.__init__(self, parent, id, title, size=(600, 600))\n menubar = wx.MenuBar()\n file = wx.Menu()\n file.Append(101, 'Quit', '' )\n menubar.Append(file, \"&amp;File\")\n self.SetMenuBar(menubar)\n wx.EVT_MENU(self, 101, self.OnQuit)\n nb = wx.Notebook(self, -1, style=wx.NB_BOTTOM)\n self.sheet1 = MySheet(nb)\n self.sheet2 = MySheet(nb)\n self.sheet3 = MySheet(nb)\n nb.AddPage(self.sheet1, \"Sheet1\")\n nb.AddPage(self.sheet2, \"Sheet2\")\n nb.AddPage(self.sheet3, \"Sheet3\")\n self.sheet1.SetFocus()\n self.StatusBar()\n # new code begins here:\n # add your text ctrl:\n self.text = wx.TextCtrl(self, -1, style = wx.TE_MULTILINE)\n # create a new sizer for both controls:\n sizer = wx.BoxSizer(wx.VERTICAL)\n # add notebook first, with size factor 2:\n sizer.Add(nb, 2)\n # then text, size factor 1, maximized\n sizer.Add(self.text, 1, wx.EXPAND)\n # assign the sizer to Frame:\n self.SetSizerAndFit(sizer)\n</code></pre>\n\n<p>Only the <code>__init__</code> method is changed. Note that you can manipulate the proportions between the notebook and text control by changing the second argument of the <code>Add</code> method.</p>\n\n<p>You can learn more about sizers from the official <a href=\"https://docs.wxpython.org/sizers_overview.html\" rel=\"nofollow noreferrer\">Sizer overview</a> article.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11596/" ]
I would like to be able to display `Notebook` and a `TxtCtrl` wx widgets in a single frame. Below is an example adapted from the wxpython wiki; is it possible to change their layout (maybe with something like `wx.SplitterWindow`) to display the text box below the `Notebook` in the same frame? ``` import wx import wx.lib.sheet as sheet class MySheet(sheet.CSheet): def __init__(self, parent): sheet.CSheet.__init__(self, parent) self.SetLabelBackgroundColour('#CCFF66') self.SetNumberRows(50) self.SetNumberCols(50) class Notebook(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(600, 600)) menubar = wx.MenuBar() file = wx.Menu() file.Append(101, 'Quit', '' ) menubar.Append(file, "&File") self.SetMenuBar(menubar) wx.EVT_MENU(self, 101, self.OnQuit) nb = wx.Notebook(self, -1, style=wx.NB_BOTTOM) self.sheet1 = MySheet(nb) self.sheet2 = MySheet(nb) self.sheet3 = MySheet(nb) nb.AddPage(self.sheet1, "Sheet1") nb.AddPage(self.sheet2, "Sheet2") nb.AddPage(self.sheet3, "Sheet3") self.sheet1.SetFocus() self.StatusBar() def StatusBar(self): self.statusbar = self.CreateStatusBar() def OnQuit(self, event): self.Close() class MyFrame(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(450, 400)) self.text = wx.TextCtrl(self, -1, style = wx.TE_MULTILINE) self.Center() class MyApp(wx.App): def OnInit(self): frame = Notebook(None, -1, 'notebook.py') frame.Show(True) frame.Center() frame2 = MyFrame(None, -1, '') frame2.Show(True) self.SetTopWindow(frame2) return True app = MyApp(0) app.MainLoop() ```
Making two widgets appear on the same frame is easy, actually. You should use sizers to accomplish this. In your example, you can change your `Notebook` class implementation to something like this: ``` class Notebook(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(600, 600)) menubar = wx.MenuBar() file = wx.Menu() file.Append(101, 'Quit', '' ) menubar.Append(file, "&File") self.SetMenuBar(menubar) wx.EVT_MENU(self, 101, self.OnQuit) nb = wx.Notebook(self, -1, style=wx.NB_BOTTOM) self.sheet1 = MySheet(nb) self.sheet2 = MySheet(nb) self.sheet3 = MySheet(nb) nb.AddPage(self.sheet1, "Sheet1") nb.AddPage(self.sheet2, "Sheet2") nb.AddPage(self.sheet3, "Sheet3") self.sheet1.SetFocus() self.StatusBar() # new code begins here: # add your text ctrl: self.text = wx.TextCtrl(self, -1, style = wx.TE_MULTILINE) # create a new sizer for both controls: sizer = wx.BoxSizer(wx.VERTICAL) # add notebook first, with size factor 2: sizer.Add(nb, 2) # then text, size factor 1, maximized sizer.Add(self.text, 1, wx.EXPAND) # assign the sizer to Frame: self.SetSizerAndFit(sizer) ``` Only the `__init__` method is changed. Note that you can manipulate the proportions between the notebook and text control by changing the second argument of the `Add` method. You can learn more about sizers from the official [Sizer overview](https://docs.wxpython.org/sizers_overview.html) article.
181,579
<p>List Comprehension is a very useful code mechanism that is found in several languages, such as Haskell, Python, and Ruby (just to name a few off the top of my head). I'm familiar with the construct.</p> <p>I find myself working on an Open Office Spreadsheet and I need to do something fairly common: I want to count all of the values in a range of cells that fall between a high and low bounds. I instantly thought that list comprehension would do the trick, but I can't find anything analogous in Open Office. There is a function called "COUNTIF", and it something similar, but not quite what I need.</p> <p>Is there a construct in Open Office that could be used for list comprehension?</p>
[ { "answer_id": 187158, "author": "sdkpoly", "author_id": 15640, "author_profile": "https://Stackoverflow.com/users/15640", "pm_score": 2, "selected": true, "text": "<p>CountIf can count values equal to one chosen. Unfortunately it seems that there is no good candidate for such function. Alternatively you can use additional column with If to display 1 or 0 if the value fits in range or not accordingly:</p>\n\n<pre><code>=If(AND({list_cell}&gt;=MinVal; {list_cell}&lt;=MaxVal); 1; 0)\n</code></pre>\n\n<p>Then only thing left is to sum up this additional column.</p>\n" }, { "answer_id": 70291061, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 0, "selected": false, "text": "<p>Assuming:</p>\n<ul>\n<li>your range is A1:A10</li>\n<li>your lower bound is at B1</li>\n<li>your upper bound is at B2</li>\n</ul>\n<p>then what you want can be achieved by:</p>\n<pre><code>=COUNTIFS(A1:A10, &quot;&gt;&quot; &amp; B1, A1:A10, &quot;&lt;&quot; &amp; B2)\n</code></pre>\n<p>(you might need to change commas into semicolons, depending on your language preference for decimal point)</p>\n<p>Quoting from the installed OpenOffice documentation:</p>\n<blockquote>\n<p>The logical relation between criteria can be defined as logical AND (conjunction). In other words, if and only if all given criteria are met, a value from the corresponding cell of the given Func_Range is taken into calculation.</p>\n</blockquote>\n<blockquote>\n<p>This function is part of the Open Document Format for Office Applications (OpenDocument) standard Version 1.2. (ISO/IEC 26300:2-2015)</p>\n</blockquote>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19182/" ]
List Comprehension is a very useful code mechanism that is found in several languages, such as Haskell, Python, and Ruby (just to name a few off the top of my head). I'm familiar with the construct. I find myself working on an Open Office Spreadsheet and I need to do something fairly common: I want to count all of the values in a range of cells that fall between a high and low bounds. I instantly thought that list comprehension would do the trick, but I can't find anything analogous in Open Office. There is a function called "COUNTIF", and it something similar, but not quite what I need. Is there a construct in Open Office that could be used for list comprehension?
CountIf can count values equal to one chosen. Unfortunately it seems that there is no good candidate for such function. Alternatively you can use additional column with If to display 1 or 0 if the value fits in range or not accordingly: ``` =If(AND({list_cell}>=MinVal; {list_cell}<=MaxVal); 1; 0) ``` Then only thing left is to sum up this additional column.
181,581
<p>How do you generate a X.509 public and private key pair and a signing request (CSR file) to be sent to a CA for signing in C#?</p>
[ { "answer_id": 187158, "author": "sdkpoly", "author_id": 15640, "author_profile": "https://Stackoverflow.com/users/15640", "pm_score": 2, "selected": true, "text": "<p>CountIf can count values equal to one chosen. Unfortunately it seems that there is no good candidate for such function. Alternatively you can use additional column with If to display 1 or 0 if the value fits in range or not accordingly:</p>\n\n<pre><code>=If(AND({list_cell}&gt;=MinVal; {list_cell}&lt;=MaxVal); 1; 0)\n</code></pre>\n\n<p>Then only thing left is to sum up this additional column.</p>\n" }, { "answer_id": 70291061, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 0, "selected": false, "text": "<p>Assuming:</p>\n<ul>\n<li>your range is A1:A10</li>\n<li>your lower bound is at B1</li>\n<li>your upper bound is at B2</li>\n</ul>\n<p>then what you want can be achieved by:</p>\n<pre><code>=COUNTIFS(A1:A10, &quot;&gt;&quot; &amp; B1, A1:A10, &quot;&lt;&quot; &amp; B2)\n</code></pre>\n<p>(you might need to change commas into semicolons, depending on your language preference for decimal point)</p>\n<p>Quoting from the installed OpenOffice documentation:</p>\n<blockquote>\n<p>The logical relation between criteria can be defined as logical AND (conjunction). In other words, if and only if all given criteria are met, a value from the corresponding cell of the given Func_Range is taken into calculation.</p>\n</blockquote>\n<blockquote>\n<p>This function is part of the Open Document Format for Office Applications (OpenDocument) standard Version 1.2. (ISO/IEC 26300:2-2015)</p>\n</blockquote>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15158/" ]
How do you generate a X.509 public and private key pair and a signing request (CSR file) to be sent to a CA for signing in C#?
CountIf can count values equal to one chosen. Unfortunately it seems that there is no good candidate for such function. Alternatively you can use additional column with If to display 1 or 0 if the value fits in range or not accordingly: ``` =If(AND({list_cell}>=MinVal; {list_cell}<=MaxVal); 1; 0) ``` Then only thing left is to sum up this additional column.
181,585
<p>I'm using PowersHell to automate iTunes but find the error handling / waiting for com objects handling to be less than optimal.</p> <p>Example code</p> <pre><code>#Cause an RPC error $iTunes = New-Object -ComObject iTunes.Application $LibrarySource = $iTunes.LibrarySource # Get "playlist" objects for main sections foreach ($PList in $LibrarySource.Playlists) { if($Plist.name -eq "Library") { $Library = $Plist } } do { write-host -ForegroundColor Green "Running a loop" foreach ($Track in $Library.Tracks) { foreach ($FoundTrack in $Library.search("$Track.name", 5)) { # do nothing... we don't care... write-host "." -nonewline } } } while(1) #END </code></pre> <p>Go into itunes and do something that makes it pop up a message - in my case I go into the Party Shuffle and I get a banner "Party shuffle automatically blah blah...." with a "Do not display" message.</p> <p>At this point if running the script will do this repeatedly:</p> <pre><code>+ foreach ($FoundTrack in $Library.search( &lt;&lt;&lt;&lt; "$Track.name", 5)) { Exception calling "Search" with "2" argument(s): "The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVER CALL_RETRYLATER))" At C:\Documents and Settings\Me\My Documents\example.ps1:17 char:45 + foreach ($FoundTrack in $Library.search( &lt;&lt;&lt;&lt; "$Track.name", 5)) { Exception calling "Search" with "2" argument(s): "The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVER CALL_RETRYLATER))" At C:\Documents and Settings\Me\My Documents\example.ps1:17 char:45 </code></pre> <p>If you waited until you you had a dialog box before running the example then instead you'll get this repeatedly:</p> <pre><code>Running a loop You cannot call a method on a null-valued expression. At C:\Documents and Settings\Me\example.ps1:17 char:45 + foreach ($FoundTrack in $Library.search( &lt;&lt;&lt;&lt; "$Track.name", 5)) { </code></pre> <p>That'll be because the $Library handle is invalid.</p> <p>If my example was doing something important - like converting tracks and then deleting the old ones, not handling the error correctly could be fatal to tracks in itunes. I want to harden up the code so that it handles iTunes being busy and will silently retry until it has success. Any suggestions?</p>
[ { "answer_id": 182176, "author": "Jeffery Hicks", "author_id": 25508, "author_profile": "https://Stackoverflow.com/users/25508", "pm_score": 1, "selected": false, "text": "<p>COM support in PowerShell is not 100% reliable. But I think the real issue is iTunes itself. The application and COM model wasn't designed, IMO, for this type of management. That said, you could implement a Trap into your script. If an exception is raised, you could have the script sleep for a few seconds.</p>\n" }, { "answer_id": 188403, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 0, "selected": false, "text": "<p>Part of your problem might be in how $Track.name is being evaluated. You could try forcing it to fully evaluate the name by using $($Track.name).</p>\n\n<p>One other thing you might try is using the -strict parameter with your new-object command/</p>\n" }, { "answer_id": 217082, "author": "Emperor XLII", "author_id": 2495, "author_profile": "https://Stackoverflow.com/users/2495", "pm_score": 2, "selected": true, "text": "<p>Here's a function to retry operations, pausing in between failures:</p>\n\n<pre><code>function retry( [scriptblock]$action, [int]$wait=2, [int]$maxRetries=100 ) {\n $results = $null\n\n $currentRetry = 0\n $success = $false\n while( -not $success ) {\n trap {\n # Set status variables at function scope.\n Set-Variable -scope 1 success $false\n Set-Variable -scope 1 currentRetry ($currentRetry + 1)\n\n if( $currentRetry -gt $maxRetries ) { break }\n\n if( $wait ) { Start-Sleep $wait }\n continue\n }\n\n $success = $true\n $results = . $action\n }\n\n return $results\n}\n</code></pre>\n\n<p>For the first error in your example, you could change the inner <code>foreach</code> loop like this:</p>\n\n<pre><code>$FoundTracks = retry { $Library.search( \"$Track.name\", 5 ) }\nforeach ($FoundTrack in $FoundTracks) { ... }\n</code></pre>\n\n<p>This uses the default values for <code>$wait</code> and <code>$maxRetries</code>, so it will attempt to call <code>$Library.search</code> 100 times, waiting 2 seconds between each try. If all retries fail, the last error will propagate to the outer scope. You can set <code>$ErrorActionPreference</code> to <code>Stop</code> to prevent the script from executing any further statements.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5330/" ]
I'm using PowersHell to automate iTunes but find the error handling / waiting for com objects handling to be less than optimal. Example code ``` #Cause an RPC error $iTunes = New-Object -ComObject iTunes.Application $LibrarySource = $iTunes.LibrarySource # Get "playlist" objects for main sections foreach ($PList in $LibrarySource.Playlists) { if($Plist.name -eq "Library") { $Library = $Plist } } do { write-host -ForegroundColor Green "Running a loop" foreach ($Track in $Library.Tracks) { foreach ($FoundTrack in $Library.search("$Track.name", 5)) { # do nothing... we don't care... write-host "." -nonewline } } } while(1) #END ``` Go into itunes and do something that makes it pop up a message - in my case I go into the Party Shuffle and I get a banner "Party shuffle automatically blah blah...." with a "Do not display" message. At this point if running the script will do this repeatedly: ``` + foreach ($FoundTrack in $Library.search( <<<< "$Track.name", 5)) { Exception calling "Search" with "2" argument(s): "The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVER CALL_RETRYLATER))" At C:\Documents and Settings\Me\My Documents\example.ps1:17 char:45 + foreach ($FoundTrack in $Library.search( <<<< "$Track.name", 5)) { Exception calling "Search" with "2" argument(s): "The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVER CALL_RETRYLATER))" At C:\Documents and Settings\Me\My Documents\example.ps1:17 char:45 ``` If you waited until you you had a dialog box before running the example then instead you'll get this repeatedly: ``` Running a loop You cannot call a method on a null-valued expression. At C:\Documents and Settings\Me\example.ps1:17 char:45 + foreach ($FoundTrack in $Library.search( <<<< "$Track.name", 5)) { ``` That'll be because the $Library handle is invalid. If my example was doing something important - like converting tracks and then deleting the old ones, not handling the error correctly could be fatal to tracks in itunes. I want to harden up the code so that it handles iTunes being busy and will silently retry until it has success. Any suggestions?
Here's a function to retry operations, pausing in between failures: ``` function retry( [scriptblock]$action, [int]$wait=2, [int]$maxRetries=100 ) { $results = $null $currentRetry = 0 $success = $false while( -not $success ) { trap { # Set status variables at function scope. Set-Variable -scope 1 success $false Set-Variable -scope 1 currentRetry ($currentRetry + 1) if( $currentRetry -gt $maxRetries ) { break } if( $wait ) { Start-Sleep $wait } continue } $success = $true $results = . $action } return $results } ``` For the first error in your example, you could change the inner `foreach` loop like this: ``` $FoundTracks = retry { $Library.search( "$Track.name", 5 ) } foreach ($FoundTrack in $FoundTracks) { ... } ``` This uses the default values for `$wait` and `$maxRetries`, so it will attempt to call `$Library.search` 100 times, waiting 2 seconds between each try. If all retries fail, the last error will propagate to the outer scope. You can set `$ErrorActionPreference` to `Stop` to prevent the script from executing any further statements.
181,596
<p>How do you convert a numerical number to an Excel column name in C# without using automation getting the value directly from Excel.</p> <p>Excel 2007 has a possible range of 1 to 16384, which is the number of columns that it supports. The resulting values should be in the form of excel column names, e.g. A, AA, AAA etc.</p>
[ { "answer_id": 181610, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 3, "selected": false, "text": "<pre><code>int nCol = 127;\nstring sChars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nstring sCol = \"\";\nwhile (nCol &gt;= 26)\n{\n int nChar = nCol % 26;\n nCol = (nCol - nChar) / 26;\n // You could do some trick with using nChar as offset from 'A', but I am lazy to do it right now.\n sCol = sChars[nChar] + sCol;\n}\nsCol = sChars[nCol] + sCol;\n</code></pre>\n\n<p><strong>Update</strong>: <a href=\"https://stackoverflow.com/users/5189/peter\">Peter</a>'s comment is right. That's what I get for writing code in the browser. :-) My solution was not compiling, it was missing the left-most letter and it was building the string in reverse order - all now fixed.</p>\n\n<p>Bugs aside, the algorithm is basically converting a number from base 10 to base 26.</p>\n\n<p><strong>Update 2</strong>: <a href=\"https://stackoverflow.com/users/3043/joel-coehoorn\">Joel Coehoorn</a> is right - the code above will return AB for 27. If it was real base 26 number, AA would be equal to A and the next number after Z would be BA.</p>\n\n<pre><code>int nCol = 127;\nstring sChars = \"0ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nstring sCol = \"\";\nwhile (nCol &gt; 26)\n{\n int nChar = nCol % 26;\n if (nChar == 0)\n nChar = 26;\n nCol = (nCol - nChar) / 26;\n sCol = sChars[nChar] + sCol;\n}\nif (nCol != 0)\n sCol = sChars[nCol] + sCol;\n</code></pre>\n" }, { "answer_id": 181809, "author": "Peter", "author_id": 5189, "author_profile": "https://Stackoverflow.com/users/5189", "pm_score": 3, "selected": false, "text": "<p><strong>Easy with recursion.</strong></p>\n\n<pre><code>public static string GetStandardExcelColumnName(int columnNumberOneBased)\n{\n int baseValue = Convert.ToInt32('A');\n int columnNumberZeroBased = columnNumberOneBased - 1;\n\n string ret = \"\";\n\n if (columnNumberOneBased &gt; 26)\n {\n ret = GetStandardExcelColumnName(columnNumberZeroBased / 26) ;\n }\n\n return ret + Convert.ToChar(baseValue + (columnNumberZeroBased % 26) );\n}\n</code></pre>\n" }, { "answer_id": 182009, "author": "RoMa", "author_id": 7690, "author_profile": "https://Stackoverflow.com/users/7690", "pm_score": 5, "selected": false, "text": "<p>Sorry, this is Python instead of C#, but at least the results are correct:</p>\n\n<pre><code>def ColIdxToXlName(idx):\n if idx &lt; 1:\n raise ValueError(\"Index is too small\")\n result = \"\"\n while True:\n if idx &gt; 26:\n idx, r = divmod(idx - 1, 26)\n result = chr(r + ord('A')) + result\n else:\n return chr(idx + ord('A') - 1) + result\n\n\nfor i in xrange(1, 1024):\n print \"%4d : %s\" % (i, ColIdxToXlName(i))\n</code></pre>\n" }, { "answer_id": 182924, "author": "Graham", "author_id": 1826, "author_profile": "https://Stackoverflow.com/users/1826", "pm_score": 11, "selected": true, "text": "<p>Here's how I do it:</p>\n<pre><code>private string GetExcelColumnName(int columnNumber)\n{\n string columnName = &quot;&quot;;\n\n while (columnNumber &gt; 0)\n {\n int modulo = (columnNumber - 1) % 26;\n columnName = Convert.ToChar('A' + modulo) + columnName;\n columnNumber = (columnNumber - modulo) / 26;\n } \n\n return columnName;\n}\n</code></pre>\n" }, { "answer_id": 260269, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>private String getColumn(int c) {\n String s = \"\";\n do {\n s = (char)('A' + (c % 26)) + s;\n c /= 26;\n } while (c-- &gt; 0);\n return s;\n}\n</code></pre>\n\n<p>Its not exactly base 26, there is no 0 in the system. If there was, 'Z' would be followed by 'BA' not by 'AA'.</p>\n" }, { "answer_id": 262598, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I'm using this one in VB.NET 2003 and it works well...</p>\n\n<pre><code>Private Function GetExcelColumnName(ByVal aiColNumber As Integer) As String\n Dim BaseValue As Integer = Convert.ToInt32((\"A\").Chars(0)) - 1\n Dim lsReturn As String = String.Empty\n\n If (aiColNumber &gt; 26) Then\n lsReturn = GetExcelColumnName(Convert.ToInt32((Format(aiColNumber / 26, \"0.0\").Split(\".\"))(0)))\n End If\n\n GetExcelColumnName = lsReturn + Convert.ToChar(BaseValue + (aiColNumber Mod 26))\nEnd Function\n</code></pre>\n" }, { "answer_id": 310428, "author": "pipTheGeek", "author_id": 28552, "author_profile": "https://Stackoverflow.com/users/28552", "pm_score": 0, "selected": false, "text": "<p>If you are wanting to reference the cell progmatically then you will get much more readable code if you use the Cells method of a sheet. It takes a row and column index instead of a traditonal cell reference. It is very similar to the Offset method.</p>\n" }, { "answer_id": 495651, "author": "vzczc", "author_id": 224, "author_profile": "https://Stackoverflow.com/users/224", "pm_score": 6, "selected": false, "text": "<p>If anyone needs to do this in Excel without VBA, here is a way:</p>\n\n<pre><code>=SUBSTITUTE(ADDRESS(1;colNum;4);\"1\";\"\")\n</code></pre>\n\n<p>where colNum is the column number</p>\n\n<p>And in VBA:</p>\n\n<pre><code>Function GetColumnName(colNum As Integer) As String\n Dim d As Integer\n Dim m As Integer\n Dim name As String\n d = colNum\n name = \"\"\n Do While (d &gt; 0)\n m = (d - 1) Mod 26\n name = Chr(65 + m) + name\n d = Int((d - m) / 26)\n Loop\n GetColumnName = name\nEnd Function\n</code></pre>\n" }, { "answer_id": 981606, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Using this in VB.Net 2005 :</p>\n\n<pre><code>Private Function ColumnName(ByVal ColumnIndex As Integer) As String\n\n Dim Name As String = \"\"\n\n Name = (New Microsoft.Office.Interop.Owc11.Spreadsheet).Columns.Item(ColumnIndex).Address(False, False, Microsoft.Office.Interop.Owc11.XlReferenceStyle.xlA1)\n Name = Split(Name, \":\")(0)\n\n Return Name\n\nEnd Function\n</code></pre>\n" }, { "answer_id": 1188802, "author": "ShloEmi", "author_id": 2759057, "author_profile": "https://Stackoverflow.com/users/2759057", "pm_score": 2, "selected": false, "text": "<p>Refining the original solution (in C#):</p>\n\n<pre><code>public static class ExcelHelper\n{\n private static Dictionary&lt;UInt16, String&gt; l_DictionaryOfColumns;\n\n public static ExcelHelper() {\n l_DictionaryOfColumns = new Dictionary&lt;ushort, string&gt;(256);\n }\n\n public static String GetExcelColumnName(UInt16 l_Column)\n {\n UInt16 l_ColumnCopy = l_Column;\n String l_Chars = \"0ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n String l_rVal = \"\";\n UInt16 l_Char;\n\n\n if (l_DictionaryOfColumns.ContainsKey(l_Column) == true)\n {\n l_rVal = l_DictionaryOfColumns[l_Column];\n }\n else\n {\n while (l_ColumnCopy &gt; 26)\n {\n l_Char = l_ColumnCopy % 26;\n if (l_Char == 0)\n l_Char = 26;\n\n l_ColumnCopy = (l_ColumnCopy - l_Char) / 26;\n l_rVal = l_Chars[l_Char] + l_rVal;\n }\n if (l_ColumnCopy != 0)\n l_rVal = l_Chars[l_ColumnCopy] + l_rVal;\n\n l_DictionaryOfColumns.ContainsKey(l_Column) = l_rVal;\n }\n\n return l_rVal;\n }\n}\n</code></pre>\n" }, { "answer_id": 1188888, "author": "ShloEmi", "author_id": 2759057, "author_profile": "https://Stackoverflow.com/users/2759057", "pm_score": 0, "selected": false, "text": "<p>Another solution:</p>\n\n<pre><code>private void Foo()\n{\n l_ExcelApp = new Excel.ApplicationClass();\n l_ExcelApp.ReferenceStyle = Excel.XlReferenceStyle.xlR1C1;\n // ... now reference by R[row]C[column], Ex. A1 &lt;==&gt; R1C1, C6 &lt;==&gt; R3C6, ...\n}\n</code></pre>\n\n<p>see more here - <a href=\"http://www.expresscomputeronline.com/20021216/techspace1.shtml\" rel=\"nofollow noreferrer\">Cell referencing in Excel for everyone! by Dr Nitin Paranjape</a></p>\n" }, { "answer_id": 1924991, "author": "Stephen Fuhry", "author_id": 111033, "author_profile": "https://Stackoverflow.com/users/111033", "pm_score": 3, "selected": false, "text": "<p>..And converted to php:</p>\n\n<pre><code>function GetExcelColumnName($columnNumber) {\n $columnName = '';\n while ($columnNumber &gt; 0) {\n $modulo = ($columnNumber - 1) % 26;\n $columnName = chr(65 + $modulo) . $columnName;\n $columnNumber = (int)(($columnNumber - $modulo) / 26);\n }\n return $columnName;\n}\n</code></pre>\n" }, { "answer_id": 2472340, "author": "Daniel", "author_id": 296803, "author_profile": "https://Stackoverflow.com/users/296803", "pm_score": 0, "selected": false, "text": "<pre><code>public static string ConvertToAlphaColumnReferenceFromInteger(int columnReference)\n {\n int baseValue = ((int)('A')) - 1 ;\n string lsReturn = String.Empty; \n\n if (columnReference &gt; 26) \n {\n lsReturn = ConvertToAlphaColumnReferenceFromInteger(Convert.ToInt32(Convert.ToDouble(columnReference / 26).ToString().Split('.')[0]));\n } \n\n return lsReturn + Convert.ToChar(baseValue + (columnReference % 26)); \n }\n</code></pre>\n" }, { "answer_id": 2538716, "author": "Rob", "author_id": 277008, "author_profile": "https://Stackoverflow.com/users/277008", "pm_score": 2, "selected": false, "text": "<p>Here is an Actionscript version:</p>\n\n<pre><code>private var columnNumbers:Array = ['A', 'B', 'C', 'D', 'E', 'F' , 'G', 'H', 'I', 'J', 'K' ,'L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];\n\n private function getExcelColumnName(columnNumber:int) : String{\n var dividend:int = columnNumber;\n var columnName:String = \"\";\n var modulo:int;\n\n while (dividend &gt; 0)\n {\n modulo = (dividend - 1) % 26;\n columnName = columnNumbers[modulo] + columnName;\n dividend = int((dividend - modulo) / 26);\n } \n\n return columnName;\n }\n</code></pre>\n" }, { "answer_id": 2652855, "author": "Arent Arntzen", "author_id": 318470, "author_profile": "https://Stackoverflow.com/users/318470", "pm_score": 5, "selected": false, "text": "<p>You might need conversion both ways, e.g from Excel column adress like AAZ to integer and from any integer to Excel. The two methods below will do just that. Assumes 1 based indexing, first element in your \"arrays\" are element number 1.\nNo limits on size here, so you can use adresses like ERROR and that would be column number 2613824 ...</p>\n\n<pre><code>public static string ColumnAdress(int col)\n{\n if (col &lt;= 26) { \n return Convert.ToChar(col + 64).ToString();\n }\n int div = col / 26;\n int mod = col % 26;\n if (mod == 0) {mod = 26;div--;}\n return ColumnAdress(div) + ColumnAdress(mod);\n}\n\npublic static int ColumnNumber(string colAdress)\n{\n int[] digits = new int[colAdress.Length];\n for (int i = 0; i &lt; colAdress.Length; ++i)\n {\n digits[i] = Convert.ToInt32(colAdress[i]) - 64;\n }\n int mul=1;int res=0;\n for (int pos = digits.Length - 1; pos &gt;= 0; --pos)\n {\n res += digits[pos] * mul;\n mul *= 26;\n }\n return res;\n}\n</code></pre>\n" }, { "answer_id": 3444285, "author": "John", "author_id": 415561, "author_profile": "https://Stackoverflow.com/users/415561", "pm_score": 4, "selected": false, "text": "<p>I discovered an error in my first post, so I decided to sit down and do the the math. What I found is that the number system used to identify Excel columns is not a base 26 system, as another person posted. Consider the following in base 10. You can also do this with the letters of the alphabet.</p>\n\n<p>Space:.........................S1, S2, S3 : S1, S2, S3<br>\n....................................0, 00, 000 :.. A, AA, AAA<br>\n....................................1, 01, 001 :.. B, AB, AAB<br>\n.................................... …, …, … :.. …, …, …<br>\n....................................9, 99, 999 :.. Z, ZZ, ZZZ<br>\nTotal states in space: 10, 100, 1000 : 26, 676, 17576<br>\nTotal States:...............1110................18278</p>\n\n<p>Excel numbers columns in the individual alphabetical spaces using base 26. You can see that in general, the state space progression is a, a^2, a^3, … for some base a, and the total number of states is a + a^2 + a^3 + … . </p>\n\n<p>Suppose you want to find the total number of states A in the first N spaces. The formula for doing so is A = (a)(a^N - 1 )/(a-1). This is important because we need to find the space N that corresponds to our index K. If I want to find out where K lies in the number system I need to replace A with K and solve for N. The solution is N = log{base a} (A (a-1)/a +1). If I use the example of a = 10 and K = 192, I know that N = 2.23804… . This tells me that K lies at the beginning of the third space since it is a little greater than two.</p>\n\n<p>The next step is to find exactly how far in the current space we are. To find this, subtract from K the A generated using the floor of N. In this example, the floor of N is two. So, A = (10)(10^2 – 1)/(10-1) = 110, as is expected when you combine the states of the first two spaces. This needs to be subtracted from K because these first 110 states would have already been accounted for in the first two spaces. This leaves us with 82 states. So, in this number system, the representation of 192 in base 10 is 082. </p>\n\n<p>The C# code using a base index of zero is</p>\n\n<pre><code> private string ExcelColumnIndexToName(int Index)\n {\n string range = string.Empty;\n if (Index &lt; 0 ) return range;\n int a = 26;\n int x = (int)Math.Floor(Math.Log((Index) * (a - 1) / a + 1, a));\n Index -= (int)(Math.Pow(a, x) - 1) * a / (a - 1);\n for (int i = x+1; Index + i &gt; 0; i--)\n {\n range = ((char)(65 + Index % a)).ToString() + range;\n Index /= a;\n }\n return range;\n }\n</code></pre>\n\n<p>//Old Post</p>\n\n<p>A zero-based solution in C#.</p>\n\n<pre><code> private string ExcelColumnIndexToName(int Index)\n {\n string range = \"\";\n if (Index &lt; 0 ) return range;\n for(int i=1;Index + i &gt; 0;i=0)\n {\n range = ((char)(65 + Index % 26)).ToString() + range;\n Index /= 26;\n }\n if (range.Length &gt; 1) range = ((char)((int)range[0] - 1)).ToString() + range.Substring(1);\n return range;\n }\n</code></pre>\n" }, { "answer_id": 3550028, "author": "Matt Lewis", "author_id": 428667, "author_profile": "https://Stackoverflow.com/users/428667", "pm_score": 2, "selected": false, "text": "<p>if you just want it for a cell formula without code, here's a formula for it:</p>\n\n<pre><code>IF(COLUMN()&gt;=26,CHAR(ROUND(COLUMN()/26,1)+64)&amp;CHAR(MOD(COLUMN(),26)+64),CHAR(COLUMN()+64))\n</code></pre>\n" }, { "answer_id": 4161315, "author": "dirn", "author_id": 505319, "author_profile": "https://Stackoverflow.com/users/505319", "pm_score": -1, "selected": false, "text": "<pre><code> public string ToBase26(int number)\n {\n if (number &lt; 0) return String.Empty;\n\n int remainder = number % 26;\n int value = number / 26;\n\n return value == 0 ?\n String.Format(\"{0}\", Convert.ToChar(65 + remainder)) :\n String.Format(\"{0}{1}\", ToBase26(value - 1), Convert.ToChar(65 + remainder));\n }\n</code></pre>\n" }, { "answer_id": 4406060, "author": "Balaji.N.S", "author_id": 409596, "author_profile": "https://Stackoverflow.com/users/409596", "pm_score": 3, "selected": false, "text": "<p>Same implementation in Java</p>\n<pre><code>public String getExcelColumnName (int columnNumber) \n { \n int dividend = columnNumber; \n int i;\n String columnName = &quot;&quot;; \n int modulo; \n while (dividend &gt; 0) \n { \n modulo = (dividend - 1) % 26; \n i = 65 + modulo;\n columnName = new Character((char)i).toString() + columnName; \n dividend = (int)((dividend - modulo) / 26); \n } \n return columnName; \n } \n</code></pre>\n" }, { "answer_id": 7178621, "author": "JRL", "author_id": 859646, "author_profile": "https://Stackoverflow.com/users/859646", "pm_score": 2, "selected": false, "text": "<p>In Delphi (Pascal):</p>\n\n<pre><code>function GetExcelColumnName(columnNumber: integer): string;\nvar\n dividend, modulo: integer;\nbegin\n Result := '';\n dividend := columnNumber;\n while dividend &gt; 0 do begin\n modulo := (dividend - 1) mod 26;\n Result := Chr(65 + modulo) + Result;\n dividend := (dividend - modulo) div 26;\n end;\nend;\n</code></pre>\n" }, { "answer_id": 7728793, "author": "lambdapilgrim", "author_id": 329189, "author_profile": "https://Stackoverflow.com/users/329189", "pm_score": 0, "selected": false, "text": "<p>Here is how I would do it in Python. The algorithm is explained below:</p>\n\n<pre><code>alph = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z')\ndef labelrec(n, res):\n if n&lt;26:\n return alph[n]+res\n else:\n rem = n%26\n res = alph[rem]+res\n n = n/26-1\n return labelrec(n, res)\n</code></pre>\n\n<p>The function labelrec can be called with the number and an empty string like:</p>\n\n<pre><code>print labelrec(16383, '')\n</code></pre>\n\n<p>Here is why it works:\nIf decimal numbers were written the same way as Excel sheet columns, number 0-9 would be written normally, but 10 would become '00' and then 20 would become '10' and so on. Mapping few numbers:</p>\n\n<p>0 - 0</p>\n\n<p>9 - 9</p>\n\n<p>10 - 00</p>\n\n<p>20 - 10</p>\n\n<p>100 - 90</p>\n\n<p>110 - 000</p>\n\n<p>1110 - 0000</p>\n\n<p>So, the pattern is clear. Starting at the unit's place, if a number is less than 10, it's representation is same as the number itself, else you need to adjust the remaining number by subtracting it by 1 and recurse. You can stop when the number is less than 10.</p>\n\n<p>The same logic is applied for numbers of base 26 in above solution.</p>\n\n<p>P.S. If you want the numbers to begin from 1, call the same function on input number after decreasing it by 1.</p>\n" }, { "answer_id": 7751167, "author": "user932708", "author_id": 932708, "author_profile": "https://Stackoverflow.com/users/932708", "pm_score": 2, "selected": false, "text": "<p>After looking at all the supplied Versions here, I decided to do one myself, using recursion.</p>\n<p>Here is my vb.net Version:</p>\n<pre><code>Function CL(ByVal x As Integer) As String\n If x &gt;= 1 And x &lt;= 26 Then\n CL = Chr(x + 64)\n Else\n CL = CL((x - x Mod 26) / 26) &amp; Chr((x Mod 26) + 1 + 64)\n End If\nEnd Function\n</code></pre>\n" }, { "answer_id": 8739121, "author": "Kelly L", "author_id": 1131589, "author_profile": "https://Stackoverflow.com/users/1131589", "pm_score": 2, "selected": false, "text": "<p>A little late to the game, but here's the code I use (in C#):</p>\n\n<pre><code>private static readonly string _Alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\npublic static int ColumnNameParse(string value)\n{\n // assumes value.Length is [1,3]\n // assumes value is uppercase\n var digits = value.PadLeft(3).Select(x =&gt; _Alphabet.IndexOf(x));\n return digits.Aggregate(0, (current, index) =&gt; (current * 26) + (index + 1));\n}\n</code></pre>\n" }, { "answer_id": 9432623, "author": "Hasan", "author_id": 1060041, "author_profile": "https://Stackoverflow.com/users/1060041", "pm_score": 1, "selected": false, "text": "<p>I'm trying to do the same thing in Java...\nI've wrote following code:</p>\n\n<pre><code>private String getExcelColumnName(int columnNumber) {\n\n int dividend = columnNumber;\n String columnName = \"\";\n int modulo;\n\n while (dividend &gt; 0)\n {\n modulo = (dividend - 1) % 26;\n\n char val = Character.valueOf((char)(65 + modulo));\n\n columnName += val;\n\n dividend = (int)((dividend - modulo) / 26);\n } \n\n return columnName;\n}\n</code></pre>\n\n<p>Now once I ran it with columnNumber = 29, it gives me the result = \"CA\" (instead of \"AC\")\nany comments what I'm missing?\nI know I can reverse it by StringBuilder.... But looking at the Graham's answer, I'm little confused....</p>\n" }, { "answer_id": 10201665, "author": "Myforwik", "author_id": 70189, "author_profile": "https://Stackoverflow.com/users/70189", "pm_score": 2, "selected": false, "text": "<p>In perl, for an input of 1 (A), 27 (AA), etc.</p>\n\n<pre><code>sub excel_colname {\n my ($idx) = @_; # one-based column number\n --$idx; # zero-based column index\n my $name = \"\";\n while ($idx &gt;= 0) {\n $name .= chr(ord(\"A\") + ($idx % 26));\n $idx = int($idx / 26) - 1;\n }\n return scalar reverse $name;\n}\n</code></pre>\n" }, { "answer_id": 14780053, "author": "user2023861", "author_id": 2023861, "author_profile": "https://Stackoverflow.com/users/2023861", "pm_score": 3, "selected": false, "text": "<p>I'm surprised all of the solutions so far contain either iteration or recursion.</p>\n\n<p>Here's my solution that runs in constant time (no loops). This solution works for all possible Excel columns and checks that the input can be turned into an Excel column. Possible columns are in the range [A, XFD] or [1, 16384]. (This is dependent on your version of Excel)</p>\n\n<pre><code>private static string Turn(uint col)\n{\n if (col &lt; 1 || col &gt; 16384) //Excel columns are one-based (one = 'A')\n throw new ArgumentException(\"col must be &gt;= 1 and &lt;= 16384\");\n\n if (col &lt;= 26) //one character\n return ((char)(col + 'A' - 1)).ToString();\n\n else if (col &lt;= 702) //two characters\n {\n char firstChar = (char)((int)((col - 1) / 26) + 'A' - 1);\n char secondChar = (char)(col % 26 + 'A' - 1);\n\n if (secondChar == '@') //Excel is one-based, but modulo operations are zero-based\n secondChar = 'Z'; //convert one-based to zero-based\n\n return string.Format(\"{0}{1}\", firstChar, secondChar);\n }\n\n else //three characters\n {\n char firstChar = (char)((int)((col - 1) / 702) + 'A' - 1);\n char secondChar = (char)((col - 1) / 26 % 26 + 'A' - 1);\n char thirdChar = (char)(col % 26 + 'A' - 1);\n\n if (thirdChar == '@') //Excel is one-based, but modulo operations are zero-based\n thirdChar = 'Z'; //convert one-based to zero-based\n\n return string.Format(\"{0}{1}{2}\", firstChar, secondChar, thirdChar);\n }\n}\n</code></pre>\n" }, { "answer_id": 15678976, "author": "MaVRoSCy", "author_id": 1387157, "author_profile": "https://Stackoverflow.com/users/1387157", "pm_score": 4, "selected": false, "text": "<p>This answer is in javaScript:</p>\n\n<pre><code>function getCharFromNumber(columnNumber){\n var dividend = columnNumber;\n var columnName = \"\";\n var modulo;\n\n while (dividend &gt; 0)\n {\n modulo = (dividend - 1) % 26;\n columnName = String.fromCharCode(65 + modulo).toString() + columnName;\n dividend = parseInt((dividend - modulo) / 26);\n } \n return columnName;\n}\n</code></pre>\n" }, { "answer_id": 16327664, "author": "Ian Atkin", "author_id": 1315142, "author_profile": "https://Stackoverflow.com/users/1315142", "pm_score": 1, "selected": false, "text": "<p>Here's my super late implementation in PHP. This one's recursive. I wrote it just before I found this post. I wanted to see if others had solved this problem already...</p>\n\n<pre><code>public function GetColumn($intNumber, $strCol = null) {\n\n if ($intNumber &gt; 0) {\n $intRem = ($intNumber - 1) % 26;\n $strCol = $this-&gt;GetColumn(intval(($intNumber - $intRem) / 26), sprintf('%s%s', chr(65 + $intRem), $strCol));\n }\n\n return $strCol;\n}\n</code></pre>\n" }, { "answer_id": 19155871, "author": "Ally", "author_id": 837649, "author_profile": "https://Stackoverflow.com/users/837649", "pm_score": 2, "selected": false, "text": "<p><strong>JavaScript Solution</strong></p>\n\n<pre><code>/**\n * Calculate the column letter abbreviation from a 1 based index\n * @param {Number} value\n * @returns {string}\n */\ngetColumnFromIndex = function (value) {\n var base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');\n var remainder, result = \"\";\n do {\n remainder = value % 26;\n result = base[(remainder || 26) - 1] + result;\n value = Math.floor(value / 26);\n } while (value &gt; 0);\n return result;\n};\n</code></pre>\n" }, { "answer_id": 21330107, "author": "Ian", "author_id": 578821, "author_profile": "https://Stackoverflow.com/users/578821", "pm_score": 0, "selected": false, "text": "<p>(I realise the question relates to C# however, if anyone reading needs to do the same thing with <strong>Java</strong> then the following may be useful)</p>\n\n<p>It turns out that this can easily be done using the the \"CellReference\" class in <a href=\"http://poi.apache.org/\" rel=\"nofollow\">Jakarta POI</a>. Also, the conversion can be done both ways.</p>\n\n<pre><code>// Convert row and column numbers (0-based) to an Excel cell reference\nCellReference numbers = new CellReference(3, 28);\nSystem.out.println(numbers.formatAsString());\n\n// Convert an Excel cell reference back into digits\nCellReference reference = new CellReference(\"AC4\");\nSystem.out.println(reference.getRow() + \", \" + reference.getCol());\n</code></pre>\n" }, { "answer_id": 21924093, "author": "Paul Ma", "author_id": 1497459, "author_profile": "https://Stackoverflow.com/users/1497459", "pm_score": 2, "selected": false, "text": "<p>Another VBA way</p>\n\n<pre><code>Public Function GetColumnName(TargetCell As Range) As String\n GetColumnName = Split(CStr(TargetCell.Cells(1, 1).Address), \"$\")(1)\nEnd Function\n</code></pre>\n" }, { "answer_id": 26063181, "author": "t3dodson", "author_id": 2175572, "author_profile": "https://Stackoverflow.com/users/2175572", "pm_score": 3, "selected": false, "text": "<p>I wanted to throw in my static class I use, for interoping between col index and col Label. I use a modified accepted answer for my ColumnLabel Method</p>\n\n<pre><code>public static class Extensions\n{\n public static string ColumnLabel(this int col)\n {\n var dividend = col;\n var columnLabel = string.Empty;\n int modulo;\n\n while (dividend &gt; 0)\n {\n modulo = (dividend - 1) % 26;\n columnLabel = Convert.ToChar(65 + modulo).ToString() + columnLabel;\n dividend = (int)((dividend - modulo) / 26);\n } \n\n return columnLabel;\n }\n public static int ColumnIndex(this string colLabel)\n {\n // \"AD\" (1 * 26^1) + (4 * 26^0) ...\n var colIndex = 0;\n for(int ind = 0, pow = colLabel.Count()-1; ind &lt; colLabel.Count(); ++ind, --pow)\n {\n var cVal = Convert.ToInt32(colLabel[ind]) - 64; //col A is index 1\n colIndex += cVal * ((int)Math.Pow(26, pow));\n }\n return colIndex;\n }\n}\n</code></pre>\n\n<p>Use this like...</p>\n\n<pre><code>30.ColumnLabel(); // \"AD\"\n\"AD\".ColumnIndex(); // 30\n</code></pre>\n" }, { "answer_id": 29550239, "author": "S_R", "author_id": 4004421, "author_profile": "https://Stackoverflow.com/users/4004421", "pm_score": 2, "selected": false, "text": "<p>These my codes to convert specific number (index start from 1) to Excel Column.</p>\n\n<pre><code> public static string NumberToExcelColumn(uint number)\n {\n uint originalNumber = number;\n\n uint numChars = 1;\n while (Math.Pow(26, numChars) &lt; number)\n {\n numChars++;\n\n if (Math.Pow(26, numChars) + 26 &gt;= number)\n {\n break;\n } \n }\n\n string toRet = \"\";\n uint lastValue = 0;\n\n do\n {\n number -= lastValue;\n\n double powerVal = Math.Pow(26, numChars - 1);\n byte thisCharIdx = (byte)Math.Truncate((columnNumber - 1) / powerVal);\n lastValue = (int)powerVal * thisCharIdx;\n\n if (numChars - 2 &gt;= 0)\n {\n double powerVal_next = Math.Pow(26, numChars - 2);\n byte thisCharIdx_next = (byte)Math.Truncate((columnNumber - lastValue - 1) / powerVal_next);\n int lastValue_next = (int)Math.Pow(26, numChars - 2) * thisCharIdx_next;\n\n if (thisCharIdx_next == 0 &amp;&amp; lastValue_next == 0 &amp;&amp; powerVal_next == 26)\n {\n thisCharIdx--;\n lastValue = (int)powerVal * thisCharIdx;\n }\n }\n\n toRet += (char)((byte)'A' + thisCharIdx + ((numChars &gt; 1) ? -1 : 0));\n\n numChars--;\n } while (numChars &gt; 0);\n\n return toRet;\n }\n</code></pre>\n\n<p>My Unit Test:</p>\n\n<pre><code> [TestMethod]\n public void Test()\n {\n Assert.AreEqual(\"A\", NumberToExcelColumn(1));\n Assert.AreEqual(\"Z\", NumberToExcelColumn(26));\n Assert.AreEqual(\"AA\", NumberToExcelColumn(27));\n Assert.AreEqual(\"AO\", NumberToExcelColumn(41));\n Assert.AreEqual(\"AZ\", NumberToExcelColumn(52));\n Assert.AreEqual(\"BA\", NumberToExcelColumn(53));\n Assert.AreEqual(\"ZZ\", NumberToExcelColumn(702));\n Assert.AreEqual(\"AAA\", NumberToExcelColumn(703));\n Assert.AreEqual(\"ABC\", NumberToExcelColumn(731));\n Assert.AreEqual(\"ACQ\", NumberToExcelColumn(771));\n Assert.AreEqual(\"AYZ\", NumberToExcelColumn(1352));\n Assert.AreEqual(\"AZA\", NumberToExcelColumn(1353));\n Assert.AreEqual(\"AZB\", NumberToExcelColumn(1354));\n Assert.AreEqual(\"BAA\", NumberToExcelColumn(1379));\n Assert.AreEqual(\"CNU\", NumberToExcelColumn(2413));\n Assert.AreEqual(\"GCM\", NumberToExcelColumn(4823));\n Assert.AreEqual(\"MSR\", NumberToExcelColumn(9300));\n Assert.AreEqual(\"OMB\", NumberToExcelColumn(10480));\n Assert.AreEqual(\"ULV\", NumberToExcelColumn(14530));\n Assert.AreEqual(\"XFD\", NumberToExcelColumn(16384));\n }\n</code></pre>\n" }, { "answer_id": 29846532, "author": "Iwan B.", "author_id": 731228, "author_profile": "https://Stackoverflow.com/users/731228", "pm_score": 1, "selected": false, "text": "<p>Coincise and elegant <strong>Ruby</strong> version:</p>\n\n<pre><code>def col_name(col_idx)\n name = \"\"\n while col_idx&gt;0\n mod = (col_idx-1)%26\n name = (65+mod).chr + name\n col_idx = ((col_idx-mod)/26).to_i\n end\n name\nend\n</code></pre>\n" }, { "answer_id": 30913322, "author": "Hangarter", "author_id": 3938098, "author_profile": "https://Stackoverflow.com/users/3938098", "pm_score": 0, "selected": false, "text": "<p>I just had to do this work today, my implementation uses recursion:</p>\n\n<pre><code>private static string GetColumnLetter(string colNumber)\n{\n if (string.IsNullOrEmpty(colNumber))\n {\n throw new ArgumentNullException(colNumber);\n }\n\n string colName = String.Empty;\n\n try\n {\n var colNum = Convert.ToInt32(colNumber);\n var mod = colNum % 26;\n var div = Math.Floor((double)(colNum)/26);\n colName = ((div &gt; 0) ? GetColumnLetter((div - 1).ToString()) : String.Empty) + Convert.ToChar(mod + 65);\n }\n finally\n {\n colName = colName == String.Empty ? \"A\" : colName;\n }\n\n return colName;\n}\n</code></pre>\n\n<p>This considers the number coming as string the the method and the numbers starting in \"0\" (A = 0)</p>\n" }, { "answer_id": 31757052, "author": "bpolat", "author_id": 2231118, "author_profile": "https://Stackoverflow.com/users/2231118", "pm_score": 0, "selected": false, "text": "<p>Objective-C Implementation :</p>\n\n<pre><code>-(NSString*)getColumnName:(int)n {\n NSString *name = @\"\";\n while (n&gt;0) {\n n--;\n char c = (char)('A' + n%26);\n name = [NSString stringWithFormat:@\"%c%@\",c,name];\n n = n/26;\n } \n return name;\n</code></pre>\n\n<p>}</p>\n\n<p>SWIFT Implementation:</p>\n\n<pre><code>func getColumnName(n:Int)-&gt;String{\n var columnName = \"\"\n var index = n\n while index&gt;0 {\n index--\n let char = Character(UnicodeScalar(65 + index%26))\n columnName = \"\\(char)\\(columnName)\"\n index = index / 26\n }\n return columnName\n</code></pre>\n\n<p>}</p>\n\n<p>The answer is based on :<a href=\"https://stackoverflow.com/a/4532562/2231118\">https://stackoverflow.com/a/4532562/2231118</a></p>\n" }, { "answer_id": 31900180, "author": "Rob Sawyer", "author_id": 67524, "author_profile": "https://Stackoverflow.com/users/67524", "pm_score": 1, "selected": false, "text": "<p>NodeJS implementation:</p>\n\n<pre><code>/**\n* getColumnFromIndex\n* Helper that returns a column value (A-XFD) for an index value (integer).\n* The column follows the Common Spreadsheet Format e.g., A, AA, AAA.\n* See https://stackoverflow.com/questions/181596/how-to-convert-a-column-number-eg-127-into-an-excel-column-eg-aa/3444285#3444285\n* @param numVal: Integer\n* @return String\n*/\ngetColumnFromIndex: function(numVal){\n var dividend = parseInt(numVal);\n var columnName = '';\n var modulo;\n while (dividend &gt; 0) {\n modulo = (dividend - 1) % 26;\n columnName = String.fromCharCode(65 + modulo) + columnName;\n dividend = parseInt((dividend - modulo) / 26);\n }\n return columnName;\n},\n</code></pre>\n\n<p>Thanks to <a href=\"https://stackoverflow.com/questions/9905533/convert-excel-column-alphabet-e-g-aa-to-number-e-g-25\">Convert excel column alphabet (e.g. AA) to number (e.g., 25)</a>. And in reverse:</p>\n\n<pre><code>/**\n* getIndexFromColumn\n* Helper that returns an index value (integer) for a column value (A-XFD).\n* The column follows the Common Spreadsheet Format e.g., A, AA, AAA.\n* See https://stackoverflow.com/questions/9905533/convert-excel-column-alphabet-e-g-aa-to-number-e-g-25\n* @param strVal: String\n* @return Integer\n*/\ngetIndexFromColumn: function(val){\n var base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', i, j, result = 0;\n for (i = 0, j = val.length - 1; i &lt; val.length; i += 1, j -= 1) {\n result += Math.pow(base.length, j) * (base.indexOf(val[i]) + 1);\n }\n return result;\n}\n</code></pre>\n" }, { "answer_id": 33702966, "author": "SierraOscar", "author_id": 4240221, "author_profile": "https://Stackoverflow.com/users/4240221", "pm_score": 0, "selected": false, "text": "<p>Saw one other VBA answer - this can be done in <a href=\"/questions/tagged/excel-vba\" class=\"post-tag\" title=\"show questions tagged &#39;excel-vba&#39;\" rel=\"tag\">excel-vba</a> with a 1 line UDF:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Function GetColLetter(ByVal colID As Integer) As String\n If colID &gt; Columns.Count Then\n Err.Raise 9, , &quot;Column index out of bounds&quot;\n Else\n GetColLetter = Split(Cells(1, colID).Address, &quot;$&quot;)(1)\n End If\nEnd Function\n</code></pre>\n" }, { "answer_id": 39018386, "author": "Herman Kan", "author_id": 1997693, "author_profile": "https://Stackoverflow.com/users/1997693", "pm_score": 2, "selected": false, "text": "<p>Though I am late to the game, <a href=\"https://stackoverflow.com/a/182924/1997693\">Graham's answer</a> is far from being optimal. Particularly, you don't have to use the <code>modulo</code>, call <code>ToString()</code> and apply <code>(int)</code> cast. Considering that in most cases in C# world you would start numbering from 0, here is my revision:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static string GetColumnName(int index) // zero-based\n{\n const byte BASE = 'Z' - 'A' + 1;\n string name = String.Empty;\n\n do\n {\n name = Convert.ToChar('A' + index % BASE) + name;\n index = index / BASE - 1;\n }\n while (index &gt;= 0);\n\n return name;\n}\n</code></pre>\n" }, { "answer_id": 39170240, "author": "user2792497", "author_id": 2792497, "author_profile": "https://Stackoverflow.com/users/2792497", "pm_score": -1, "selected": false, "text": "<p>Microsoft Excel Miniature, Quick-and-Dirty formula.</p>\n\n<p>Hi,</p>\n\n<p>Here's one way to get the Excel character-column-header from a number....</p>\n\n<p>I created a formula for an Excel cell. </p>\n\n<p>(i.e. I took the approach of not using VBA programming.)</p>\n\n<p>The formula looks at a cell that has a number in it and tells you what the column is -- in letters.</p>\n\n<p>In the attached image:</p>\n\n<ul>\n<li>I put 1,2,3 etc in the top row all the way out to column ABS.</li>\n<li>I pasted my formula in the second row all the way out to ABS.</li>\n<li>My formula looks at row 1 and converts the number to Excel's column header id. </li>\n<li>My formula works for all numbers out to 702 (zz).</li>\n<li><p>I did it in this manner to prove that the formula works so you can look at the output from the formula and look at the column header above and easily visually verify that the formula works. :-)</p>\n\n<p>=CONCATENATE(MID(\"_abcdefghijklmnopqrstuvwxyz\",(IF(MOD(K1,26)>0,INT(K1/26)+1,(INT(K1/26)))),1),MID(\"abcdefghijklmnopqrstuvwxyz\",IF(MOD(K1,26)=0,26,MOD(K1,26)),1))</p></li>\n</ul>\n\n<p>The underscore was there for debugging purposes - to let you know there was an actual space and that it was working correctly.</p>\n\n<p>With this formula above -- whatever you put in K1 - the formula will tell you what the column header will be.</p>\n\n<p>The formula, in its current form, only goes out to 2 digits (ZZ) but could be modified to add the 3rd letter (ZZZ).</p>\n\n<p><a href=\"https://i.stack.imgur.com/Aqzn4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Aqzn4.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 41148862, "author": "Maslow", "author_id": 57883, "author_profile": "https://Stackoverflow.com/users/57883", "pm_score": 1, "selected": false, "text": "<p>F# version of each way</p>\n\n<pre><code>let rec getExcelColumnName x = if x&lt;26 then int 'A'+x|&gt;char|&gt;string else (x/26-1|&gt;c)+ c(x%26)\n</code></pre>\n\n<p>pardon the minimizing, was working on a better version of <a href=\"https://stackoverflow.com/a/4500043/57883\">https://stackoverflow.com/a/4500043/57883</a></p>\n\n<p><hr />\nand the opposite direction:</p>\n\n<pre><code>// return values start at 0\nlet getIndexFromExcelColumnName (x:string) =\n let a = int 'A'\n let fPow len i =\n Math.Pow(26., len - 1 - i |&gt; float)\n |&gt; int\n\n let getValue len i c = \n int c - a + 1 * fPow len i\n let f i = getValue x.Length i x.[i]\n [0 .. x.Length - 1]\n |&gt; Seq.map f\n |&gt; Seq.sum\n |&gt; fun x -&gt; x - 1\n</code></pre>\n" }, { "answer_id": 41817847, "author": "Extragorey", "author_id": 6680521, "author_profile": "https://Stackoverflow.com/users/6680521", "pm_score": 3, "selected": false, "text": "<p>Just throwing in a simple two-line C# implementation using recursion, because all the answers here seem far more complicated than necessary.</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Gets the column letter(s) corresponding to the given column number.\n/// &lt;/summary&gt;\n/// &lt;param name=\"column\"&gt;The one-based column index. Must be greater than zero.&lt;/param&gt;\n/// &lt;returns&gt;The desired column letter, or an empty string if the column number was invalid.&lt;/returns&gt;\npublic static string GetColumnLetter(int column) {\n if (column &lt; 1) return String.Empty;\n return GetColumnLetter((column - 1) / 26) + (char)('A' + (column - 1) % 26);\n}\n</code></pre>\n" }, { "answer_id": 42949724, "author": "Vlad Schnakovszki", "author_id": 1195527, "author_profile": "https://Stackoverflow.com/users/1195527", "pm_score": 1, "selected": false, "text": "<p>This is the question all others as well as Google redirect to so I'm posting this here.</p>\n\n<p>Many of these answers are correct but too cumbersome for simple situations such as when you don't have over 26 columns. If you have any doubt whether you might go into double character columns then ignore this answer, but if you're sure you won't, then you could do it as simple as this in C#:</p>\n\n<pre><code>public static char ColIndexToLetter(short index)\n{\n if (index &lt; 0 || index &gt; 25) throw new ArgumentException(\"Index must be between 0 and 25.\");\n return (char)('A' + index);\n}\n</code></pre>\n\n<p>Heck, if you're confident about what you're passing in you could even remove the validation and use this inline:</p>\n\n<pre><code>(char)('A' + index)\n</code></pre>\n\n<p>This will be very similar in many languages so you can adapt it as needed.</p>\n\n<p>Again, <strong>only use this if you're 100% sure you won't have more than 26 columns</strong>.</p>\n" }, { "answer_id": 46165397, "author": "phlare", "author_id": 6845867, "author_profile": "https://Stackoverflow.com/users/6845867", "pm_score": 1, "selected": false, "text": "<p>Thanks for the answers here!! helped me come up with these helper functions for some interaction with the Google Sheets API that i'm working on in Elixir/Phoenix</p>\n\n<p>here's what i came up with (could probably use some extra validation and error handling)</p>\n\n<p>In Elixir:</p>\n\n<pre><code>def number_to_column(number) do\n cond do\n (number &gt; 0 &amp;&amp; number &lt;= 26) -&gt;\n to_string([(number + 64)])\n (number &gt; 26) -&gt;\n div_col = number_to_column(div(number - 1, 26))\n remainder = rem(number, 26)\n rem_col = cond do\n (remainder == 0) -&gt;\n number_to_column(26)\n true -&gt;\n number_to_column(remainder)\n end\n div_col &lt;&gt; rem_col\n true -&gt;\n \"\"\n end\nend\n</code></pre>\n\n<p>And the inverse function: </p>\n\n<pre><code>def column_to_number(column) do\n column\n |&gt; to_charlist\n |&gt; Enum.reverse\n |&gt; Enum.with_index\n |&gt; Enum.reduce(0, fn({char, idx}, acc) -&gt;\n ((char - 64) * :math.pow(26,idx)) + acc\n end)\n |&gt; round\nend\n</code></pre>\n\n<p>And some tests:</p>\n\n<pre><code>describe \"test excel functions\" do\n @excelTestData [{\"A\", 1}, {\"Z\",26}, {\"AA\", 27}, {\"AB\", 28}, {\"AZ\", 52},{\"BA\", 53}, {\"AAA\", 703}]\n\n test \"column to number\" do\n Enum.each(@excelTestData, fn({input, expected_result}) -&gt;\n actual_result = BulkOnboardingController.column_to_number(input)\n assert actual_result == expected_result\n end)\n end\n\n test \"number to column\" do\n Enum.each(@excelTestData, fn({expected_result, input}) -&gt;\n actual_result = BulkOnboardingController.number_to_column(input)\n assert actual_result == expected_result\n end)\n end\nend\n</code></pre>\n" }, { "answer_id": 47124842, "author": "DataEngineer", "author_id": 7271239, "author_profile": "https://Stackoverflow.com/users/7271239", "pm_score": 2, "selected": false, "text": "<p>Sorry, this is Python instead of C#, but at least the results are correct:</p>\n\n<pre><code>def excel_column_number_to_name(column_number):\n output = \"\"\n index = column_number-1\n while index &gt;= 0:\n character = chr((index%26)+ord('A'))\n output = output + character\n index = index/26 - 1\n\n return output[::-1]\n\n\nfor i in xrange(1, 1024):\n print \"%4d : %s\" % (i, excel_column_number_to_name(i))\n</code></pre>\n\n<p>Passed these test cases:</p>\n\n<ul>\n<li>Column Number: 494286 => ABCDZ </li>\n<li>Column Number: 27 => AA</li>\n<li>Column Number: 52 => AZ</li>\n</ul>\n" }, { "answer_id": 51805461, "author": "Phoeson", "author_id": 1799100, "author_profile": "https://Stackoverflow.com/users/1799100", "pm_score": 1, "selected": false, "text": "<p>This is a javascript version according to Graham's code</p>\n\n<pre><code>function (columnNumber) {\n var dividend = columnNumber;\n var columnName = \"\";\n var modulo;\n\n while (dividend &gt; 0) {\n modulo = (dividend - 1) % 26;\n columnName = String.fromCharCode(65 + modulo) + columnName;\n dividend = parseInt((dividend - modulo) / 26);\n }\n\n return columnName;\n};\n</code></pre>\n" }, { "answer_id": 52790077, "author": "user1098928", "author_id": 1098928, "author_profile": "https://Stackoverflow.com/users/1098928", "pm_score": 2, "selected": false, "text": "<p>For what it is worth, here is Graham's code in Powershell:</p>\n\n<pre><code>function ConvertTo-ExcelColumnID {\nparam (\n [parameter(Position = 0,\n HelpMessage = \"A 1-based index to convert to an excel column ID. e.g. 2 =&gt; 'B', 29 =&gt; 'AC'\",\n Mandatory = $true)]\n [int]$index\n);\n\n[string]$result = '';\nif ($index -le 0 ) {\n return $result;\n}\n\nwhile ($index -gt 0) {\n [int]$modulo = ($index - 1) % 26;\n $character = [char]($modulo + [int][char]'A');\n $result = $character + $result;\n [int]$index = ($index - $modulo) / 26;\n}\n\nreturn $result;\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 53039230, "author": "grepit", "author_id": 717630, "author_profile": "https://Stackoverflow.com/users/717630", "pm_score": 1, "selected": false, "text": "<p>Most of previous answers are correct. Here is one more way of converting column number to excel columns.\nsolution is rather simple if we think about this as a base conversion. Simply, convert the column number to base 26 since there is 26 letters only.\nHere is how you can do this: </p>\n\n<p><strong>steps:</strong></p>\n\n<ul>\n<li><p>set the column as a quotient</p></li>\n<li><p>subtract one from quotient variable (from previous step) because we need to end up on <a href=\"http://www.asciitable.com/\" rel=\"nofollow noreferrer\">ascii table</a> with 97 being a.</p></li>\n<li><p>divide by 26 and get the remainder.</p></li>\n<li>add +97 to remainder and convert to char (since 97 is \"a\" in ASCII table)</li>\n<li>quotient becomes the new quotient/ 26 (since we might go over 26 column)</li>\n<li>continue to do this until quotient is greater than 0 and then return the result</li>\n</ul>\n\n<p>here is the code that does this :)</p>\n\n<pre><code>def convert_num_to_column(column_num):\n result = \"\"\n quotient = column_num\n remainder = 0\n while (quotient &gt;0):\n quotient = quotient -1\n remainder = quotient%26\n result = chr(int(remainder)+97)+result\n quotient = int(quotient/26)\n return result\n\nprint(\"--\",convert_num_to_column(1).upper())\n</code></pre>\n" }, { "answer_id": 56959174, "author": "AlishahNovin", "author_id": 212434, "author_profile": "https://Stackoverflow.com/users/212434", "pm_score": 2, "selected": false, "text": "<p>More than 30 solutions already, but here's my one-line C# solution... </p>\n\n<pre><code>public string IntToExcelColumn(int i)\n{\n return ((i&lt;16926? \"\" : ((char)((((i/26)-1)%26)+65)).ToString()) + (i&lt;2730? \"\" : ((char)((((i/26)-1)%26)+65)).ToString()) + (i&lt;26? \"\" : ((char)((((i/26)-1)%26)+65)).ToString()) + ((char)((i%26)+65)));\n}\n</code></pre>\n" }, { "answer_id": 58386648, "author": "Ricky", "author_id": 11003725, "author_profile": "https://Stackoverflow.com/users/11003725", "pm_score": -1, "selected": false, "text": "<p>Here is my solution in python </p>\n\n<pre><code>import math\n\nnum = 3500\nrow_number = str(math.ceil(num / 702))\nletters = ''\nnum = num - 702 * math.floor(num / 702)\nwhile num:\n mod = (num - 1) % 26\n letters += chr(mod + 65)\n num = (num - 1) // 26\nresult = row_number + (\"\".join(reversed(letters)))\nprint(result)\n\n</code></pre>\n" }, { "answer_id": 59755393, "author": "Tyler", "author_id": 3640355, "author_profile": "https://Stackoverflow.com/users/3640355", "pm_score": 0, "selected": false, "text": "<p><strong>Typescript</strong> </p>\n\n<pre><code>function lengthToExcelColumn(len: number): string {\n\n let dividend: number = len;\n let columnName: string = '';\n let modulo: number = 0;\n\n while (dividend &gt; 0) {\n modulo = (dividend - 1) % 26;\n columnName = String.fromCharCode(65 + modulo).toString() + columnName;\n dividend = Math.floor((dividend - modulo) / 26);\n }\n return columnName;\n}\n</code></pre>\n" }, { "answer_id": 60234558, "author": "Konstantin Gredeskoul", "author_id": 542553, "author_profile": "https://Stackoverflow.com/users/542553", "pm_score": 0, "selected": false, "text": "<p>Seems like so many answers are much more complex than necessary. Here is a generic Ruby answer based on the recursion described above:</p>\n\n<p>One nice thing about this answer is that it's not limited to the 26 characters of English Alphabet. You can define any range you like in <code>COLUMNS</code> constant and it will do the right thing.</p>\n\n<pre><code> # vim: ft=ruby\n class Numeric\n COLUMNS = ('A'..'Z').to_a\n\n def to_excel_column(n = self)\n n &lt; 1 ? '' : begin\n base = COLUMNS.size\n to_excel_column((n - 1) / base) + COLUMNS[(n - 1) % base]\n end\n end\n end\n\n # verify:\n (1..52).each { |i| printf \"%4d =&gt; %4s\\n\", i, i.to_excel_column }\n</code></pre>\n\n<p>This prints the following, eg:</p>\n\n<pre><code> 1 =&gt; A\n 2 =&gt; B\n 3 =&gt; C\n ....\n 33 =&gt; AG\n 34 =&gt; AH\n 35 =&gt; AI\n 36 =&gt; AJ\n 37 =&gt; AK\n 38 =&gt; AL\n 39 =&gt; AM\n 40 =&gt; AN\n 41 =&gt; AO\n 42 =&gt; AP\n 43 =&gt; AQ\n 44 =&gt; AR\n 45 =&gt; AS\n 46 =&gt; AT\n 47 =&gt; AU\n 48 =&gt; AV\n 49 =&gt; AW\n 50 =&gt; AX\n 51 =&gt; AY\n 52 =&gt; AZ\n</code></pre>\n" }, { "answer_id": 60323894, "author": "Pranav Mishra", "author_id": 1697718, "author_profile": "https://Stackoverflow.com/users/1697718", "pm_score": 0, "selected": false, "text": "<p>This is a common question asked in coding test.\nit has some constraints:\nmax columns per row= 702\noutput should have row number+column name e.g. for 703 answer is 2A.\n(note: i have just modified existing code from another answer)\nhere is the code for the same:</p>\n\n<pre><code> static string GetExcelColumnName(long columnNumber)\n {\n //max number of column per row\n const long maxColPerRow = 702;\n //find row number\n long rowNum = (columnNumber / maxColPerRow);\n //find tierable columns in the row.\n long dividend = columnNumber - (maxColPerRow * rowNum);\n\n string columnName = String.Empty;\n\n long modulo;\n\n while (dividend &gt; 0)\n {\n modulo = (dividend - 1) % 26;\n columnName = Convert.ToChar(65 + modulo).ToString() + columnName;\n dividend = (int)((dividend - modulo) / 26);\n }\n\n return rowNum+1+ columnName;\n }\n}\n</code></pre>\n" }, { "answer_id": 60853972, "author": "Agneum", "author_id": 4774960, "author_profile": "https://Stackoverflow.com/users/4774960", "pm_score": 0, "selected": false, "text": "<p><strong>T-SQL (SQL SERVER 18)</strong></p>\n\n<p>Copy of the solution on first page</p>\n\n<pre><code>CREATE FUNCTION dbo.getExcelColumnNameByOrdinal(@RowNum int) \nRETURNS varchar(5) \nAS \nBEGIN \n DECLARE @dividend int = @RowNum;\n DECLARE @columnName varchar(max) = '';\n DECLARE @modulo int;\n\n WHILE (@dividend &gt; 0)\n BEGIN \n SELECT @modulo = ((@dividend - 1) % 26);\n SELECT @columnName = CHAR((65 + @modulo)) + @columnName;\n SELECT @dividend = CAST(((@dividend - @modulo) / 26) as int);\n END\n RETURN \n @columnName;\n\nEND;\n</code></pre>\n" }, { "answer_id": 63238554, "author": "Hunter", "author_id": 416207, "author_profile": "https://Stackoverflow.com/users/416207", "pm_score": 0, "selected": false, "text": "<p>Here is a simpler solution for zero based column Index</p>\n<pre><code> public static string GetColumnIndexNumberToExcelColumn(int columnIndex)\n {\n int offset = columnIndex % 26;\n int multiple = columnIndex / 26;\n\n int initialSeed = 65;//Represents column &quot;A&quot;\n if (multiple == 0)\n {\n return Convert.ToChar(initialSeed + offset).ToString();\n }\n\n return $&quot;{Convert.ToChar(initialSeed + multiple - 1)}{Convert.ToChar(initialSeed + offset)}&quot;;\n }\n</code></pre>\n" }, { "answer_id": 66651166, "author": "Chirag Sheth", "author_id": 12910923, "author_profile": "https://Stackoverflow.com/users/12910923", "pm_score": 1, "selected": false, "text": "<p>This snippet works for A to ZZ column Names</p>\n<pre><code>string columnName = columnNumber &gt; 26 ? Convert.ToChar(64 + (columnNumber / 26)).ToString() + Convert.ToChar(64 + (columnNumber % 26)) : Convert.ToChar(64 + columnNumber).ToString();\n</code></pre>\n" }, { "answer_id": 72162327, "author": "desseim", "author_id": 3055345, "author_profile": "https://Stackoverflow.com/users/3055345", "pm_score": 3, "selected": false, "text": "<p>Although there are already a bunch of valid answers<sup>1</sup>, none get into the theory behind it.</p>\n<p>Excel column names are <a href=\"https://en.wikipedia.org/wiki/Bijective_numeration#The_bijective_base-26_system\" rel=\"nofollow noreferrer\">bijective base-26</a> representations of their number. This is quite different than an ordinary base 26 (there is no leading zero), and I really recommend reading the <a href=\"https://en.wikipedia.org/wiki/Bijective_numeration\" rel=\"nofollow noreferrer\">Wikipedia entry</a> to grasp the differences. For example, the decimal value <code>702</code> (decomposed in <code>26*26 + 26</code>) is represented in &quot;ordinary&quot; base 26 by <code>110</code> (i.e. <code>1x26^2 + 1x26^1 + 0x26^0</code>) and in <em>bijective</em> base-26 by <code>ZZ</code> (i.e. <code>26x26^1 + 26x26^0</code>).</p>\n<p>Differences aside, bijective numeration <em>is</em> a <a href=\"https://en.wikipedia.org/wiki/Positional_notation\" rel=\"nofollow noreferrer\">positional notation</a>, and as such we can perform conversions using an iterative (or recursive) algorithm which on each iteration finds the digit of the next position (similarly to an ordinary base conversion algorithm).</p>\n<p>The <a href=\"https://en.wikipedia.org/wiki/Bijective_numeration#Definition\" rel=\"nofollow noreferrer\">general formula</a> to get the digit at the last position (the one indexed 0) of the bijective base-<code>k</code> representation of a decimal number <code>m</code> is (<code>f</code> being the ceiling function minus 1):</p>\n<pre><code>m - (f(m / k) * k)\n</code></pre>\n<p>The digit at the next position (i.e. the one indexed 1) is found by applying the same formula to the result of <code>f(m / k)</code>. We know that for the last digit (i.e. the one with the highest index) <code>f(m / k)</code> is 0.</p>\n<p>This forms the basis for an iteration that finds each successive digit in bijective base-<code>k</code> of a decimal number. In pseudo-code it would look like this (<code>digit()</code> maps a decimal integer to its representation in the bijective base -- e.g. <code>digit(1)</code> would return <code>A</code> in bijective base-26):</p>\n<pre><code>fun conv(m)\n q = f(m / k)\n a = m - (q * k)\n if (q == 0)\n return digit(a)\n else\n return conv(q) + digit(a);\n</code></pre>\n<p>So we can translate this to C#<sup>2</sup> to get a generic<sup>3</sup> &quot;conversion to bijective base-k&quot; <code>ToBijective()</code> routine:</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>class BijectiveNumeration {\n private int baseK;\n private Func&lt;int, char&gt; getDigit;\n public BijectiveNumeration(int baseK, Func&lt;int, char&gt; getDigit) {\n this.baseK = baseK;\n this.getDigit = getDigit;\n }\n\n public string ToBijective(double decimalValue) {\n double q = f(decimalValue / baseK);\n double a = decimalValue - (q * baseK);\n return ((q &gt; 0) ? ToBijective(q) : &quot;&quot;) + getDigit((int)a);\n }\n\n private static double f(double i) {\n return (Math.Ceiling(i) - 1);\n }\n}\n</code></pre>\n<p>Now for conversion to bijective base-26 (our &quot;Excel column name&quot; use case):</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>static void Main(string[] args)\n{\n BijectiveNumeration bijBase26 = new BijectiveNumeration(\n 26,\n (value) =&gt; Convert.ToChar('A' + (value - 1))\n );\n\n Console.WriteLine(bijBase26.ToBijective(1)); // prints &quot;A&quot;\n Console.WriteLine(bijBase26.ToBijective(26)); // prints &quot;Z&quot;\n Console.WriteLine(bijBase26.ToBijective(27)); // prints &quot;AA&quot;\n Console.WriteLine(bijBase26.ToBijective(702)); // prints &quot;ZZ&quot;\n Console.WriteLine(bijBase26.ToBijective(16384)); // prints &quot;XFD&quot;\n}\n</code></pre>\n<p>Excel's maximum column index is <code>16384</code> / <code>XFD</code>, but this code will convert any positive number.</p>\n<p>As an added bonus, we can now easily convert to any bijective base. For example for <a href=\"https://en.wikipedia.org/wiki/Bijective_numeration#The_bijective_base-10_system\" rel=\"nofollow noreferrer\">bijective base-10</a>:</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>static void Main(string[] args)\n{\n BijectiveNumeration bijBase10 = new BijectiveNumeration(\n 10,\n (value) =&gt; value &lt; 10 ? Convert.ToChar('0'+value) : 'A'\n );\n\n Console.WriteLine(bijBase10.ToBijective(1)); // prints &quot;1&quot;\n Console.WriteLine(bijBase10.ToBijective(10)); // prints &quot;A&quot;\n Console.WriteLine(bijBase10.ToBijective(123)); // prints &quot;123&quot;\n Console.WriteLine(bijBase10.ToBijective(20)); // prints &quot;1A&quot;\n Console.WriteLine(bijBase10.ToBijective(100)); // prints &quot;9A&quot;\n Console.WriteLine(bijBase10.ToBijective(101)); // prints &quot;A1&quot;\n Console.WriteLine(bijBase10.ToBijective(2010)); // prints &quot;19AA&quot;\n}\n</code></pre>\n<hr />\n<p><sup>1</sup> This generic answer can eventually be reduced to the other, correct, specific answers, but I find it hard to fully grasp the logic of the solutions without the formal theory behind bijective numeration in general. It also proves its correctness nicely. Additionally, several similar questions link back to this one, some being language-agnostic or more generic. That's why I thought the addition of this answer was warranted, and that this question was a good place to put it.</p>\n<p><sup>2</sup> C# disclaimer: I implemented an example in C# because this is what is asked here, but I have never learned nor used the language. I have verified it does compile and run, but please adapt it to fit the language best practices / general conventions, if necessary.</p>\n<p><sup>3</sup> This example only aims to be correct and understandable ; it could and should be optimized would performance matter (e.g. with tail-recursion -- but that seems to <a href=\"https://thomaslevesque.com/2011/09/02/tail-recursion-in-c/\" rel=\"nofollow noreferrer\">require trampolining</a> in C#), and made safer (e.g. by validating parameters).</p>\n" }, { "answer_id": 72744619, "author": "Ramil Shavaleev", "author_id": 7250868, "author_profile": "https://Stackoverflow.com/users/7250868", "pm_score": 0, "selected": false, "text": "<p>My solution based on <a href=\"https://stackoverflow.com/a/182924/7250868\">Graham</a>, <a href=\"https://stackoverflow.com/a/39018386/7250868\">Herman Kan</a> and <a href=\"https://stackoverflow.com/a/72162327/7250868\">desseim</a> answers, with using StringBuilder:</p>\n<pre><code>internal class Program\n{\n #region get_excel_col_name\n /// &lt;summary&gt;\n /// Returns the name of the column by its number\n /// &lt;/summary&gt;\n /// &lt;param name=&quot;col_num&quot;&gt;Column number&lt;/param&gt;\n /// &lt;returns&gt;Column name&lt;/returns&gt;\n /// &lt;remarks&gt;Numbering columns from zero&lt;/remarks&gt;\n private static string get_excel_col_name(int col_num)\n {\n StringBuilder sb = new StringBuilder(2);\n if (col_num &gt;= 0)\n {\n do\n {\n sb.Insert(0, (char)(col_num % 26 + 65));\n col_num /= 26;\n }\n while (--col_num &gt;= 0);\n }\n return sb.ToString();\n }\n #endregion\n\n private static void Main(string[] args)\n {\n Console.WriteLine(get_excel_col_name(34));//outputs AI\n Console.ReadKey(true);\n }\n}\n</code></pre>\n" }, { "answer_id": 73153547, "author": "yuriy", "author_id": 1095566, "author_profile": "https://Stackoverflow.com/users/1095566", "pm_score": 0, "selected": false, "text": "<pre><code> static string[] ExcelColumnAlphabetIdentifiers = new string[] { &quot;&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &quot;G&quot;, &quot;H&quot;, &quot;I&quot;, &quot;J&quot;, &quot;K&quot;, &quot;L&quot;, &quot;M&quot;, &quot;N&quot;, \n &quot;O&quot;, &quot;P&quot;, &quot;Q&quot;, &quot;R&quot;, &quot;S&quot;, &quot;T&quot;, &quot;U&quot;, &quot;V&quot;, &quot;W&quot;, &quot;X&quot;, &quot;Y&quot;, &quot;Z&quot; };\n public static string ExcelColumnAlphabetIdentifier( int ColumnNumber)\n {\n StringBuilder sb = new StringBuilder();\n int remainder = ColumnNumber;\n do\n {\n sb.Append(ExcelColumnAlphabetIdentifiers[remainder % 26]);\n remainder = remainder / 26;\n }\n while (remainder &gt; 0);\n return sb.ToString();\n }\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3851/" ]
How do you convert a numerical number to an Excel column name in C# without using automation getting the value directly from Excel. Excel 2007 has a possible range of 1 to 16384, which is the number of columns that it supports. The resulting values should be in the form of excel column names, e.g. A, AA, AAA etc.
Here's how I do it: ``` private string GetExcelColumnName(int columnNumber) { string columnName = ""; while (columnNumber > 0) { int modulo = (columnNumber - 1) % 26; columnName = Convert.ToChar('A' + modulo) + columnName; columnNumber = (columnNumber - modulo) / 26; } return columnName; } ```
181,605
<p>I wrote a wrapper for a COM object that only excepted strings as input, so in good OOP practice I wrapped the string up in a function so that it was easier to build and call.</p> <p>I was just wondering if anyone could think of a better way to do the following code. </p> <pre><code> Public Function OpenTable(ByVal TablePath As String, Optional ByVal OpenAs As String = Nothing, _ Optional ByVal Hide As Boolean = False, Optional ByVal AsReadOnly As Boolean = False, _ Optional ByVal Interactive As Boolean = True, Optional ByVal Password As String = Nothing, _ Optional ByVal NoIndex As Boolean = False, Optional ByVal ViewAutomatic As Boolean = True) As TableInfo If String.IsNullOrEmpty(TablePath) Then Throw New ArgumentNullException("TablePath", "TablePath cannot be null or empty") End If Dim Builder = New StringBuilder("Open Table ") Builder.AppendFormat("{0}{1}{2}", ControlChars.Quote, TablePath, ControlChars.Quote) If (Not String.IsNullOrEmpty(OpenAs)) Then Builder.AppendFormat(" as {0} ", OpenAs) If (Hide) Then Builder.Append(" Hide ") If (AsReadOnly) Then Builder.Append(" ReadOnly ") If (Interactive) Then Builder.Append(" Interactive ") If (Not String.IsNullOrEmpty(Password)) Then Builder.AppendFormat(" Password {0} ", Password) If (NoIndex) Then Builder.Append(" NoIndex ") If (ViewAutomatic) Then Builder.Append(" View Automatic ") MyComApp.Do(Builder.ToString) Dim FileInfo = New IO.FileInfo(TablePath) Return New TableInfo(FileInfo.Name.Substring(0, InStrRev(FileInfo.Name, ".") - 1)) End Function </code></pre> <p>The amount of arguments that the function has to take is my biggest worry. This one is not too bad but there are some other functions that I may have to make in the future that will take a lot more arguments, so I'm mainly looking for better ways to build large argument functions.</p>
[ { "answer_id": 181616, "author": "Alexander Morland", "author_id": 4013, "author_profile": "https://Stackoverflow.com/users/4013", "pm_score": 0, "selected": false, "text": "<p>Since i dont know your programming language, im gonna keep this to pseudo code, but my general answer is to use ann array as single parameter:</p>\n\n<pre><code>function OpenTable( options As array) {\n if (options is not array or options is empty) {\n Throw exception\n }\n return_string = \"\";\n if ( key is set ('readOnly', options) and is not empty) {\n return_string = return_string + ' readonly';\n }\n // repeat last 3 lines for all your params\n}\n</code></pre>\n\n<p>Ok the last part of your function doesnt make sense to me, but the idea of array of params should come across i think. Good luck.</p>\n" }, { "answer_id": 181618, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>One way to handle functions that can take lots of arguments is to create a new object type whose sole purpose is to hold arguments for that function. Then you create a new object of that type, set the properties as needed, then pass that one object reference to your <code>OpenTable</code> function.</p>\n" }, { "answer_id": 181619, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": true, "text": "<p>In this case it seems many of the parameters are just 'configuration values' (which end up being strings), you could modify it to accept a single class for all the configuration that you prepare before the call and that will return you the string accordingly.</p>\n\n<p>Something like</p>\n\n<pre><code>class COMConfiguration {\n private bool Hide = false;\n private bool AsReadOnly = false;\n //and so on...\n\n public void setHide(bool v) { Hide = v; }\n\n //only setters\n\n public string getConfigString() {\n StringBuilder sb = new StringBuilder();\n if (Hide) { sb.Append(\" Hide \"); }\n if (AsReadOnly) { sb.Append(\" ReadOnly \"); }\n //and so on\n return sb.ToString()\n }\n}\n</code></pre>\n" }, { "answer_id": 181639, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 0, "selected": false, "text": "<p>You can switch all your boolean parameters to a single parameter of an <a href=\"http://msdn.microsoft.com/en-us/library/8h84wky1(VS.80).aspx\" rel=\"nofollow noreferrer\">enum</a> type, marked as <a href=\"http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx\" rel=\"nofollow noreferrer\">Flags</a>. Here's an example declaration:</p>\n\n<pre><code>' Define an Enum with FlagsAttribute.\n&lt;FlagsAttribute( )&gt; _\nEnum TableOptions as Short\n Hide = 1\n AsReadOnly = 2\n Interactive = 4\n NoIndex = 8\n ViewAutomatic = 16\nEnd Enum\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6335/" ]
I wrote a wrapper for a COM object that only excepted strings as input, so in good OOP practice I wrapped the string up in a function so that it was easier to build and call. I was just wondering if anyone could think of a better way to do the following code. ``` Public Function OpenTable(ByVal TablePath As String, Optional ByVal OpenAs As String = Nothing, _ Optional ByVal Hide As Boolean = False, Optional ByVal AsReadOnly As Boolean = False, _ Optional ByVal Interactive As Boolean = True, Optional ByVal Password As String = Nothing, _ Optional ByVal NoIndex As Boolean = False, Optional ByVal ViewAutomatic As Boolean = True) As TableInfo If String.IsNullOrEmpty(TablePath) Then Throw New ArgumentNullException("TablePath", "TablePath cannot be null or empty") End If Dim Builder = New StringBuilder("Open Table ") Builder.AppendFormat("{0}{1}{2}", ControlChars.Quote, TablePath, ControlChars.Quote) If (Not String.IsNullOrEmpty(OpenAs)) Then Builder.AppendFormat(" as {0} ", OpenAs) If (Hide) Then Builder.Append(" Hide ") If (AsReadOnly) Then Builder.Append(" ReadOnly ") If (Interactive) Then Builder.Append(" Interactive ") If (Not String.IsNullOrEmpty(Password)) Then Builder.AppendFormat(" Password {0} ", Password) If (NoIndex) Then Builder.Append(" NoIndex ") If (ViewAutomatic) Then Builder.Append(" View Automatic ") MyComApp.Do(Builder.ToString) Dim FileInfo = New IO.FileInfo(TablePath) Return New TableInfo(FileInfo.Name.Substring(0, InStrRev(FileInfo.Name, ".") - 1)) End Function ``` The amount of arguments that the function has to take is my biggest worry. This one is not too bad but there are some other functions that I may have to make in the future that will take a lot more arguments, so I'm mainly looking for better ways to build large argument functions.
In this case it seems many of the parameters are just 'configuration values' (which end up being strings), you could modify it to accept a single class for all the configuration that you prepare before the call and that will return you the string accordingly. Something like ``` class COMConfiguration { private bool Hide = false; private bool AsReadOnly = false; //and so on... public void setHide(bool v) { Hide = v; } //only setters public string getConfigString() { StringBuilder sb = new StringBuilder(); if (Hide) { sb.Append(" Hide "); } if (AsReadOnly) { sb.Append(" ReadOnly "); } //and so on return sb.ToString() } } ```
181,613
<p>This is the unabashed attempt of a similar <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c">C#</a> question.</p> <p>So what are your favorite F# hidden (or not) features?</p> <p>Most of the features I've used so far aren't exactly hidden but have been quite refreshing. Like how trivial it is to overload operators compared to say C# or VB.NET.</p> <p>And <code>Async&lt;T&gt;</code> has helped me shave off some real ugly code.</p> <p>I'm quite new to the language still so it'd be great to learn what other features are being used in the wild.</p>
[ { "answer_id": 181633, "author": "ChaosSpeeder", "author_id": 205962, "author_profile": "https://Stackoverflow.com/users/205962", "pm_score": 1, "selected": false, "text": "<p>There are no hidden features, because F# is in design mode. All what we have is a Technical Preview, which changes every two month.</p>\n\n<p>see <a href=\"http://research.microsoft.com/fsharp/\" rel=\"nofollow noreferrer\">http://research.microsoft.com/fsharp/</a></p>\n" }, { "answer_id": 185991, "author": "Chris Smith", "author_id": 322, "author_profile": "https://Stackoverflow.com/users/322", "pm_score": 3, "selected": false, "text": "<p>Yes, F# doesn't have any 'hidden' features, but it sure does have a lot of power packed into the simple language. A less-known feature of the language, is where you can basically <a href=\"http://www.atrevido.net/blog/2008/08/31/Statically+Typed+Duck+Typing+In+F.aspx\" rel=\"nofollow noreferrer\">enable duck typing</a> despite the fact F# is staticaly typed.</p>\n" }, { "answer_id": 211691, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 3, "selected": false, "text": "<p>Automatically-generated comparison functions for algebraic data types (based on lexicographical ordering) is a nice feature that is relatively unknown; see</p>\n\n<p><a href=\"http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!548.entry\" rel=\"nofollow noreferrer\">http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!548.entry</a></p>\n\n<p>for an example.</p>\n" }, { "answer_id": 846036, "author": "Precipitous", "author_id": 77784, "author_profile": "https://Stackoverflow.com/users/77784", "pm_score": 2, "selected": false, "text": "<p>Use of F# as a utility scripting language may be under appreciated. F# enthusiasts tend to be quants. Sometimes you want something to back up your MP3s (or dozens of database servers) that's a little more robust than batch. I've been hunting for a modern replacement for jscript / vbscript. Lately, I've used IronPython, but F# may be more complete and the .NET interaction is less cumbersome. </p>\n\n<p>I like <a href=\"https://stackoverflow.com/questions/8448/f-curried-function\">curried functions</a> for entertainment value. Show a curried function to a pure procedural / OOP program for at least three WTFs. Starting with this is a bad way to get F# converts, though :)</p>\n" }, { "answer_id": 1170259, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 3, "selected": false, "text": "<p>See this question </p>\n\n<p><a href=\"https://stackoverflow.com/questions/890794/f-operator\">F# operator &quot;?&quot;</a></p>\n\n<p>for info on the question-mark operator and how it provides the basic language mechanism to build a feature akin to 'dynamic' in C#.</p>\n" }, { "answer_id": 1844881, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 3, "selected": false, "text": "<p>F# has a little-used feature called \"signature files\". You can have a big implementation file full of <em>public</em> types/methods/modules/functions, but then you can <em>hide and selectively expose</em> that functionality to the sequel of the program via a signature file. That is, a signature file acts as a kind of screen/filter that enables you to make entities \"public to this file\" but \"private to the rest of the program\".</p>\n\n<p>I feel like this is a pretty killer feature on the .Net platform, because the only other/prior tool you have for this kind of encapsulation is assemblies. If you have a small component with a few related types that want to be able to see each other's internal details, but don't want those types to have all those bits public to <em>everyone</em>, what can you do? Well, you can do two things:</p>\n\n<ol>\n<li>You can put that component in a separate assembly, and make the members that those types share be \"internal\", and make the narrow part you want everyone else to see be \"public\", or</li>\n<li>You just mark the internal stuff \"internal\" but you leave those types in your gigantic assembly and just hope that all the other code in the assembly chooses not to call those members that were only marked 'internal' because one other type needed to see it.</li>\n</ol>\n\n<p>In my experience, on large software projects, everyone always does #2, because #1 is a non-starter for various reasons (people don't want 50 small assemblies, they want 1 or 2 or 3 large assemblies, for other maybe-good reasons unrelated to the encapsulation point I am raising (aside: everyone mentions ILMerge but no one uses it)).</p>\n\n<p>So you chose option #2. Then a year later, you finally decide to refactor out that component, and you discover that over the past year, 17 other places now call into that 'internal' method that was really only meant for that one other type to call, making it really hard to factor out that bit because now everyone depends on those implementation details. Bummer.</p>\n\n<p>The point is, there is no good way to create a moderate-size intra-assembly encapsulation scope/boundary in .Net. Often times \"internal\" is too big and \"private\" is too small.</p>\n\n<p>... until F#. With F# signature files, you can create an encapsulation scope of \"this source code file\" by marking a bunch of stuff as public within the implementation file, so all the other code in the file can see it and party on it, but then use a signature file to hide all of the details expect the narrow public interface that component exposes to the rest of the world. This is happy. Define three highly related types in one file, let them see each others implementation details, but only expose the truly public stuff to everyone else. Win!</p>\n\n<p>Signature files are perhaps not the <em>ideal</em> feature for intra-assembly encapsulation boundaries, but they are the <em>only</em> such feature I know, and so I cling to them like a life raft in the ocean.</p>\n\n<p>TL;DR</p>\n\n<p>Complexity is the enemy. Encapsulation boundaries are a weapon against this enemy. \"private\" is a great weapon but sometimes too small to be applicable, and \"internal\" is often too weak because so much code (entire assembly and all InternalsVisibleTo's) can see internal stuff. F# offers a scope bigger than \"private to a type\" but smaller than \"the whole assembly\", and that is very useful.</p>\n" }, { "answer_id": 1846680, "author": "kvb", "author_id": 82959, "author_profile": "https://Stackoverflow.com/users/82959", "pm_score": 2, "selected": false, "text": "<p>Inlined operators on generic types can have different generic constraints:</p>\n\n<pre><code>type 'a Wrapper = Wrapper of 'a with\n static member inline (+)(Wrapper(a),Wrapper(b)) = Wrapper(a + b)\n static member inline Exp(Wrapper(a)) = Wrapper(exp a)\n\nlet objWrapper = Wrapper(obj())\nlet intWrapper = (Wrapper 1) + (Wrapper 2)\nlet fltWrapper = exp (Wrapper 1.0)\n\n(* won''t compile *)\nlet _ = exp (Wrapper 1)\n</code></pre>\n" }, { "answer_id": 1846741, "author": "kvb", "author_id": 82959, "author_profile": "https://Stackoverflow.com/users/82959", "pm_score": 5, "selected": false, "text": "<p>User defined numeric literals can be defined by providing a module whose name starts with <code>NumericLiteral</code> and which defines certain methods (<code>FromZero</code>, <code>FromOne</code>, etc.).</p>\n\n<p>In particular, you can use this to provide a much more readable syntax for calling <code>LanguagePrimitives.GenericZero</code> and <code>LanguagePrimitives.GenericOne</code>:</p>\n\n<pre><code>module NumericLiteralG = begin\n let inline FromZero() = LanguagePrimitives.GenericZero\n let inline FromOne() = LanguagePrimitives.GenericOne\nend\n\nlet inline genericFactorial n =\n let rec fact n = if (n = 0G) then 1G else n * (fact (n - 1G))\n fact n\n\nlet flt = genericFactorial 30.\nlet bigI = genericFactorial 30I\n</code></pre>\n" }, { "answer_id": 3138320, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 3, "selected": false, "text": "<p>Passing <code>--warnon:1182</code> to the compiler turns on warnings about unused variables; variable names that begin with underscore are immune.</p>\n" }, { "answer_id": 3141668, "author": "Dan Fitch", "author_id": 27614, "author_profile": "https://Stackoverflow.com/users/27614", "pm_score": 3, "selected": false, "text": "<p>Not really <em>hidden</em>, but as a non-ML person this escaped me for quite a while:</p>\n\n<p>Pattern matching can decompose <strong>arbitrarily deep</strong> into data structures.</p>\n\n<p>Here's a [incredibly arbitrary] nested tuple example; this works on lists or unions or any combinations of nested values:</p>\n\n<pre><code>let listEven =\n \"Manipulating strings can be intriguing using F#\".Split ' '\n |&gt; List.ofArray\n |&gt; List.map (fun x -&gt; (x.Length % 2 = 0, x.Contains \"i\"), x)\n |&gt; List.choose \n ( function (true, true), s -&gt; Some s \n | _, \"F#\" -&gt; Some \"language\" \n | _ -&gt; None ) \n</code></pre>\n" }, { "answer_id": 3869778, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 3, "selected": false, "text": "<p>I wonder what happens if you add</p>\n\n<pre><code>&lt;appSettings&gt;\n &lt;add key=\"fsharp-navigationbar-enabled\" value=\"true\" /&gt;\n&lt;/appSettings&gt;\n</code></pre>\n\n<p>to your devenv.exe.config file? (Use at your own risk.)</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8280/" ]
This is the unabashed attempt of a similar [C#](https://stackoverflow.com/questions/9033/hidden-features-of-c) question. So what are your favorite F# hidden (or not) features? Most of the features I've used so far aren't exactly hidden but have been quite refreshing. Like how trivial it is to overload operators compared to say C# or VB.NET. And `Async<T>` has helped me shave off some real ugly code. I'm quite new to the language still so it'd be great to learn what other features are being used in the wild.
User defined numeric literals can be defined by providing a module whose name starts with `NumericLiteral` and which defines certain methods (`FromZero`, `FromOne`, etc.). In particular, you can use this to provide a much more readable syntax for calling `LanguagePrimitives.GenericZero` and `LanguagePrimitives.GenericOne`: ``` module NumericLiteralG = begin let inline FromZero() = LanguagePrimitives.GenericZero let inline FromOne() = LanguagePrimitives.GenericOne end let inline genericFactorial n = let rec fact n = if (n = 0G) then 1G else n * (fact (n - 1G)) fact n let flt = genericFactorial 30. let bigI = genericFactorial 30I ```
181,643
<p>I basically need to show a wait window to the user. For this i have put two seperate window forms in the application. the first form is the main form with a button. The second one is a empty one with just a label text. On click of the button in Form1 i do the below </p> <pre><code>Form2 f = new Form2(); f.Show(); Thread.Sleep(2000); f.Close(); </code></pre> <p>My idea here is to show the wait window to the user for 2 second. But when i do this the Form 2 is not completely loaded because of which the label in it is blank. Please let me know your inputs on this.</p>
[ { "answer_id": 181663, "author": "Ihar Bury", "author_id": 18001, "author_profile": "https://Stackoverflow.com/users/18001", "pm_score": 3, "selected": true, "text": "<p>That's because you probably do some lengthy operation in the same thread (UI thread). You should execute your code in a new thread (see Thread class) or at least call Application.DoEvents periodically from inside your lengthy operation to update the UI.</p>\n" }, { "answer_id": 181664, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>You're basically blocking the UI thread.</p>\n\n<p>I suggest that instead, you make your Form2 constructor (or possibly Load event handler) start a timer which will fire two seconds later. When the timer fires, close the form. During those two seconds, the UI thread will be free, so everything will display properly and the user will be able to move the window etc.</p>\n" }, { "answer_id": 181683, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 2, "selected": false, "text": "<p>When yo use Thread.Sleep you will disable the windows message loop and prevent the window from painting itself. </p>\n\n<p>You could force a repaint:</p>\n\n<pre><code>f.Refresh();\n</code></pre>\n\n<p>Or better yet use a timer with a callback.</p>\n\n<pre><code>Timer t = new Timer();\nt.Interval = 2000;\nt.Tick += delegate { Close(); t.Stop();};\nt.Start();\n</code></pre>\n\n<p>To prevent users from clicking in the original window you can open the new form as a dialog:</p>\n\n<pre><code>f.ShowDialog();\n</code></pre>\n" }, { "answer_id": 181702, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": -1, "selected": false, "text": "<p>You can (an always should for UI threads) use <a href=\"http://msdn.microsoft.com/en-us/library/6b1kkss0.aspx\" rel=\"nofollow noreferrer\">Thread.Current.Join(2000)</a> instead of Thread.Sleep(2000).</p>\n" }, { "answer_id": 181834, "author": "GvS", "author_id": 11492, "author_profile": "https://Stackoverflow.com/users/11492", "pm_score": 0, "selected": false, "text": "<p>I think you should just use</p>\n\n<pre><code>f.ShowDialog(this);\n</code></pre>\n\n<p>Then control is returned when f is closed.</p>\n\n<p>By using the sleep, you are blocking the UI thread from updating for 2 seconds. (The thread is asleep).</p>\n" }, { "answer_id": 6380878, "author": "Trev", "author_id": 802581, "author_profile": "https://Stackoverflow.com/users/802581", "pm_score": 2, "selected": false, "text": "<p>Here is a Waiting Box class I use. Here is how you use it:</p>\n\n<pre><code>using WaitingBox;\nShowWaitingBox waiting = new ShowWaitingBox(\"Title Text\",\"Some Text so the user knows whats going on..\");\nwaiting.Start();\n//do something that takes a while\nwaiting.Stop();\n</code></pre>\n\n<p>Here is the code for WaitingBox:</p>\n\n<pre><code> using System;\n using System.Collections.Generic;\n using System.ComponentModel;\n using System.Data;\n using System.Drawing;\n using System.Linq;\n using System.Text;\n using System.Windows.Forms;\n using System.Threading;\n\n\n\n namespace WaitingBox\n {\n public class ShowWaitingBox\n {\n private class WaitingForm:Form\n {\n public WaitingForm()\n {\n this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();\n this.label1 = new System.Windows.Forms.Label();\n this.progressBar1 = new System.Windows.Forms.ProgressBar();\n this.tableLayoutPanel1.SuspendLayout();\n this.SuspendLayout();\n // \n // tableLayoutPanel1\n // \n this.tableLayoutPanel1.ColumnCount = 1;\n this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));\n this.tableLayoutPanel1.Controls.Add(this.progressBar1, 0, 0);\n this.tableLayoutPanel1.Controls.Add(this.label1, 0, 2);\n this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;\n this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);\n this.tableLayoutPanel1.Name = \"tableLayoutPanel1\";\n this.tableLayoutPanel1.RowCount = 3;\n this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));\n this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 29F));\n this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));\n this.tableLayoutPanel1.Size = new System.Drawing.Size(492, 155);\n this.tableLayoutPanel1.TabIndex = 0;\n // \n // label1\n // \n this.label1.Anchor = System.Windows.Forms.AnchorStyles.Top;\n this.label1.AutoSize = true;\n this.label1.Location = new System.Drawing.Point(209, 92);\n this.label1.Name = \"label1\";\n this.label1.Size = new System.Drawing.Size(73, 13);\n this.label1.TabIndex = 3;\n this.label1.Text = \"Please Wait...\";\n // \n // progressBar1\n // \n this.progressBar1.Anchor = System.Windows.Forms.AnchorStyles.Bottom;\n this.progressBar1.Location = new System.Drawing.Point(22, 37);\n this.progressBar1.Name = \"progressBar1\";\n this.progressBar1.Size = new System.Drawing.Size(447, 23);\n this.progressBar1.TabIndex = 2;\n // \n // WaitingForm\n // \n this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);\n this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;\n this.ClientSize = new System.Drawing.Size(492, 155);\n this.Controls.Add(this.tableLayoutPanel1);\n this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;\n this.Name = \"WaitingForm\";\n this.Text = \"Working in the background\";\n this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.WaitingForm_FormClosing);\n this.Load += new System.EventHandler(this.WaitingForm_Load);\n this.tableLayoutPanel1.ResumeLayout(false);\n this.tableLayoutPanel1.PerformLayout();\n this.ResumeLayout(false);\n }\n\n private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;\n private System.Windows.Forms.ProgressBar progressBar1;\n private System.Windows.Forms.Label label1;\n\n private void WaitingForm_Load(object sender, EventArgs e)\n {\n progressBar1.Style = ProgressBarStyle.Marquee;\n this.BringToFront();\n this.CenterToScreen();\n }\n\n private void WaitingForm_FormClosing(object sender, FormClosingEventArgs e)\n {\n }\n\n internal void SetLabel(string p)\n {\n label1.Text = p;\n }\n }\n private WaitingForm wf = new WaitingForm();\n private string title, text;\n private Thread waiting;\n public bool IsAlive\n {\n get\n {\n return waiting.IsAlive;\n }\n set { }\n }\n public ShowWaitingBox(string Title, string Text)\n {\n this.title = string.IsNullOrEmpty(Title) ? \"Working in the Background..\": Title;\n this.text = string.IsNullOrEmpty(Text) ? \"Please wait...\" : Text;\n waiting = new Thread(new ThreadStart(Show));\n\n }\n\n public ShowWaitingBox()\n {\n waiting = new Thread(new ThreadStart(Show));\n }\n\n private void Show()\n {\n wf.Show();\n wf.Text = this.title;\n wf.SetLabel(this.text);\n while (true) {\n\n wf.Refresh();\n System.Threading.Thread.Sleep(50);\n }\n }\n public void Start()\n {\n waiting.Start();\n }\n public void Stop()\n {\n waiting.Abort();\n }\n }\n }\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20951/" ]
I basically need to show a wait window to the user. For this i have put two seperate window forms in the application. the first form is the main form with a button. The second one is a empty one with just a label text. On click of the button in Form1 i do the below ``` Form2 f = new Form2(); f.Show(); Thread.Sleep(2000); f.Close(); ``` My idea here is to show the wait window to the user for 2 second. But when i do this the Form 2 is not completely loaded because of which the label in it is blank. Please let me know your inputs on this.
That's because you probably do some lengthy operation in the same thread (UI thread). You should execute your code in a new thread (see Thread class) or at least call Application.DoEvents periodically from inside your lengthy operation to update the UI.
181,648
<p>I have problems opening a berkeley db in python using bdtables. As bdtables is used by the library I am using to access the database, I need it to work.</p> <p>The problem seems to be that the db environment I am trying to open (I got a copy of the database to open), is version 4.4 while libdb is version 4.6. I get the following error using bsddb.dbtables.bsdTableDB([dbname],[folder]):</p> <pre><code>(-30972, "DB_VERSION_MISMATCH: Database environment version mismatch -- Program version 4.6 doesn't match environment version 4.4") </code></pre> <p>However, bsddb.btopen([dbname]) works.</p> <p>I have also tried installing db4.4-util, db4.5-util and db4.6-util. Trying to use db4.6_verify results in:</p> <pre><code>db4.6_verify: Program version 4.6 doesn't match environment version 4.4 db4.6_verify: DB_ENV-&gt;open: DB_VERSION_MISMATCH: Database environment version mismatchs </code></pre> <p>db4.4_verify results in the computer just hanging, and nothing happening.</p> <p>Finally, if I run db4.4_recover on the database, that works. However, afterwards I get the following error 'No such file or directory' in python.</p>
[ { "answer_id": 185678, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": true, "text": "<p>I think answers should go in the \"answer\" section rather than as an addendum to the question since that marks the question as having an answer on the various question-list pages. I'll do that for you but, if you also get around to doing it, leave a comment on my answer so I can delete it.</p>\n\n<p>Quoting \"answer in question\":</p>\n\n<p>Verifying everything in this question, I eventually solved the problem. The 'No such file or directory' are caused by some __db.XXX files missing. Using</p>\n\n<pre><code>bsddb.dbtables.bsdTableDB([dbname],[folder], create=1)\n</code></pre>\n\n<p>after db4.4_recover, these files got created and everything is now working.</p>\n\n<p>Still, it was a bit of an obscure problem, and initially hard to figure out. But thanks to the question <a href=\"https://stackoverflow.com/questions/37644/examining-berkeley-db-files-from-the-cli\">Examining Berkeley DB files from the CLI</a>, I got the tools I needed. I'll just post it here if someone ends up with the same problem in the future and end up at stackoverflow.com</p>\n" }, { "answer_id": 194022, "author": "Staale", "author_id": 3355, "author_profile": "https://Stackoverflow.com/users/3355", "pm_score": 0, "selected": false, "text": "<p>Damn, verifying everything in this question I eventually solved the problem. The 'No such file or directory' are caused by some __db.XXX files missing. Using bsddb.dbtables.bsdTableDB([dbname],[folder], create=1) after db4.4_recover, these files got created and everything is now working.</p>\n\n<p>Still, it was a bit of an obscure problem, and initially hard to figure out. But thanks to the question Examining Berkeley DB files from the CLI I got the tools I needed. I'll just post it here if someone ends up with the same problem in the future and end up at stackoverflow.com</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355/" ]
I have problems opening a berkeley db in python using bdtables. As bdtables is used by the library I am using to access the database, I need it to work. The problem seems to be that the db environment I am trying to open (I got a copy of the database to open), is version 4.4 while libdb is version 4.6. I get the following error using bsddb.dbtables.bsdTableDB([dbname],[folder]): ``` (-30972, "DB_VERSION_MISMATCH: Database environment version mismatch -- Program version 4.6 doesn't match environment version 4.4") ``` However, bsddb.btopen([dbname]) works. I have also tried installing db4.4-util, db4.5-util and db4.6-util. Trying to use db4.6\_verify results in: ``` db4.6_verify: Program version 4.6 doesn't match environment version 4.4 db4.6_verify: DB_ENV->open: DB_VERSION_MISMATCH: Database environment version mismatchs ``` db4.4\_verify results in the computer just hanging, and nothing happening. Finally, if I run db4.4\_recover on the database, that works. However, afterwards I get the following error 'No such file or directory' in python.
I think answers should go in the "answer" section rather than as an addendum to the question since that marks the question as having an answer on the various question-list pages. I'll do that for you but, if you also get around to doing it, leave a comment on my answer so I can delete it. Quoting "answer in question": Verifying everything in this question, I eventually solved the problem. The 'No such file or directory' are caused by some \_\_db.XXX files missing. Using ``` bsddb.dbtables.bsdTableDB([dbname],[folder], create=1) ``` after db4.4\_recover, these files got created and everything is now working. Still, it was a bit of an obscure problem, and initially hard to figure out. But thanks to the question [Examining Berkeley DB files from the CLI](https://stackoverflow.com/questions/37644/examining-berkeley-db-files-from-the-cli), I got the tools I needed. I'll just post it here if someone ends up with the same problem in the future and end up at stackoverflow.com
181,652
<p>Let's say I have this model named <em>Product</em> with a field named <em>brand</em>. Suppose the values of <em>brand</em> are stored in the format <em>this_is_a_brand</em>. Can I define a method in the model (or anywhere else) that allows me to modify the value of <em>brand</em> before it is called. For example, if I call <em>@product.brand</em>, I want to get <em>This is a Brand</em>, instead of <em>this_is_a_brand</em>.</p>
[ { "answer_id": 181665, "author": "Josh Moore", "author_id": 5004, "author_profile": "https://Stackoverflow.com/users/5004", "pm_score": 0, "selected": false, "text": "<p>In your model you can override the method call <code>brand</code>.</p>\n\n<pre><code>def brand\n#code to modify the value that is stored in brand\nreturn modified_brand\nend\n</code></pre>\n\n<p>This will allow it to be stored as this_is_a_brand. But, it will be returned as \"this is a brand\".</p>\n" }, { "answer_id": 181831, "author": "tomafro", "author_id": 7126, "author_profile": "https://Stackoverflow.com/users/7126", "pm_score": 3, "selected": false, "text": "<p>Rather than accessing @attributes directly, you should use <code>read_attribute</code> and <code>write_attribute</code>:</p>\n\n<pre><code>def brand\n b = read_attribute(:brand) \n b &amp;&amp; b.transform_in_some_way\nend\n\ndef brand=(b)\n b &amp;&amp; b.transform_in_some_way\n write_attribute(:brand, b)\nend\n</code></pre>\n" }, { "answer_id": 183970, "author": "two-bit-fool", "author_id": 23899, "author_profile": "https://Stackoverflow.com/users/23899", "pm_score": 5, "selected": true, "text": "<p>I would recommend using the square bracket syntax (<code>[]</code> and <code>[]=</code>) instead of <code>read_attribute</code> and <code>write_attribute</code>. The square bracket syntax is shorter and <a href=\"http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001375\" rel=\"noreferrer\">designed to wrap the <strong>protected</strong> read/write_attribute methods</a>.</p>\n\n<pre><code>def brand\n original = self[:brand]\n transform(original)\nend\n\ndef brand=(b)\n self[:brand] = reverse_transform(b)\nend\n</code></pre>\n" }, { "answer_id": 32418376, "author": "frankpinto", "author_id": 2456847, "author_profile": "https://Stackoverflow.com/users/2456847", "pm_score": 1, "selected": false, "text": "<p>As the last answer was posted 7 years ago, I'll contribute what the <a href=\"http://api.rubyonrails.org/classes/ActiveRecord/Base.html\" rel=\"nofollow\">Rails API</a> currently suggests.</p>\n\n<pre><code>def brand\n super.humanize\nend\n</code></pre>\n\n<p><a href=\"http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-humanize\" rel=\"nofollow\">Humanize</a> turns 'this_is_a_brand' to 'This is a brand'</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9776/" ]
Let's say I have this model named *Product* with a field named *brand*. Suppose the values of *brand* are stored in the format *this\_is\_a\_brand*. Can I define a method in the model (or anywhere else) that allows me to modify the value of *brand* before it is called. For example, if I call *@product.brand*, I want to get *This is a Brand*, instead of *this\_is\_a\_brand*.
I would recommend using the square bracket syntax (`[]` and `[]=`) instead of `read_attribute` and `write_attribute`. The square bracket syntax is shorter and [designed to wrap the **protected** read/write\_attribute methods](http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001375). ``` def brand original = self[:brand] transform(original) end def brand=(b) self[:brand] = reverse_transform(b) end ```
181,693
<p>Apparently ;-) the standard containers provide some form of guarantees.</p> <p>What type of guarantees and what exactly are the differences between the different types of container?</p> <p>Working from <a href="http://www.sgi.com/tech/stl/" rel="noreferrer">the SGI page</a> (about <a href="http://en.wikipedia.org/wiki/Standard_Template_Library" rel="noreferrer">STL</a>) I have come up with this:</p> <pre><code>Container Types: ================ Container: Forward Container Reverse Container Random Access Container Sequence Front Insert Sequence Back Insert Sequence Associative Container Simple Associative Container Pair Associative Container Sorted Associative Container Multiple Associative Container Container Types mapped to Standard Containers ============================================= std::vector: Sequence Back Sequence Forward/Reverse/Random Container std::deque: Sequence Front/Back Sequence Forward/Reverse/Random Container std::list: Sequence Front/Back Sequence Forward/Reverse Container std::set: Sorted/Simple/Unique Associative Container Forward Container std::map: Sorted/Pair/Unique Associative Container Forward Container std::multiset: Sorted/Simple/Multiple Associative Container Forward Container std::multimap: Sorted/Pair/Multiple Associative Container Forward Container Container Guarantees: ===================== Simp or For Rev Rand Front Back Assoc Sort Mult Cont: Cont: Cont Cont: Sequ: Sequ: Sequ: Cont: Cont: Cont: Copy Const: O(n) Fill Const: O(n) begin() O(1) end() O(1) rbegin() O(1) rend() O(1) front() O(1) push_front() O(1) pop_front() O(1) push_back() O(1) pop_back() O(1) Insert() O(ln(n)) Insert: fill O(n) Insert: range O(n) O(kln(n)+n) size() O(1) swap() O(1) erase key O(ln(n)) erase element O(1) erase range O(ln(n)+S) count() O(log(n)+k) find() O(ln(n)) equal range O(ln(n)) Lower Bound/Upper Bound O(ln(n)) Equality O(n) InEquality O(n) Element Access O(1) </code></pre>
[ { "answer_id": 181770, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 3, "selected": false, "text": "<p>I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).</p>\n\n<p>Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet points for each specific method.</p>\n\n<p>Also the STL library reference at <a href=\"http://www.cplusplus.com/reference/stl/\" rel=\"noreferrer\">http://www.cplusplus.com/reference/stl/</a> provides the complexity requirements where appropriate.</p>\n" }, { "answer_id": 26395804, "author": "Nayana Adassuriya", "author_id": 1268258, "author_profile": "https://Stackoverflow.com/users/1268258", "pm_score": 8, "selected": true, "text": "<p>I found the nice resource <em><a href=\"http://www.cs.northwestern.edu/~riesbeck/programming/c++/stl-summary.html\" rel=\"noreferrer\">Standard C++ Containers</a></em>. Probably this is what you all looking for.</p>\n\n<p><strong>VECTOR</strong></p>\n\n<p><strong>Constructors</strong></p>\n\n<pre><code>vector&lt;T&gt; v; Make an empty vector. O(1)\nvector&lt;T&gt; v(n); Make a vector with N elements. O(n)\nvector&lt;T&gt; v(n, value); Make a vector with N elements, initialized to value. O(n)\nvector&lt;T&gt; v(begin, end); Make a vector and copy the elements from begin to end. O(n)\n</code></pre>\n\n<p><strong>Accessors</strong></p>\n\n<pre><code>v[i] Return (or set) the I'th element. O(1)\nv.at(i) Return (or set) the I'th element, with bounds checking. O(1)\nv.size() Return current number of elements. O(1)\nv.empty() Return true if vector is empty. O(1)\nv.begin() Return random access iterator to start. O(1)\nv.end() Return random access iterator to end. O(1)\nv.front() Return the first element. O(1)\nv.back() Return the last element. O(1)\nv.capacity() Return maximum number of elements. O(1)\n</code></pre>\n\n<p><strong>Modifiers</strong></p>\n\n<pre><code>v.push_back(value) Add value to end. O(1) (amortized)\nv.insert(iterator, value) Insert value at the position indexed by iterator. O(n)\nv.pop_back() Remove value from end. O(1)\nv.assign(begin, end) Clear the container and copy in the elements from begin to end. O(n)\nv.erase(iterator) Erase value indexed by iterator. O(n)\nv.erase(begin, end) Erase the elements from begin to end. O(n)\n</code></pre>\n\n<p>For other containers, refer to the page.</p>\n" }, { "answer_id": 61696562, "author": "iamakshatjain", "author_id": 8520377, "author_profile": "https://Stackoverflow.com/users/8520377", "pm_score": 1, "selected": false, "text": "<p>Another quick lookup table is available at this <a href=\"https://alyssaq.github.io/stl-complexities/\" rel=\"nofollow noreferrer\">github page</a></p>\n\n<p>Note : This does not consider all the containers such as, unordered_map etc. but is still great to look at. It is just a cleaner version of <a href=\"http://cs.northwestern.edu/~riesbeck/programming/c++/stl-summary.html\" rel=\"nofollow noreferrer\">this</a></p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14065/" ]
Apparently ;-) the standard containers provide some form of guarantees. What type of guarantees and what exactly are the differences between the different types of container? Working from [the SGI page](http://www.sgi.com/tech/stl/) (about [STL](http://en.wikipedia.org/wiki/Standard_Template_Library)) I have come up with this: ``` Container Types: ================ Container: Forward Container Reverse Container Random Access Container Sequence Front Insert Sequence Back Insert Sequence Associative Container Simple Associative Container Pair Associative Container Sorted Associative Container Multiple Associative Container Container Types mapped to Standard Containers ============================================= std::vector: Sequence Back Sequence Forward/Reverse/Random Container std::deque: Sequence Front/Back Sequence Forward/Reverse/Random Container std::list: Sequence Front/Back Sequence Forward/Reverse Container std::set: Sorted/Simple/Unique Associative Container Forward Container std::map: Sorted/Pair/Unique Associative Container Forward Container std::multiset: Sorted/Simple/Multiple Associative Container Forward Container std::multimap: Sorted/Pair/Multiple Associative Container Forward Container Container Guarantees: ===================== Simp or For Rev Rand Front Back Assoc Sort Mult Cont: Cont: Cont Cont: Sequ: Sequ: Sequ: Cont: Cont: Cont: Copy Const: O(n) Fill Const: O(n) begin() O(1) end() O(1) rbegin() O(1) rend() O(1) front() O(1) push_front() O(1) pop_front() O(1) push_back() O(1) pop_back() O(1) Insert() O(ln(n)) Insert: fill O(n) Insert: range O(n) O(kln(n)+n) size() O(1) swap() O(1) erase key O(ln(n)) erase element O(1) erase range O(ln(n)+S) count() O(log(n)+k) find() O(ln(n)) equal range O(ln(n)) Lower Bound/Upper Bound O(ln(n)) Equality O(n) InEquality O(n) Element Access O(1) ```
I found the nice resource *[Standard C++ Containers](http://www.cs.northwestern.edu/~riesbeck/programming/c++/stl-summary.html)*. Probably this is what you all looking for. **VECTOR** **Constructors** ``` vector<T> v; Make an empty vector. O(1) vector<T> v(n); Make a vector with N elements. O(n) vector<T> v(n, value); Make a vector with N elements, initialized to value. O(n) vector<T> v(begin, end); Make a vector and copy the elements from begin to end. O(n) ``` **Accessors** ``` v[i] Return (or set) the I'th element. O(1) v.at(i) Return (or set) the I'th element, with bounds checking. O(1) v.size() Return current number of elements. O(1) v.empty() Return true if vector is empty. O(1) v.begin() Return random access iterator to start. O(1) v.end() Return random access iterator to end. O(1) v.front() Return the first element. O(1) v.back() Return the last element. O(1) v.capacity() Return maximum number of elements. O(1) ``` **Modifiers** ``` v.push_back(value) Add value to end. O(1) (amortized) v.insert(iterator, value) Insert value at the position indexed by iterator. O(n) v.pop_back() Remove value from end. O(1) v.assign(begin, end) Clear the container and copy in the elements from begin to end. O(n) v.erase(iterator) Erase value indexed by iterator. O(n) v.erase(begin, end) Erase the elements from begin to end. O(n) ``` For other containers, refer to the page.
181,718
<p>When I add a breakpoint and hit F5 to run in the debugger (I am using my debug build), a dialog pops up telling my my web.config file does not have debug=true in it (which is does) and I get 2 choices a) run without the debugger or b) let visual studio update my web.config file. If I choose b) the web.config is updated badly and nothing will work. If I choose a) then the site appears and I can test it out, but no debugging.</p> <p>I am an experienced developer, but I have never used visual studio and asp.net for web development before, so I am feeling rather frustrated by all the walls it is putting up to prevent me working.</p> <p>So far I have not been able to use the debugger. Is there something totally obvious that I am missing? What would you check if it was happening to you?</p>
[ { "answer_id": 181736, "author": "liggett78", "author_id": 19762, "author_profile": "https://Stackoverflow.com/users/19762", "pm_score": 3, "selected": true, "text": "<p>Open web.config manually and make sure the following line is in there</p>\n\n<pre><code>&lt;compilation defaultLanguage=\"c#\" debug=\"true\" /&gt;\n</code></pre>\n\n<p>Now you should be able to debug from VS. If this does not work I suggest that you recreate the project.</p>\n\n<p>EDIT: perhaps from what you say it could be that web.config is screwed up, e.g.contains invalid xml, no closing tag for some element etc.</p>\n" }, { "answer_id": 181748, "author": "Larry", "author_id": 24472, "author_profile": "https://Stackoverflow.com/users/24472", "pm_score": 1, "selected": false, "text": "<p>ligget78 said it first ^^</p>\n\n<p>Try to delete completely web.config and let Visual Studio recreate it, if possible.</p>\n" }, { "answer_id": 181751, "author": "massimogentilini", "author_id": 11673, "author_profile": "https://Stackoverflow.com/users/11673", "pm_score": 0, "selected": false, "text": "<p>If the debug=true is enabled then there is some problem in the Internet Application Server application. Try re-creating the web application and let Visual Studio create the web site.</p>\n\n<p>Check also that the cassini web server is set up to be used as the debugging web server in the project properties.</p>\n" }, { "answer_id": 181755, "author": "naspinski", "author_id": 14777, "author_profile": "https://Stackoverflow.com/users/14777", "pm_score": 1, "selected": false, "text": "<p>I agree with what was posted above, but another thing you can check is to, make sure that your page header in your aspx files does not disable debugging:</p>\n\n<pre><code>&lt;%@ Page Language=\"C#\" MasterPageFile=\"~/default.master\" AutoEventWireup=\"true\" CodeFile=\"Default.aspx.cs\" Inherits=\"_Default\" Title=\"some title\" Debug=\"false\" %&gt;\n</code></pre>\n\n<p>^^ that will turn off debugging.</p>\n" }, { "answer_id": 182595, "author": "osp70", "author_id": 2357, "author_profile": "https://Stackoverflow.com/users/2357", "pm_score": 1, "selected": false, "text": "<p>In your project do a solution wide search for 'debug=' and if only one shows up then do a folder search. I've had it happen where there are multiple config files and this can cause problems.</p>\n" }, { "answer_id": 41760419, "author": "quinekxi", "author_id": 956702, "author_profile": "https://Stackoverflow.com/users/956702", "pm_score": 0, "selected": false, "text": "<p>This might be a dumb answer but it might also help.</p>\n\n<p>I also encountered this problem on my setup. Though debug is already set to true, when F5 is hit, it won't still stop where the breakpoint is at.</p>\n\n<p>I've solved it by chance when I close all the open IE then hit F5 again and that's how it work. (in my case, I placed the breakpoint at page_load for verification if it does stop at breakpoint).</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4012/" ]
When I add a breakpoint and hit F5 to run in the debugger (I am using my debug build), a dialog pops up telling my my web.config file does not have debug=true in it (which is does) and I get 2 choices a) run without the debugger or b) let visual studio update my web.config file. If I choose b) the web.config is updated badly and nothing will work. If I choose a) then the site appears and I can test it out, but no debugging. I am an experienced developer, but I have never used visual studio and asp.net for web development before, so I am feeling rather frustrated by all the walls it is putting up to prevent me working. So far I have not been able to use the debugger. Is there something totally obvious that I am missing? What would you check if it was happening to you?
Open web.config manually and make sure the following line is in there ``` <compilation defaultLanguage="c#" debug="true" /> ``` Now you should be able to debug from VS. If this does not work I suggest that you recreate the project. EDIT: perhaps from what you say it could be that web.config is screwed up, e.g.contains invalid xml, no closing tag for some element etc.
181,719
<p>How do I start a process, such as launching a URL when the user clicks a button?</p>
[ { "answer_id": 181727, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 5, "selected": false, "text": "<p>You can use the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx\" rel=\"noreferrer\">System.Diagnostics.Process.Start</a> method to start a process. You can even pass a URL as a string and it'll kick off the default browser.</p>\n" }, { "answer_id": 181728, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 3, "selected": false, "text": "<p>Use the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process(VS.80).aspx\" rel=\"noreferrer\">Process</a> class. The MSDN documentation has an example how to use it.</p>\n" }, { "answer_id": 181821, "author": "GvS", "author_id": 11492, "author_profile": "https://Stackoverflow.com/users/11492", "pm_score": 4, "selected": false, "text": "<p>Just as Matt says, use <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx\" rel=\"noreferrer\">Process.Start</a>.</p>\n\n<p>You can pass a URL, or a document. They will be started by the registered application.</p>\n\n<p>Example:</p>\n\n<pre><code>Process.Start(\"Test.Txt\");\n</code></pre>\n\n<p>This will start Notepad.exe with Text.Txt loaded.</p>\n" }, { "answer_id": 181857, "author": "Andy McCluggage", "author_id": 3362, "author_profile": "https://Stackoverflow.com/users/3362", "pm_score": 8, "selected": false, "text": "<p>As suggested by Matt Hamilton, the quick approach where you have limited control over the process, is to use the static Start method on the System.Diagnostics.Process class...</p>\n\n<pre><code>using System.Diagnostics;\n...\nProcess.Start(\"process.exe\");\n</code></pre>\n\n<p>The alternative is to use an instance of the Process class. This allows much more control over the process including scheduling, the type of the window it will run in and, most usefully for me, the ability to wait for the process to finish.</p>\n\n<pre><code>using System.Diagnostics;\n...\nProcess process = new Process();\n// Configure the process using the StartInfo properties.\nprocess.StartInfo.FileName = \"process.exe\";\nprocess.StartInfo.Arguments = \"-n\";\nprocess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;\nprocess.Start();\nprocess.WaitForExit();// Waits here for the process to exit.\n</code></pre>\n\n<p>This method allows far more control than I've mentioned.</p>\n" }, { "answer_id": 24823340, "author": "Blackvault", "author_id": 3602240, "author_profile": "https://Stackoverflow.com/users/3602240", "pm_score": 4, "selected": false, "text": "<p>I used the following in my own program. </p>\n\n<pre><code>Process.Start(\"http://www.google.com/etc/etc/test.txt\")\n</code></pre>\n\n<p>It's a bit basic, but it does the job for me.</p>\n" }, { "answer_id": 26772447, "author": "AVIK DUTTA", "author_id": 4137130, "author_profile": "https://Stackoverflow.com/users/4137130", "pm_score": 2, "selected": false, "text": "<p>Include the <code>using System.Diagnostics;</code>.</p>\n\n<p>And then call this <code>Process.Start(\"Paste your URL string here!\");</code></p>\n\n<p>Try something like this:</p>\n\n<pre><code>using System.Web.UI;\nusing System.Web.UI.WebControls;\nusing System.Diagnostics;\n\nnamespace btnproce\n{\n public partial class WebForm1 : System.Web.UI.Page\n {\n protected void Page_Load(object sender, EventArgs e)\n {\n\n }\n\n protected void Button1_Click(object sender, EventArgs e)\n {\n string t =\"Balotelli\";\n Process.Start(\"http://google.com/search?q=\" + t);\n }\n }\n}\n</code></pre>\n\n<p>Please note that it is a sample ASP.NET page as an example. You should try and improvise a little bit.</p>\n" }, { "answer_id": 29357273, "author": "SimperT", "author_id": 4367485, "author_profile": "https://Stackoverflow.com/users/4367485", "pm_score": 3, "selected": false, "text": "<pre><code>var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"/YourSubDirectory/yourprogram.exe\");\nProcess.Start(new ProcessStartInfo(path));\n</code></pre>\n" }, { "answer_id": 31140674, "author": "alireza amini", "author_id": 3970128, "author_profile": "https://Stackoverflow.com/users/3970128", "pm_score": 3, "selected": false, "text": "<p>You can use this syntax for running any application:</p>\n\n<pre><code>System.Diagnostics.Process.Start(\"Example.exe\");\n</code></pre>\n\n<p>And the same one for a URL. Just write your URL between this <code>()</code>.</p>\n\n<p>Example:</p>\n\n<pre><code>System.Diagnostics.Process.Start(\"http://www.google.com\");\n</code></pre>\n" }, { "answer_id": 31994088, "author": "Carla Jesus", "author_id": 5087231, "author_profile": "https://Stackoverflow.com/users/5087231", "pm_score": 2, "selected": false, "text": "<p>Declare this</p>\n\n<pre><code>[DllImport(\"user32\")]\nprivate static extern bool SetForegroundWindow(IntPtr hwnd);\n[DllImport(\"user32\")]\nprivate static extern bool ShowWindowAsync(IntPtr hwnd, int a);\n</code></pre>\n\n<p>And put this inside your function (note that \"checkInstalled\" is optional, but if you'll use it, you have to implement it)</p>\n\n<pre><code>if (ckeckInstalled(\"example\"))\n{\n int count = Process.GetProcessesByName(\"example\").Count();\n if (count &lt; 1)\n Process.Start(\"example.exe\");\n else\n {\n var proc = Process.GetProcessesByName(\"example\").FirstOrDefault();\n if (proc != null &amp;&amp; proc.MainWindowHandle != IntPtr.Zero)\n {\n SetForegroundWindow(proc.MainWindowHandle);\n ShowWindowAsync(proc.MainWindowHandle, 3);\n }\n }\n}\n</code></pre>\n\n<p><strong>NOTE:</strong> I'm not sure if this works when more than one instance of the .exe is running.</p>\n" }, { "answer_id": 37459732, "author": "Ravi Kumar G N", "author_id": 5680680, "author_profile": "https://Stackoverflow.com/users/5680680", "pm_score": 3, "selected": false, "text": "<pre><code>class ProcessStart\n{\n static void Main(string[] args)\n {\n Process notePad = new Process();\n\n notePad.StartInfo.FileName = \"notepad.exe\";\n notePad.StartInfo.Arguments = \"ProcessStart.cs\";\n\n notePad.Start();\n }\n}\n</code></pre>\n" }, { "answer_id": 39277571, "author": "user4340666", "author_id": 4340666, "author_profile": "https://Stackoverflow.com/users/4340666", "pm_score": 2, "selected": false, "text": "<p>To start <a href=\"https://en.wikipedia.org/wiki/Microsoft_Word\" rel=\"nofollow noreferrer\">Microsoft Word</a> for example, use this code:</p>\n\n<pre><code>private void button1_Click(object sender, EventArgs e)\n{\n string ProgramName = \"winword.exe\";\n Process.Start(ProgramName);\n}\n</code></pre>\n\n<p>For more explanations, check out <a href=\"http://www.csharp-tutorials1.blogspot.com/2016/08/how-to-start-process-or-program-in-c.html\" rel=\"nofollow noreferrer\">this link</a>.</p>\n" }, { "answer_id": 62896522, "author": "Moon Waxing", "author_id": 2234635, "author_profile": "https://Stackoverflow.com/users/2234635", "pm_score": 2, "selected": false, "text": "<p>If using on Windows</p>\n<pre><code>Process process = new Process();\nprocess.StartInfo.FileName = &quot;Test.txt&quot;;\nprocess.Start();\n</code></pre>\n<p>Works for .Net Framework but for Net core 3.1 also need to set UseShellExecute to true</p>\n<pre><code>Process process = new Process();\nprocess.StartInfo.FileName = &quot;Test.txt&quot;;\nprocess.StartInfo.UseShellExecute = true;\nprocess.Start();\n</code></pre>\n" }, { "answer_id": 66843763, "author": "NoNAME", "author_id": 14935884, "author_profile": "https://Stackoverflow.com/users/14935884", "pm_score": 0, "selected": false, "text": "<p>You can use this syntax:</p>\n<pre><code>private void button1_Click(object sender, EventArgs e) {\n System.Diagnostics.Process.Start(/*your file name goes here*/);\n}\n</code></pre>\n<p>Or even this:</p>\n<pre><code>using System;\nusing System.Diagnostics;\n//rest of the code\n\nprivate void button1_Click(object sender, EventArgs e) {\n Process.Start(/*your file name goes here*/);\n}\n</code></pre>\n<p>Both methods would perform the same task.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I start a process, such as launching a URL when the user clicks a button?
As suggested by Matt Hamilton, the quick approach where you have limited control over the process, is to use the static Start method on the System.Diagnostics.Process class... ``` using System.Diagnostics; ... Process.Start("process.exe"); ``` The alternative is to use an instance of the Process class. This allows much more control over the process including scheduling, the type of the window it will run in and, most usefully for me, the ability to wait for the process to finish. ``` using System.Diagnostics; ... Process process = new Process(); // Configure the process using the StartInfo properties. process.StartInfo.FileName = "process.exe"; process.StartInfo.Arguments = "-n"; process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized; process.Start(); process.WaitForExit();// Waits here for the process to exit. ``` This method allows far more control than I've mentioned.
181,745
<p>Often when making changes to a VS2008 ASP.net project we get a message like:</p> <p>BC30560: 'mymodule_ascx' is ambiguous in the namespace 'ASP'.</p> <p>This goes away after a recompile or sometimes just waiting 10 seconds and refreshing the page. </p> <p>Any way to get rid of it?</p>
[ { "answer_id": 300955, "author": "Nathan", "author_id": 24954, "author_profile": "https://Stackoverflow.com/users/24954", "pm_score": 1, "selected": false, "text": "<p>I used to have this problem sometimes too. If I remember correctly it was caused by something like the following:</p>\n\n<pre><code>&lt;%@ Page Inherits=\"_Default\" %&gt;\n</code></pre>\n\n<p>or perhaps </p>\n\n<pre><code>&lt;%@ Page ClassName=\"_Default\" %&gt;\n</code></pre>\n\n<p>Or something like that. I'm not 100% sure which attribute it was (it's been a while).</p>\n\n<p>But look look for something like _Default in your Page directive and replace them with actual class names in all of your files. For some reason, ASP.Net doesn't always interpret the _Default correctly, yielding temporary ambiguous references.</p>\n" }, { "answer_id": 300972, "author": "Nathan", "author_id": 24954, "author_profile": "https://Stackoverflow.com/users/24954", "pm_score": 3, "selected": true, "text": "<p>Another possibility:</p>\n\n<p><a href=\"http://channel9.msdn.com/forums/TechOff/157050-BC30560-mycontrolascx-is-ambiguous-in-the-namespace-ASP/\" rel=\"nofollow noreferrer\">http://channel9.msdn.com/forums/TechOff/157050-BC30560-mycontrolascx-is-ambiguous-in-the-namespace-ASP/</a></p>\n\n<p>Seemed to have some success with changing</p>\n\n<pre><code>src=\"mycontrol.ascx.cs\"\n</code></pre>\n\n<p>to</p>\n\n<pre><code>CodeBehind=\"mycontrol.ascx.cs\"\n</code></pre>\n" }, { "answer_id": 301017, "author": "Pat Hermens", "author_id": 1677, "author_profile": "https://Stackoverflow.com/users/1677", "pm_score": 1, "selected": false, "text": "<p>Similar to the two previous answers, you'll most probably have a \"copy and pasted\" copy of an existing page in the same site, and this will then contain the same @Page directives which will lead to a clashing of functions (especially because everything in .Net defaults to Partial Classes.) This little gem has bitten me all-too-often.</p>\n\n<p>Just update the \"Inherits\" to point to something specific to your page (i.e.: your page name prefixed by an underscore -- as it's more-often-than-not guaranteed to be unique), and ensured that you haven't got two Public Partial Classes named the same in different code-behind files (otherwise Page_Load in _Default [default.aspx], will clash with Page_Load in _Default [copy of default.aspx])</p>\n" }, { "answer_id": 1262428, "author": "proudgeekdad", "author_id": 702, "author_profile": "https://Stackoverflow.com/users/702", "pm_score": 4, "selected": false, "text": "<p>I just solved this problem with the assistance following link: \n<a href=\"http://www.netomatix.com/development/usercontrols2.aspx\" rel=\"noreferrer\">http://www.netomatix.com/development/usercontrols2.aspx</a></p>\n\n<p>In a nutshell, your class is called MyModule. However, if you do not specify the ClassName property in the @Control directive, the compiler may append _ascx to the control's class, which results in MyModule_ascx. Since the page can't find MyModule_ascx, it blows up in your face. You need to explicitly tell it the ClassName...</p>\n\n<pre><code>&lt;%@ Control Language=\"vb\" AutoEventWireup=\"false\" CodeBehind=\"MyModule.ascx.vb\" ClassName=\"MyModule\" %&gt;\n</code></pre>\n" }, { "answer_id": 1502527, "author": "mrrrk", "author_id": 155791, "author_profile": "https://Stackoverflow.com/users/155791", "pm_score": 2, "selected": false, "text": "<p>I've just suffered this. Stuff that worked fine and was untouched for months started randomly failing after some unrelated updates. I'd recompile and the problem would disappear only to reappear somewhere else. </p>\n\n<p>I seem to have resolved it by clearing out the ASP.NET temporary folder, e.g. C:\\Windows\\Microsoft.NET\\Framework\\v2.0.xxxxx\\Temporary ASP.NET Files. This required an IIS restart to really clean it out.</p>\n\n<p><strong>Update:</strong> I tried adding <code>tempDirectory=\"e:\\someotherfolder\"</code> to the <code>compilation</code> element of the web.config and that seems to have had some success. Also added <code>batch=\"false\"</code> but not sure if that's had an effect.</p>\n" }, { "answer_id": 9101512, "author": "jam40jeff", "author_id": 1183492, "author_profile": "https://Stackoverflow.com/users/1183492", "pm_score": 5, "selected": false, "text": "<p>I recently came across this problem and it was only happening on one server even though all were running the same code. I thoroughly investigated the problem to make sure there were no user controls with clashing names, temp files were cleared out, etc.</p>\n<p>The only thing that solved the problems (it seems permanently) is changing the batch attribute of the compilation element to false in the web.config, as suggested in the following link:</p>\n<p><a href=\"http://personalinertia.blogspot.com/2007/06/there-bug-in-compiler.html\" rel=\"nofollow noreferrer\">http://personalinertia.blogspot.com/2007/06/there-bug-in-compiler.html</a></p>\n<pre><code>&lt;compilation debug=&quot;true&quot; batch=&quot;false&quot;&gt;\n</code></pre>\n<p>I firmly believe that this is in fact a bug in the compiler as suggested on that site.</p>\n" }, { "answer_id": 32122914, "author": "CaffeineDrivenDevelopment", "author_id": 342029, "author_profile": "https://Stackoverflow.com/users/342029", "pm_score": 0, "selected": false, "text": "<p>Also ran into this with MasterPages on projects that were originally .net 1.1 and 2.0 projects and later converted. In both cases, the @MasterType directive referenced the virtualpath. I changed to &lt;%@ MasterType TypeName=\"MasterPages_MasterPage\" %>, cleaned the solution and the problem went away. HTH</p>\n" }, { "answer_id": 42792928, "author": "Shwan", "author_id": 3148419, "author_profile": "https://Stackoverflow.com/users/3148419", "pm_score": 1, "selected": false, "text": "<p>Try to change web.config, set batch to false </p>\n\n<pre><code>&lt;compilation batch=\"false\"&gt;\n&lt;/compilation&gt;\n</code></pre>\n" }, { "answer_id": 44574981, "author": "ajeh", "author_id": 2721750, "author_profile": "https://Stackoverflow.com/users/2721750", "pm_score": 1, "selected": false, "text": "<p>For me this error was a red herring. In reality one of the user controls had errors caused by .NET 2.,0 to 4.5 migration, which had to be fixed in the code, but VS threw this misleading error messages. After multiple attempts to upgrade the projects it finally started erroring on the actual lines of code, but I don't know how to reproduce this after hours of frustration and fruitless attempts to apply solutions from all over the Internet.</p>\n" }, { "answer_id": 65418187, "author": "GreenRock", "author_id": 4683257, "author_profile": "https://Stackoverflow.com/users/4683257", "pm_score": 0, "selected": false, "text": "<p>Rebuild Solution worked for me.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23066/" ]
Often when making changes to a VS2008 ASP.net project we get a message like: BC30560: 'mymodule\_ascx' is ambiguous in the namespace 'ASP'. This goes away after a recompile or sometimes just waiting 10 seconds and refreshing the page. Any way to get rid of it?
Another possibility: <http://channel9.msdn.com/forums/TechOff/157050-BC30560-mycontrolascx-is-ambiguous-in-the-namespace-ASP/> Seemed to have some success with changing ``` src="mycontrol.ascx.cs" ``` to ``` CodeBehind="mycontrol.ascx.cs" ```
181,775
<p>Not sure what exactly is going on here, but seems like in .NET 1.1 an uninitialized event delegate can run without issues, but in .NET 2.0+ it causes a NullReferenceException. Any ideas why. The code below will run fine without issues in 1.1, in 2.0 it gives a NullReferenceException. I'm curious why does it behave differently? What changed?</p> <p>Thanks</p> <p>eg</p> <pre><code>class Class1 { public delegate void ChartJoinedRowAddedHandler(object sender); public static event ChartJoinedRowAddedHandler ChartJoinedRowAdded; public static DataTable dt; public static void Main() { dt = new DataTable(); dt.RowChanged += new DataRowChangeEventHandler(TableEventHandler); object [] obj = new object[]{1,2}; dt.Columns.Add("Name"); dt.Columns.Add("Last"); dt.NewRow(); dt.Rows.Add(obj); } private static void TableEventHandler(object sender, DataRowChangeEventArgs e) { ChartJoinedRowAdded(new object()); } } </code></pre>
[ { "answer_id": 181790, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": true, "text": "<p>[updated] AFAIK, there was no change here to the fundamental delegate handling; the difference is in how DataTable behaves.</p>\n\n<p>However! Be very careful using static events, especially if you are subscribing from instances (rather than static methods). This is a good way to keep huge swathes of objects alive and not be garbage collected.</p>\n\n<p>Running the code via csc from 1.1 shows that the general delegate side is the same - I think the difference is that the DataTable code that raises RowChanged was swallowing the exception. For example, make the code like below:</p>\n\n<pre><code> Console.WriteLine(\"Before\");\n ChartJoinedRowAdded(new object());\n Console.WriteLine(\"After\");\n</code></pre>\n\n<p>You'll see \"Before\", but no \"After\"; an exception was thrown and swallowed by the DataTable.</p>\n" }, { "answer_id": 181826, "author": "Soraz", "author_id": 24610, "author_profile": "https://Stackoverflow.com/users/24610", "pm_score": 1, "selected": false, "text": "<p>The eventhandler system is basically just a list of functions to call when a given event is raised.</p>\n\n<p>It initializes to the \"null\" list, and not the empty list, so you need to do </p>\n\n<pre><code>if (ChartJoinedRowAdded != null)\n ChartJoinedRowAdded(new object())\n</code></pre>\n" }, { "answer_id": 181984, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 0, "selected": false, "text": "<p>The way events work hasn't really changed from 1.1 to 2</p>\n\n<p>Although the syntax looks like normal aggregation it really isn't:</p>\n\n<pre><code>dt.RowChanged += TableEventHandler;\ndt.RowChanged += null;\ndt.RowChanged += delegate (object sender, DataRowChangeEventArgs e) {\n //anon\n};\n</code></pre>\n\n<p>Will fire <code>TableEventHandler</code> and then the delegate - the null is just skipped.</p>\n\n<p>You can use null to clear events, but only inside the event firing class:</p>\n\n<pre><code>this.MyEvent = null;\n</code></pre>\n\n<p>If nothing subscribes your event will be null - see soraz's answer. The <code>DataTable</code> class will contain a similar check and won't fire the event if there are no subscribers.</p>\n\n<p>The standard pattern is:</p>\n\n<pre><code>//events should just about always use this pattern: object, args\npublic static event EventHandler&lt;MyEventArgs&gt; ChartJoinedRowAdded;\n\n\n//inheriting classes can override this event behaviour\nprotected virtual OnChartJoinedRowAdded() {\n if( ChartJoinedRowAdded != null )\n ChartJoinedRowAdded( this, new MyEventArgs(...) );\n}\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26050/" ]
Not sure what exactly is going on here, but seems like in .NET 1.1 an uninitialized event delegate can run without issues, but in .NET 2.0+ it causes a NullReferenceException. Any ideas why. The code below will run fine without issues in 1.1, in 2.0 it gives a NullReferenceException. I'm curious why does it behave differently? What changed? Thanks eg ``` class Class1 { public delegate void ChartJoinedRowAddedHandler(object sender); public static event ChartJoinedRowAddedHandler ChartJoinedRowAdded; public static DataTable dt; public static void Main() { dt = new DataTable(); dt.RowChanged += new DataRowChangeEventHandler(TableEventHandler); object [] obj = new object[]{1,2}; dt.Columns.Add("Name"); dt.Columns.Add("Last"); dt.NewRow(); dt.Rows.Add(obj); } private static void TableEventHandler(object sender, DataRowChangeEventArgs e) { ChartJoinedRowAdded(new object()); } } ```
[updated] AFAIK, there was no change here to the fundamental delegate handling; the difference is in how DataTable behaves. However! Be very careful using static events, especially if you are subscribing from instances (rather than static methods). This is a good way to keep huge swathes of objects alive and not be garbage collected. Running the code via csc from 1.1 shows that the general delegate side is the same - I think the difference is that the DataTable code that raises RowChanged was swallowing the exception. For example, make the code like below: ``` Console.WriteLine("Before"); ChartJoinedRowAdded(new object()); Console.WriteLine("After"); ``` You'll see "Before", but no "After"; an exception was thrown and swallowed by the DataTable.
181,780
<p>I have an app where I would like to support device rotation in certain views but other don't particularly make sense in Landscape mode, so as I swapping the views out I would like to force the rotation to be set to portrait.</p> <p>There is an undocumented property setter on UIDevice that does the trick but obviously generates a compiler warning and could disappear with a future revision of the SDK.</p> <pre><code>[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationPortrait]; </code></pre> <p>Are there any documented ways to force the orientation?</p> <p><strong>Update:</strong> I thought I would provide an example as I am not looking for shouldAutorotateToInterfaceOrientation as I have already implemented that.</p> <p>I want my app to support landscape and portrait in View 1 but only portrait in View 2. I have already implemented shouldAutorotateToInterfaceOrientation for all views but if the user is in landscape mode in View 1 and then switches to View 2, I want to force the phone to rotate back to Portrait.</p>
[ { "answer_id": 183348, "author": "Martin Gordon", "author_id": 2481, "author_profile": "https://Stackoverflow.com/users/2481", "pm_score": -1, "selected": false, "text": "<p>If you are using UIViewControllers, there is this method:</p>\n\n<pre><code>- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation\n</code></pre>\n\n<p>Return <code>NO</code> for the view controllers containing the views you don't want to rotate.</p>\n\n<p><a href=\"http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instm/UIViewController/shouldAutorotateToInterfaceOrientation:\" rel=\"nofollow noreferrer\">More info here</a></p>\n" }, { "answer_id": 184631, "author": "Andrew Grant", "author_id": 1043, "author_profile": "https://Stackoverflow.com/users/1043", "pm_score": -1, "selected": false, "text": "<p>I don't think this is possible to do at run-time, though you could of course just apply a 90 degree transform to your UI.</p>\n" }, { "answer_id": 190359, "author": "kdbdallas", "author_id": 26728, "author_profile": "https://Stackoverflow.com/users/26728", "pm_score": -1, "selected": false, "text": "<p>This is what I use. (You get some compile warnings but it works in both the Simulator and the iPhone)</p>\n\n<pre><code>[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight];\n[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];\n</code></pre>\n" }, { "answer_id": 464053, "author": "Bdebeez", "author_id": 35516, "author_profile": "https://Stackoverflow.com/users/35516", "pm_score": 4, "selected": false, "text": "<p>From what I can tell, the <code>setOrientation:</code> method doesn't work (or perhaps works no longer). Here's what I'm doing to do this:</p>\n\n<p>first, put this define at the top of your file, right under your #imports:</p>\n\n<pre><code>#define degreesToRadian(x) (M_PI * (x) / 180.0)\n</code></pre>\n\n<p>then, in the <code>viewWillAppear:</code> method</p>\n\n<pre><code>[[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO]; \nif (self.interfaceOrientation == UIInterfaceOrientationPortrait) { \n self.view.transform = CGAffineTransformIdentity;\n self.view.transform = CGAffineTransformMakeRotation(degreesToRadian(90));\n self.view.bounds = CGRectMake(0.0, 0.0, 480, 320);\n}\n</code></pre>\n\n<p>if you want that to be animated, then you can wrap the whole thing in an animation block, like so:</p>\n\n<pre><code>[UIView beginAnimations:@\"View Flip\" context:nil];\n[UIView setAnimationDuration:1.25];\n[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];\n\n[[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO]; \nif (self.interfaceOrientation == UIInterfaceOrientationPortrait) { \n self.view.transform = CGAffineTransformIdentity;\n self.view.transform = CGAffineTransformMakeRotation(degreesToRadian(90));\n self.view.bounds = CGRectMake(0.0, 0.0, 480, 320);\n}\n[UIView commitAnimations];\n</code></pre>\n\n<p>Then, in your portrait mode controller, you can do the reverse - check to see if its currently in landscape, and if so, rotate it back to Portrait.</p>\n" }, { "answer_id": 793285, "author": "Michael Gaylord", "author_id": 84290, "author_profile": "https://Stackoverflow.com/users/84290", "pm_score": 4, "selected": false, "text": "<p>If you want to force it to rotate from portrait to landscape here is the code. Just note that you need adjust the center of your view. I noticed that mine didn't place the view in the right place. Otherwise, it worked perfectly. Thanks for the tip.</p>\n\n<pre><code>if(UIInterfaceOrientationIsLandscape(self.interfaceOrientation)){\n\n [UIView beginAnimations:@\"View Flip\" context:nil];\n [UIView setAnimationDuration:0.5f];\n [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];\n\n self.view.transform = CGAffineTransformIdentity;\n self.view.transform = CGAffineTransformMakeRotation(degreesToRadian(90));\n self.view.bounds = CGRectMake(0.0f, 0.0f, 480.0f, 320.0f);\n self.view.center = CGPointMake(160.0f, 240.0f);\n\n [UIView commitAnimations];\n}\n</code></pre>\n" }, { "answer_id": 1850462, "author": "John K", "author_id": 224434, "author_profile": "https://Stackoverflow.com/users/224434", "pm_score": 4, "selected": true, "text": "<p>This is no longer an issue on the later iPhone 3.1.2 SDK. It now appears to honor the requested orientation of the view being pushed back onto the stack. That likely means that you would need to detect older iPhone OS versions and only apply the setOrientation when it is prior to the latest release.</p>\n\n<p>It is not clear if Apple's static analysis will understand that you are working around the older SDK limitations. I personally have been told by Apple to remove the method call on my next update so I am not yet sure if having a hack for older devices will get through the approval process.</p>\n" }, { "answer_id": 3526379, "author": "Andrew Vilcsak", "author_id": 418817, "author_profile": "https://Stackoverflow.com/users/418817", "pm_score": 3, "selected": false, "text": "<p>I was having an issue where I had a <code>UIViewController</code> on the screen, in a <code>UINavigationController</code>, in landscape orientation. When the next view controller is pushed in the flow, however, I needed the device to return to portrait orientation.</p>\n\n<p>What I noticed, was that the <code>shouldAutorotateToInterfaceOrientation:</code> method isn't called when a new view controller is pushed onto the stack, but <strong>it is called when a view controller is popped from the stack</strong>.</p>\n\n<p>Taking advantage of this, I am using this snippet of code in one of my apps:</p>\n\n<pre><code>- (void)selectHostingAtIndex:(int)hostingIndex {\n\n self.transitioning = YES;\n\n UIViewController *garbageController = [[[UIViewController alloc] init] autorelease];\n [self.navigationController pushViewController:garbageController animated:NO];\n [self.navigationController popViewControllerAnimated:NO];\n\n BBHostingController *hostingController = [[BBHostingController alloc] init];\n hostingController.hosting = [self.hostings objectAtIndex:hostingIndex];\n [self.navigationController pushViewController:hostingController animated:YES];\n [hostingController release];\n\n self.transitioning = NO;\n}\n\n- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {\n if (self.transitioning)\n return (toInterfaceOrientation == UIInterfaceOrientationPortrait);\n else\n return YES;\n}\n</code></pre>\n\n<p>Basically, by creating an empty view controller, pushing it onto the stack, and immediately popping it off, it's possible to get the interface to revert to the portrait position. Once the controller has been popped, I just push on the controller that I intended to push in the first place. Visually, it looks great - the empty, arbitrary view controller is never seen by the user.</p>\n" }, { "answer_id": 3685397, "author": "Vinzius", "author_id": 243465, "author_profile": "https://Stackoverflow.com/users/243465", "pm_score": 0, "selected": false, "text": "<p>I found a solution and wrote something in french (but code are in english). <a href=\"http://www.geckogeek.fr/iphone-forcer-le-mode-landscape-ou-portrait-en-cours-dexecution.html\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>The way is to add the controller to the window view (the controller must possess a good implementation of the shouldRotate.... function).</p>\n" }, { "answer_id": 4035140, "author": "Rafael Nobre", "author_id": 338514, "author_profile": "https://Stackoverflow.com/users/338514", "pm_score": 3, "selected": false, "text": "<p>I've been digging and digging looking for a good solution to this. Found this blog post that does the trick: remove your outermost view from the key <code>UIWindow</code> and add it again, the system will then re-query the <code>shouldAutorotateToInterfaceOrientation:</code> methods from your viewcontrollers, enforcing the correct orientation to be applied.\nSee it : <a href=\"http://goodliffe.blogspot.com/2009/12/iphone-forcing-uiview-to-reorientate.html\" rel=\"nofollow noreferrer\">iphone forcing uiview to reorientate</a></p>\n" }, { "answer_id": 4374179, "author": "Henry Cooke", "author_id": 284475, "author_profile": "https://Stackoverflow.com/users/284475", "pm_score": 2, "selected": false, "text": "<p>FWIW, here's my implementation of manually setting orientation (to go in your app's root view controller, natch): </p>\n\n<pre><code>-(void)rotateInterfaceToOrientation:(UIDeviceOrientation)orientation{\n\n CGRect bounds = [[ UIScreen mainScreen ] bounds ];\n CGAffineTransform t;\n CGFloat r = 0;\n switch ( orientation ) {\n case UIDeviceOrientationLandscapeRight:\n r = -(M_PI / 2);\n break;\n case UIDeviceOrientationLandscapeLeft:\n r = M_PI / 2;\n break;\n }\n if( r != 0 ){\n CGSize sz = bounds.size;\n bounds.size.width = sz.height;\n bounds.size.height = sz.width;\n }\n t = CGAffineTransformMakeRotation( r );\n\n UIApplication *application = [ UIApplication sharedApplication ];\n\n [ UIView beginAnimations:@\"InterfaceOrientation\" context: nil ];\n [ UIView setAnimationDuration: [ application statusBarOrientationAnimationDuration ] ];\n self.view.transform = t;\n self.view.bounds = bounds;\n [ UIView commitAnimations ];\n\n [ application setStatusBarOrientation: orientation animated: YES ]; \n}\n</code></pre>\n\n<p>coupled with the following <code>UINavigationControllerDelegate</code> method (assuming you're using a <code>UINavigationController</code>):</p>\n\n<pre><code>-(void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{\n // rotate interface, if we need to\n UIDeviceOrientation orientation = [[ UIDevice currentDevice ] orientation ];\n BOOL bViewControllerDoesSupportCurrentOrientation = [ viewController shouldAutorotateToInterfaceOrientation: orientation ];\n if( !bViewControllerDoesSupportCurrentOrientation ){\n [ self rotateInterfaceToOrientation: UIDeviceOrientationPortrait ];\n }\n}\n</code></pre>\n\n<p>That takes care of rotating the root view according to whether an incoming <code>UIViewController</code> supports the current device orientation. Finally, you'll want to hook up <code>rotateInterfaceToOrientation</code> to actual device orientation changes in order to mimic standard iOS functionality. Add this event handler to the same root view controller:</p>\n\n<pre><code>-(void)onUIDeviceOrientationDidChangeNotification:(NSNotification*)notification{\n UIViewController *tvc = self.rootNavigationController.topViewController;\n UIDeviceOrientation orientation = [[ UIDevice currentDevice ] orientation ];\n // only switch if we need to (seem to get multiple notifications on device)\n if( orientation != [[ UIApplication sharedApplication ] statusBarOrientation ] ){\n if( [ tvc shouldAutorotateToInterfaceOrientation: orientation ] ){\n [ self rotateInterfaceToOrientation: orientation ];\n }\n }\n}\n</code></pre>\n\n<p>Finally, register for <code>UIDeviceOrientationDidChangeNotification</code> notifications in <code>init</code> or <code>loadview</code> like so:</p>\n\n<pre><code>[[ NSNotificationCenter defaultCenter ] addObserver: self\n selector: @selector(onUIDeviceOrientationDidChangeNotification:)\n name: UIDeviceOrientationDidChangeNotification\n object: nil ];\n[[ UIDevice currentDevice ] beginGeneratingDeviceOrientationNotifications ];\n</code></pre>\n" }, { "answer_id": 4915378, "author": "Josh", "author_id": 605558, "author_profile": "https://Stackoverflow.com/users/605558", "pm_score": 7, "selected": false, "text": "<p>This is long after the fact, but just in case anybody comes along who isn't using a navigation controller and/or doesn't wish to use undocumented methods:</p>\n\n<pre><code>UIViewController *c = [[UIViewController alloc]init];\n[self presentModalViewController:c animated:NO];\n[self dismissModalViewControllerAnimated:NO];\n[c release];\n</code></pre>\n\n<p>It is sufficient to present and dismiss a vanilla view controller.</p>\n\n<p>Obviously you'll still need to confirm or deny the orientation in your override of shouldAutorotateToInterfaceOrientation. But this will cause shouldAutorotate... to be called again by the system.</p>\n" }, { "answer_id": 5705918, "author": "user324168", "author_id": 324168, "author_profile": "https://Stackoverflow.com/users/324168", "pm_score": 2, "selected": false, "text": "<p>This works for me (thank you Henry Cooke):</p>\n\n<p>The aim for me was to deal with landscape orientations changes only.</p>\n\n<h2>init method:</h2>\n\n<pre><code>[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];\n[[NSNotificationCenter defaultCenter] addObserver:self\n selector:@selector(orientationChanged:)\n name:UIDeviceOrientationDidChangeNotification\n object:nil];\n</code></pre>\n\n<hr>\n\n<pre><code>- (void)orientationChanged:(NSNotification *)notification { \n //[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];\n UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;\n CGRect bounds = [[ UIScreen mainScreen ] bounds ];\n CGAffineTransform t;\n CGFloat r = 0;\n switch ( orientation ) {\n case UIDeviceOrientationLandscapeRight:\n r = 0;\n NSLog(@\"Right\");\n break;\n case UIDeviceOrientationLandscapeLeft:\n r = M_PI;\n NSLog(@\"Left\");\n break;\n default:return;\n }\n\n t = CGAffineTransformMakeRotation( r );\n\n UIApplication *application = [ UIApplication sharedApplication ];\n [ UIView beginAnimations:@\"InterfaceOrientation\" context: nil ];\n [ UIView setAnimationDuration: [ application statusBarOrientationAnimationDuration ] ];\n self.view.transform = t;\n self.view.bounds = bounds;\n [ UIView commitAnimations ];\n\n [ application setStatusBarOrientation: orientation animated: YES ];\n}\n</code></pre>\n" }, { "answer_id": 6332405, "author": "Christian Schnorr", "author_id": 796103, "author_profile": "https://Stackoverflow.com/users/796103", "pm_score": 3, "selected": false, "text": "<p>Josh's answer works fine for me.</p>\n\n<p>However, I prefer posting an <em>\"orientation did change, please update UI\"</em> notification. When this notification is received by a view controller, it calls <code>shouldAutorotateToInterfaceOrientation:</code>, allowing you to set any orientation by returning <code>YES</code> for the orientation you want.</p>\n\n<pre><code>[[NSNotificationCenter defaultCenter] postNotificationName:UIDeviceOrientationDidChangeNotification object:nil];\n</code></pre>\n\n<p>The only problem is that this forces a re-orientation <strong>without</strong> an animation. You would need to wrap this line between <code>beginAnimations:</code> and <code>commitAnimations</code> to achieve a smooth transition.</p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 7637322, "author": "stephencampbell", "author_id": 976918, "author_profile": "https://Stackoverflow.com/users/976918", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>I have an app where I would like to support device rotation in certain views but other don't particularly make sense in Landscape mode, so as I swapping the views out I would like to force the rotation to be set to portrait.</p>\n</blockquote>\n\n<p>I realise that the above original post in this thread is very old now, but I had a similar problem to it - ie. all of the screens in my App are portrait only, with the exception of one screen, which can be rotated between landscape and portrait by the user.</p>\n\n<p>This was straightforward enough, but like other posts, I wanted the App to automatically return to portrait regardless of the current device orientation, when returning to the previous screen.</p>\n\n<p>The solution I implemented was to hide the Navigation Bar while in landscape mode, meaning that the user can only return to previous screens whilst in portrait. Therefore, all other screens can only be in portrait.</p>\n\n<pre><code>- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)pInterfaceOrientation {\n BOOL lHideNavBar = self.interfaceOrientation == UIInterfaceOrientationPortrait ? NO : YES;\n [self.navigationController setNavigationBarHidden:lHideNavBar animated:YES];\n}\n</code></pre>\n\n<p>This also has the added benefit for my App in that there is more screen space available in landscape mode. This is useful because the screen in question is used to display PDF files.</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 10515645, "author": "Guntis Treulands", "author_id": 894671, "author_profile": "https://Stackoverflow.com/users/894671", "pm_score": 3, "selected": false, "text": "<p>There is a simple way to programmatically force iPhone to the necessary orientation - using two of already provided answers by <strong>kdbdallas</strong>, <strong>Josh</strong> :</p>\n\n<pre><code>//will rotate status bar\n[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight];\n\n\n//will re-rotate view according to statusbar\nUIViewController *c = [[UIViewController alloc]init];\n[self presentModalViewController:c animated:NO];\n[self dismissModalViewControllerAnimated:NO];\n[c release];\n</code></pre>\n\n<p>works like a charm :)</p>\n\n<p>EDIT:</p>\n\n<p>for iOS 6 I need to add this function:\n(works on modal viewcontroller)</p>\n\n<pre><code>- (NSUInteger)supportedInterfaceOrientations\n{\n return (UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight);\n}\n</code></pre>\n" }, { "answer_id": 11337681, "author": "David van Dugteren", "author_id": 297201, "author_profile": "https://Stackoverflow.com/users/297201", "pm_score": 1, "selected": false, "text": "<p>I solved this quite easily in the end. I tried every suggestion above and still came up short, so this was my solution:</p>\n\n<p>In the ViewController that needs to remain Landscape (Left or Right), I listen for orientation changes:</p>\n\n<pre><code> [[NSNotificationCenter defaultCenter] addObserver:self\n selector:@selector(didRotate:)\n name:UIDeviceOrientationDidChangeNotification object:nil];\n</code></pre>\n\n<p>Then in didRotate:</p>\n\n<pre><code>- (void) didRotate:(NSNotification *)notification\n{ if (orientationa == UIDeviceOrientationPortrait) \n {\n if (hasRotated == NO) \n {\n NSLog(@\"Rotating to portait\");\n hasRotated = YES;\n [UIView beginAnimations: @\"\" context:nil];\n [UIView setAnimationDuration: 0];\n self.view.transform = CGAffineTransformIdentity;\n self.view.transform = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(-90));\n self.view.bounds = CGRectMake(0.0f, 0.0f, 480.0f, 320.0f);\n self.view.frame = CGRectMake(0.0f, 0.0f, 480.0f, 320.0f);\n [UIView commitAnimations];\n\n }\n}\nelse if (UIDeviceOrientationIsLandscape( orientationa))\n{\n if (hasRotated) \n {\n NSLog(@\"Rotating to lands\");\n hasRotated = NO;\n [UIView beginAnimations: @\"\" context:nil];\n [UIView setAnimationDuration: 0];\n self.view.transform = CGAffineTransformIdentity;\n self.view.transform = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(0));\n self.view.bounds = CGRectMake(0.0f, 0.0f, 320.0f, 480.0f);\n self.view.frame = CGRectMake(0.0f, 0.0f, 320.0f, 480.0f);\n [UIView commitAnimations];\n\n }\n}\n</code></pre>\n\n<p>Keep in mind any Super Views/Subviews that use autoresizing, as the view.bounds/frame are being reset explicitly... </p>\n\n<p>The only caveat to this method for keeping the view Landscape, is the inherent animation switching between orientations that has to occur, when it would be better to have it appear to have no change. </p>\n" }, { "answer_id": 14299516, "author": "Bo A", "author_id": 871434, "author_profile": "https://Stackoverflow.com/users/871434", "pm_score": 1, "selected": false, "text": "<p>iOS 6 solution:</p>\n\n<pre><code>[[[self window] rootViewController] presentViewController:[[UIViewController alloc] init] animated:NO completion:^{\n [[[self window] rootViewController] dismissViewControllerAnimated:NO completion:nil];\n}];\n</code></pre>\n\n<p>The exact code depends per app and also where you place it (I used it in my AppDelegate). Replace <code>[[self window] rootViewController]</code> with what you use. I was using a <code>UITabBarController</code>.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4496/" ]
I have an app where I would like to support device rotation in certain views but other don't particularly make sense in Landscape mode, so as I swapping the views out I would like to force the rotation to be set to portrait. There is an undocumented property setter on UIDevice that does the trick but obviously generates a compiler warning and could disappear with a future revision of the SDK. ``` [[UIDevice currentDevice] setOrientation:UIInterfaceOrientationPortrait]; ``` Are there any documented ways to force the orientation? **Update:** I thought I would provide an example as I am not looking for shouldAutorotateToInterfaceOrientation as I have already implemented that. I want my app to support landscape and portrait in View 1 but only portrait in View 2. I have already implemented shouldAutorotateToInterfaceOrientation for all views but if the user is in landscape mode in View 1 and then switches to View 2, I want to force the phone to rotate back to Portrait.
This is no longer an issue on the later iPhone 3.1.2 SDK. It now appears to honor the requested orientation of the view being pushed back onto the stack. That likely means that you would need to detect older iPhone OS versions and only apply the setOrientation when it is prior to the latest release. It is not clear if Apple's static analysis will understand that you are working around the older SDK limitations. I personally have been told by Apple to remove the method call on my next update so I am not yet sure if having a hack for older devices will get through the approval process.
181,805
<p>What's the difference between absolute path &amp; relative path when using any web server or Tomcat?</p>
[ { "answer_id": 181811, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 6, "selected": true, "text": "<p>Absolute paths start with / and refer to a location from the root of the current site (or virtual host).</p>\n\n<p>Relative paths do not start with / and refer to a location from the actual location of the document the reference is made.</p>\n\n<p>Examples, assuming root is <a href=\"http://foo.com/site/\" rel=\"noreferrer\">http://foo.com/site/</a></p>\n\n<p>Absolute path, no matter where we are on the site</p>\n\n<pre><code>/foo.html\n</code></pre>\n\n<p>will refer to <a href=\"http://foo.com/site/foo.html\" rel=\"noreferrer\">http://foo.com/site/foo.html</a></p>\n\n<p>Relative path, assuming the containing link is located in <a href=\"http://foo.com/site/part1/bar.html\" rel=\"noreferrer\">http://foo.com/site/part1/bar.html</a></p>\n\n<pre><code>../part2/quux.html\n</code></pre>\n\n<p>will refer to <a href=\"http://foo.com/site/part2/quux.html\" rel=\"noreferrer\">http://foo.com/site/part2/quux.html</a></p>\n\n<p>or</p>\n\n<pre><code>part2/blue.html\n</code></pre>\n\n<p>will refer to <a href=\"http://foo.com/site/part1/part2/blue.html\" rel=\"noreferrer\">http://foo.com/site/part1/part2/blue.html</a></p>\n" }, { "answer_id": 181914, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": "<p>Important to note that relative paths are also subjective. </p>\n\n<p>ie: </p>\n\n<pre><code>&lt;?php \n #bar.php\n require('../foo.php'); \n?&gt;\n</code></pre>\n\n<pre>\n/dir/bar.php \n/foo.php # prints a \n/dir/foo.php # prints b \n/dir/other/ # empty dir\n</pre>\n\n<pre>\n$ pwd \n> /\n$ php dir/bar.php \n> / + ../foo.php == /foo.php \n> prints a \n$ cd dir \n$ php bar.php\n> /dir + ../foo.php = /foo.php \n> prints a\n$ cd other\n$ php ../bar.php \n> /dir/other + ../foo.php = /dir/foo.php \n> prints b\n</pre>\n\n<p>This can create some rather confusing situations, especially if you have many files with releative references and multiple possible places that can act as an \"entry point\" that controls what the relative path is relative to. </p>\n\n<p>In such situations, one should compute the absolute path manually based on a fixed known, ie: </p>\n\n<pre><code>&lt;?php\n require( realpath(dirname(__FILE__) . '/../foo.php') )\n</code></pre>\n\n<p>or </p>\n\n<pre><code>&lt;?php\n require( SOMECONSTANT . '/relative/path.php' ); \n</code></pre>\n\n<p>or</p>\n\n<pre><code>&lt;?php\n require( $_SERVER['DOCUMENT_ROOT'] . '/relative/path.php' );\n</code></pre>\n" }, { "answer_id": 8892388, "author": "David Brossard", "author_id": 1021725, "author_profile": "https://Stackoverflow.com/users/1021725", "pm_score": 1, "selected": false, "text": "<p>Through trial and error I have determined that the starting point of a path in Tomcat is the webapps folder.</p>\n\n<p>In other words if your Java code is trying to read ../somefile.txt then the absolute path to that file would be %TOMCAT_HOME%/webapps/../somefile.txt i.e. %TOMCAT_HOME%/webapps/somefile.txt</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15177/" ]
What's the difference between absolute path & relative path when using any web server or Tomcat?
Absolute paths start with / and refer to a location from the root of the current site (or virtual host). Relative paths do not start with / and refer to a location from the actual location of the document the reference is made. Examples, assuming root is <http://foo.com/site/> Absolute path, no matter where we are on the site ``` /foo.html ``` will refer to <http://foo.com/site/foo.html> Relative path, assuming the containing link is located in <http://foo.com/site/part1/bar.html> ``` ../part2/quux.html ``` will refer to <http://foo.com/site/part2/quux.html> or ``` part2/blue.html ``` will refer to <http://foo.com/site/part1/part2/blue.html>
181,810
<p>I am writing a custom ant task that extends Task. I am using the log() method in the task. What I want to do is use a unit test while deveoping the task, but I don't know how to set up a context for the task to run in to initialise the task as if it were running in ant.</p> <p>This is the custom Task:</p> <pre><code>public class CopyAndSetPropertiesForFiles extends Task { public void execute() throws BuildException { log("CopyAndSetPropertiesForFiles begin execute()"); log("CopyAndSetPropertiesForFiles end execute()"); } } </code></pre> <p>This is the unit test code:</p> <pre><code>CopyAndSetPropertiesForFiles task = new CopyAndSetPropertiesForFiles(); task.execute(); </code></pre> <p>When the code is run as a test it gives a NullPointerException when it calls log.</p> <pre><code>java.lang.NullPointerException at org.apache.tools.ant.Task.log(Task.java:346) at org.apache.tools.ant.Task.log(Task.java:334) at uk.co.tbp.ant.custom.CopyAndSetPropertiesForFiles.execute(CopyAndSetPropertiesForFiles.java:40) at uk.co.tbp.ant.custom.test.TestCopyAndSetPropertiesForFiles.testCopyAndSetPropertiesForFiles(TestCopyAndSetPropertiesForFiles.java:22) </code></pre> <p>Does anybody know a way to provide a context or stubs or something similar to the task?</p> <p>Thanks,</p> <p>Rob.</p> <p>Accepted answer from Abarax. I was able to call task.setProject(new Project()); The code now executes OK (except no logging appears in th console - at least I can exercise the code :-) ).</p>
[ { "answer_id": 185806, "author": "abarax", "author_id": 24390, "author_profile": "https://Stackoverflow.com/users/24390", "pm_score": 2, "selected": true, "text": "<p>Looking at the Ant source code these are the two relevent classes: <a href=\"http://www.docjar.com/html/api/org/apache/tools/ant/ProjectComponent.java.html\" rel=\"nofollow noreferrer\">ProjectComponent</a> and <a href=\"http://www.docjar.com/html/api/org/apache/tools/ant/Task.java.html\" rel=\"nofollow noreferrer\">Task</a></p>\n\n<p>You are calling the log method from Task: </p>\n\n<pre><code>public void log(String msg) {\n log(msg, Project.MSG_INFO);\n}\n</code></pre>\n\n<p>Which calls:</p>\n\n<pre><code>public void log(String msg, int msgLevel) {\n if (getProject() != null) {\n getProject().log(this, msg, msgLevel);\n } else {\n super.log(msg, msgLevel);\n }\n}\n</code></pre>\n\n<p>Since you do not have project set it will call \"super.log(msg, msgLevel)\"</p>\n\n<pre><code>public void log(String msg, int msgLevel) {\n if (getProject() != null) {\n getProject().log(msg, msgLevel);\n } else {\n // 'reasonable' default, if the component is used without\n // a Project ( for example as a standalone Bean ).\n // Most ant components can be used this way.\n if (msgLevel &lt;= Project.MSG_INFO) {\n System.err.println(msg);\n }\n }\n}\n</code></pre>\n\n<p>It looks like this may be your problem. Your task needs a project context.</p>\n" }, { "answer_id": 186459, "author": "Chii", "author_id": 17335, "author_profile": "https://Stackoverflow.com/users/17335", "pm_score": 3, "selected": false, "text": "<p>Or better yet, decouple the task object itself from the logic (lets call it TaskImpl) inside the task - so that you can pass in your own dependencies (e.g., the logger). Then, instead of testing the task object, you test TaskImpl -> which you can pass in the logger, and any other weird bits and pieces it might need to do its job. Then unit testing is a matter of mocking the dependencies. </p>\n" }, { "answer_id": 1875418, "author": "Emily", "author_id": 203809, "author_profile": "https://Stackoverflow.com/users/203809", "pm_score": 1, "selected": false, "text": "<p>Ant has a handy class called BuildFileTest that extends the JUnit TestCase class. You can use it to test the behaviour of individual targets in a build file. Using this would take care of all the annoying context.</p>\n\n<p>There's a <a href=\"http://ant.apache.org/manual/tutorial-writing-tasks.html#TestingTasks\" rel=\"nofollow noreferrer\">Test The Task</a> chapter in the Apache Ant Writing Tasks Tutorial that describes this.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26063/" ]
I am writing a custom ant task that extends Task. I am using the log() method in the task. What I want to do is use a unit test while deveoping the task, but I don't know how to set up a context for the task to run in to initialise the task as if it were running in ant. This is the custom Task: ``` public class CopyAndSetPropertiesForFiles extends Task { public void execute() throws BuildException { log("CopyAndSetPropertiesForFiles begin execute()"); log("CopyAndSetPropertiesForFiles end execute()"); } } ``` This is the unit test code: ``` CopyAndSetPropertiesForFiles task = new CopyAndSetPropertiesForFiles(); task.execute(); ``` When the code is run as a test it gives a NullPointerException when it calls log. ``` java.lang.NullPointerException at org.apache.tools.ant.Task.log(Task.java:346) at org.apache.tools.ant.Task.log(Task.java:334) at uk.co.tbp.ant.custom.CopyAndSetPropertiesForFiles.execute(CopyAndSetPropertiesForFiles.java:40) at uk.co.tbp.ant.custom.test.TestCopyAndSetPropertiesForFiles.testCopyAndSetPropertiesForFiles(TestCopyAndSetPropertiesForFiles.java:22) ``` Does anybody know a way to provide a context or stubs or something similar to the task? Thanks, Rob. Accepted answer from Abarax. I was able to call task.setProject(new Project()); The code now executes OK (except no logging appears in th console - at least I can exercise the code :-) ).
Looking at the Ant source code these are the two relevent classes: [ProjectComponent](http://www.docjar.com/html/api/org/apache/tools/ant/ProjectComponent.java.html) and [Task](http://www.docjar.com/html/api/org/apache/tools/ant/Task.java.html) You are calling the log method from Task: ``` public void log(String msg) { log(msg, Project.MSG_INFO); } ``` Which calls: ``` public void log(String msg, int msgLevel) { if (getProject() != null) { getProject().log(this, msg, msgLevel); } else { super.log(msg, msgLevel); } } ``` Since you do not have project set it will call "super.log(msg, msgLevel)" ``` public void log(String msg, int msgLevel) { if (getProject() != null) { getProject().log(msg, msgLevel); } else { // 'reasonable' default, if the component is used without // a Project ( for example as a standalone Bean ). // Most ant components can be used this way. if (msgLevel <= Project.MSG_INFO) { System.err.println(msg); } } } ``` It looks like this may be your problem. Your task needs a project context.
181,818
<p>According to the <a href="http://feedparser.org/docs/introduction.html" rel="noreferrer">feedparser documentation</a>, I can turn an RSS feed into a parsed object like this:</p> <pre><code>import feedparser d = feedparser.parse('http://feedparser.org/docs/examples/atom10.xml') </code></pre> <p>but I can't find anything showing how to go the other way; I'd like to be able do manipulate 'd' and then output the result as XML:</p> <pre><code>print d.toXML() </code></pre> <p>but there doesn't seem to be anything in feedparser for going in that direction. Am I going to have to loop through d's various elements, or is there a quicker way?</p>
[ { "answer_id": 181832, "author": "Andrea Ambu", "author_id": 21384, "author_profile": "https://Stackoverflow.com/users/21384", "pm_score": 0, "selected": false, "text": "<pre><code>from xml.dom import minidom\n\ndoc= minidom.parse('./your/file.xml')\nprint doc.toxml()\n</code></pre>\n\n<p>The only problem is that it do not download feeds from the internet.</p>\n" }, { "answer_id": 181903, "author": "Jon Cage", "author_id": 15369, "author_profile": "https://Stackoverflow.com/users/15369", "pm_score": 0, "selected": false, "text": "<p>As a method of making a feed, how about <a href=\"http://www.dalkescientific.com/Python/PyRSS2Gen.html\" rel=\"nofollow noreferrer\">PyRSS2Gen</a>? :)</p>\n\n<p>I've not played with FeedParser, but have you tried just doing str(yourFeedParserObject)? I've often been suprised by various modules that have <strong>str</strong> methods to just output the object as text.</p>\n\n<p><strong>[Edit]</strong> Just tried the str() method and it doesn't work on this one. Worth a shot though ;-)</p>\n" }, { "answer_id": 181931, "author": "Jon Cage", "author_id": 15369, "author_profile": "https://Stackoverflow.com/users/15369", "pm_score": 1, "selected": false, "text": "<p>If you're looking to read in an XML feed, modify it and then output it again, there's <a href=\"http://wiki.python.org/moin/RssLibraries\" rel=\"nofollow noreferrer\">a page on the main python wiki indicating that the RSS.py library might support what you're after</a> (it reads most RSS and is able to output RSS 1.0). I've not looked at it in much detail though..</p>\n" }, { "answer_id": 191899, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 4, "selected": true, "text": "<p>Appended is a not hugely-elegant, but working solution - it uses feedparser to parse the feed, you can then modify the entries, and it passes the data to PyRSS2Gen. It preserves <em>most</em> of the feed info (the important bits anyway, there are somethings that will need extra conversion, the parsed_feed['feed']['image'] element for example).</p>\n\n<p>I put this together as part of a <a href=\"http://github.com/dbr/pyfeedproc\" rel=\"nofollow noreferrer\">little feed-processing framework</a> I'm fiddling about with.. It may be of some use (it's pretty short - should be less than 100 lines of code in total when done..)</p>\n\n<pre><code>#!/usr/bin/env python\nimport datetime\n\n# http://www.feedparser.org/\nimport feedparser\n# http://www.dalkescientific.com/Python/PyRSS2Gen.html\nimport PyRSS2Gen\n\n# Get the data\nparsed_feed = feedparser.parse('http://reddit.com/.rss')\n\n# Modify the parsed_feed data here\n\nitems = [\n PyRSS2Gen.RSSItem(\n title = x.title,\n link = x.link,\n description = x.summary,\n guid = x.link,\n pubDate = datetime.datetime(\n x.modified_parsed[0],\n x.modified_parsed[1],\n x.modified_parsed[2],\n x.modified_parsed[3],\n x.modified_parsed[4],\n x.modified_parsed[5])\n )\n\n for x in parsed_feed.entries\n]\n\n# make the RSS2 object\n# Try to grab the title, link, language etc from the orig feed\n\nrss = PyRSS2Gen.RSS2(\n title = parsed_feed['feed'].get(\"title\"),\n link = parsed_feed['feed'].get(\"link\"),\n description = parsed_feed['feed'].get(\"description\"),\n\n language = parsed_feed['feed'].get(\"language\"),\n copyright = parsed_feed['feed'].get(\"copyright\"),\n managingEditor = parsed_feed['feed'].get(\"managingEditor\"),\n webMaster = parsed_feed['feed'].get(\"webMaster\"),\n pubDate = parsed_feed['feed'].get(\"pubDate\"),\n lastBuildDate = parsed_feed['feed'].get(\"lastBuildDate\"),\n\n categories = parsed_feed['feed'].get(\"categories\"),\n generator = parsed_feed['feed'].get(\"generator\"),\n docs = parsed_feed['feed'].get(\"docs\"),\n\n items = items\n)\n\n\nprint rss.to_xml()\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15371/" ]
According to the [feedparser documentation](http://feedparser.org/docs/introduction.html), I can turn an RSS feed into a parsed object like this: ``` import feedparser d = feedparser.parse('http://feedparser.org/docs/examples/atom10.xml') ``` but I can't find anything showing how to go the other way; I'd like to be able do manipulate 'd' and then output the result as XML: ``` print d.toXML() ``` but there doesn't seem to be anything in feedparser for going in that direction. Am I going to have to loop through d's various elements, or is there a quicker way?
Appended is a not hugely-elegant, but working solution - it uses feedparser to parse the feed, you can then modify the entries, and it passes the data to PyRSS2Gen. It preserves *most* of the feed info (the important bits anyway, there are somethings that will need extra conversion, the parsed\_feed['feed']['image'] element for example). I put this together as part of a [little feed-processing framework](http://github.com/dbr/pyfeedproc) I'm fiddling about with.. It may be of some use (it's pretty short - should be less than 100 lines of code in total when done..) ``` #!/usr/bin/env python import datetime # http://www.feedparser.org/ import feedparser # http://www.dalkescientific.com/Python/PyRSS2Gen.html import PyRSS2Gen # Get the data parsed_feed = feedparser.parse('http://reddit.com/.rss') # Modify the parsed_feed data here items = [ PyRSS2Gen.RSSItem( title = x.title, link = x.link, description = x.summary, guid = x.link, pubDate = datetime.datetime( x.modified_parsed[0], x.modified_parsed[1], x.modified_parsed[2], x.modified_parsed[3], x.modified_parsed[4], x.modified_parsed[5]) ) for x in parsed_feed.entries ] # make the RSS2 object # Try to grab the title, link, language etc from the orig feed rss = PyRSS2Gen.RSS2( title = parsed_feed['feed'].get("title"), link = parsed_feed['feed'].get("link"), description = parsed_feed['feed'].get("description"), language = parsed_feed['feed'].get("language"), copyright = parsed_feed['feed'].get("copyright"), managingEditor = parsed_feed['feed'].get("managingEditor"), webMaster = parsed_feed['feed'].get("webMaster"), pubDate = parsed_feed['feed'].get("pubDate"), lastBuildDate = parsed_feed['feed'].get("lastBuildDate"), categories = parsed_feed['feed'].get("categories"), generator = parsed_feed['feed'].get("generator"), docs = parsed_feed['feed'].get("docs"), items = items ) print rss.to_xml() ```
181,829
<p>I'm working in a web application using VB.NET. There is also VisualBasic code mixed in it, in particular the Date variable and the Month function of VB.</p> <p>The problem is this part:</p> <pre><code>Month("10/01/2008") </code></pre> <p>On the servers, I get 10 (October) as the month (which is supposed to be correct). On my machine, I get 1 (January) (which is supposed to be wrong).</p> <p>Two of my colleagues (on their own machines) get different answers, one got 1, the other got 10.</p> <p><strong>The question is, why is this so?</strong></p> <p>On my end, I can solve the problem by using .NET's DateTime's Parse (or ParseExact) function to force everything to be "dd/MM/yyyy" format. This works. I'm just wondering why there's an inconsistency.</p> <p>Extra info: I know the parameter for Month function is supposed to be a Date variable. The code used a string as parameter, and Option Strict was off, and the developers mainly let VB do its own conversion thing. (Legacy code maintenance has a lot of inertia...)</p> <p>If it helps, the version of Microsoft.VisualBasic.dll on the servers is 7.10.6310.4 (under the Framework folder v1.1.4322). The version on mine (and my 2 colleagues') machine is 7.10.6001.4.</p> <p>Edit: Regional settings for all machines already set to dd/MM/yyyy format (short date format).</p>
[ { "answer_id": 181844, "author": "EggyBach", "author_id": 15475, "author_profile": "https://Stackoverflow.com/users/15475", "pm_score": 4, "selected": true, "text": "<p>This normally has to do with the regional settings, and more specifically the date/time formats. If you set these formats so that they are all the same on the machines you're testing on, the results should be consistent. </p>\n\n<p>Your idea of using ParseExact is definitely the better solution to go with, IMHO.</p>\n" }, { "answer_id": 181860, "author": "Jan", "author_id": 25727, "author_profile": "https://Stackoverflow.com/users/25727", "pm_score": 2, "selected": false, "text": "<p>This is because the runtime has to convert your given value \"10/01/2008\" which is indeed a string implicitly to the DateTime datatype.</p>\n\n<p>When converting strings to dates and the other way round, the string format depends on the locale settings of windows.</p>\n\n<p>See <a href=\"http://msdn.microsoft.com/en-us/library/aa292073.aspx\" rel=\"nofollow noreferrer\">this link</a> on msdn.</p>\n\n<p>In <a href=\"http://msdn.microsoft.com/en-us/library/3eaydw6e(VS.80).aspx\" rel=\"nofollow noreferrer\">this article</a> a way to specify a date literal which is independent of your locale settings:</p>\n\n<p>Just enclose the date with the sign # and specify it in the form mm/dd/yyyy:</p>\n\n<p>So the code </p>\n\n<pre><code>Month(#10/01/2008#) \n</code></pre>\n\n<p>should give you the answer 10 on any machine.</p>\n\n<p>Ther a two more worarounds given in that msdn article:</p>\n\n<p><strong>1. Use the Format Function with predifned Date/Time Format</strong></p>\n\n<blockquote>\n <p>To convert a Date literal to the\n format of your locale, or to a custom\n format, supply the literal to the\n Format Function, specifying either\n Predefined Date/Time Formats (Format\n Function) or User-Defined Date/Time\n Formats (Format Function). The\n following example demonstrates this.</p>\n \n <p>MsgBox(\"The formatted date is \" &amp;\n Format(#5/31/1993#, \"dddd, d MMM\n yyyy\"))</p>\n</blockquote>\n\n<p><strong>2. Use the DateTime-Class Constructor to construt the right DateTime value</strong></p>\n\n<blockquote>\n <p>Alternatively, you can use one of the\n overloaded constructors of the\n DateTime structure to assemble a date\n and time value. The following example\n creates a value to represent May 31,\n 1993 at 12:14 in the afternoon.</p>\n \n <p>Dim dateInMay As New\n System.DateTime(1993, 5, 31, 12, 14,\n 0)</p>\n</blockquote>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12984/" ]
I'm working in a web application using VB.NET. There is also VisualBasic code mixed in it, in particular the Date variable and the Month function of VB. The problem is this part: ``` Month("10/01/2008") ``` On the servers, I get 10 (October) as the month (which is supposed to be correct). On my machine, I get 1 (January) (which is supposed to be wrong). Two of my colleagues (on their own machines) get different answers, one got 1, the other got 10. **The question is, why is this so?** On my end, I can solve the problem by using .NET's DateTime's Parse (or ParseExact) function to force everything to be "dd/MM/yyyy" format. This works. I'm just wondering why there's an inconsistency. Extra info: I know the parameter for Month function is supposed to be a Date variable. The code used a string as parameter, and Option Strict was off, and the developers mainly let VB do its own conversion thing. (Legacy code maintenance has a lot of inertia...) If it helps, the version of Microsoft.VisualBasic.dll on the servers is 7.10.6310.4 (under the Framework folder v1.1.4322). The version on mine (and my 2 colleagues') machine is 7.10.6001.4. Edit: Regional settings for all machines already set to dd/MM/yyyy format (short date format).
This normally has to do with the regional settings, and more specifically the date/time formats. If you set these formats so that they are all the same on the machines you're testing on, the results should be consistent. Your idea of using ParseExact is definitely the better solution to go with, IMHO.
181,845
<p>I met a problem when deveoping a photo viewer application. I use ListBox to Show Images, which is contained in a ObservableCollection. I bind the ListBox's ItemsSource to the ObservableCollection.</p> <pre><code> &lt;DataTemplate DataType="{x:Type modeldata:ImageInfo}"&gt; &lt;Image Margin="6" Source="{Binding Thumbnail}" Width="{Binding ZoomBarWidth.Width, Source={StaticResource zoombarmanager}}" Height="{Binding ZoomBarWidth.Width, Source={StaticResource zoombarmanager}}"/&gt; &lt;/DataTemplate&gt; &lt;Grid DataContext="{StaticResource imageinfolder}"&gt; &lt;ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled"&gt; &lt;ListBox Name="PhotosListBox" IsSynchronizedWithCurrentItem="True" Style="{StaticResource PhotoListBoxStyle}" Margin="5" SelectionMode="Extended" ItemsSource="{Binding}" /&gt; &lt;/ScrollViewer&gt; </code></pre> <p>I also bind the Image'height in ListBox with a slider.(the slider's Value also bind to zoombarmanager.ZoomBarWidth.Width). But I found if the collection become larger, such as: contains more then 1000 images, If I use the slider to change the size of iamges, it become a bit slow. My Question is. 1. Why it become Slow? become it tries to zoom every images,or it just because notify("Width") is invoked more than 1000 times. 2. Is there any method to solve this kind of problem and make it faster.</p> <p>The PhotoListBoxStyle is like this:</p> <pre><code> &lt;Style~~ TargetType="{x:Type ListBox}" x:Key="PhotoListBoxStyle"&gt; &lt;Setter Property="Foreground" Value="White" /&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type ListBox}" &gt; &lt;WrapPanel Margin="5" IsItemsHost="True" Orientation="Horizontal" VerticalAlignment="Top" HorizontalAlignment="Stretch" /&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style~~&gt; </code></pre> <p>But If I use the Style above, I have to use ScrollViewer outside ListBox, otherwise I have no idea how to get a smooth scrolling scrollerbar and the wrappanel seems have no default scrollerbar. Anyone help? It is said listbox with scrollviewer has poor performance.</p>
[ { "answer_id": 181883, "author": "J c", "author_id": 25837, "author_profile": "https://Stackoverflow.com/users/25837", "pm_score": 2, "selected": false, "text": "<ol>\n<li><p>I am not familiar with this component, but in general there is going to be limitations on the number of items a listbox can display at one time.</p></li>\n<li><p>A method to solve this kind of problem is to keep the number of images loaded in the control within the number the control can display at acceptable performance levels. Two techniques to do this are paging or dynamic loading.</p></li>\n</ol>\n\n<p>In paging, you add controls to switch between discrete blocks of pictures, for example, 100 at a time, with forward and back arrows, similar to navigating database records.</p>\n\n<p>With dynamic loading, you implement paging behind the scenes in such a way that when the user scrolls to the end, the application automatically loads in the next batch of pictures, and potentially even removes a batch of old ones to keep the responsiveness reasonable. There may be a small pause as this occurs and there may be some work involved to keep the control at the proper scroll point, but this may be an acceptable trade-off.</p>\n" }, { "answer_id": 182005, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 0, "selected": false, "text": "<p>What does your PhotoListBoxStyle style look like? If it's changing the ListBox's ItemsPanelTemplate then there's a good chance your ListBox isn't using a VirtualizingStackPanel as its underlying list panel. Non-virtualized ListBoxes are a lot slower with many items.</p>\n" }, { "answer_id": 182014, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": 1, "selected": false, "text": "<p>try to virtualize your stackpael with the VirtualizingStackPanel.IsVirtualizing=\"True\" attached property. this should increase performance. </p>\n\n<p>using a listbox with many items in a scrollviewer is another known performance issue within wpf. if you can, try to get rid of the scrollviewer. </p>\n\n<p>if your itemtemplates are kinda complex you should consider using the Recycling VirtualizationMode. this tells your listbox to reuse existing objects and not create new ones all the time.</p>\n" }, { "answer_id": 182827, "author": "Joel B Fant", "author_id": 22211, "author_profile": "https://Stackoverflow.com/users/22211", "pm_score": 2, "selected": false, "text": "<p>Part of the problem is that it is loading the full image in each. You have to use an <code>IValueConverter</code> to open each image in a thumbnail size by setting either the <code>DecodePixelWidth</code> or <code>DecodePixelHeight</code> properties on the <code>BitmapImage</code>. Here's an example I use in one of my projects...</p>\n\n<pre><code>class PathToThumbnailConverter : IValueConverter {\n public int DecodeWidth {\n get;\n set;\n }\n\n public PathToThumbnailConverter() {\n DecodeWidth = 200;\n }\n\n public object Convert( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture ) {\n var path = value as string;\n\n if ( !string.IsNullOrEmpty( path ) ) {\n\n FileInfo info = new FileInfo( path );\n\n if ( info.Exists &amp;&amp; info.Length &gt; 0 ) {\n BitmapImage bi = new BitmapImage();\n\n bi.BeginInit();\n bi.DecodePixelWidth = DecodeWidth;\n bi.CacheOption = BitmapCacheOption.OnLoad;\n bi.UriSource = new Uri( info.FullName );\n bi.EndInit();\n\n return bi;\n }\n }\n\n return null;\n }\n\n public object ConvertBack( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture ) {\n throw new NotImplementedException();\n }\n\n}\n</code></pre>\n" }, { "answer_id": 182897, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 2, "selected": false, "text": "<p>I would recommend you not bind the Width/Height property of each individual image, but rather you bind a <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.layouttransform.aspx\" rel=\"nofollow noreferrer\">LayoutTransform</a> on the ListBox's <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.itemspanel.aspx\" rel=\"nofollow noreferrer\">ItemsPanel</a>. Something like:</p>\n\n<pre><code>&lt;ListBox.ItemsPanel&gt;\n &lt;ItemsPanelTemplate&gt;\n &lt;StackPanel&gt;\n &lt;StackPanel.LayoutTransform&gt;\n &lt;ScaleTransform\n ScaleX=\"{Binding Path=Value, ElementName=ZoomSlider}\"\n ScaleY=\"{Binding Path=Value, ElementName=ZoomSlider}\" /&gt;\n &lt;/StackPanel.LayoutTransform&gt;\n &lt;/StackPanel&gt;\n &lt;/ItemsPanelTemplate&gt;\n&lt;/ListBox.ItemsPanel&gt;\n</code></pre>\n" }, { "answer_id": 186187, "author": "rudigrobler", "author_id": 5147, "author_profile": "https://Stackoverflow.com/users/5147", "pm_score": 4, "selected": true, "text": "<p>The problem is that your new Layout Panel is the WrapPanel and it doesn't support Virtualization! It is possible to create your own Virtualized WrapPanel... Read more <a href=\"http://jerryclin.wordpress.com/2008/02/06/making-a-virtualizing-wrappanel/\" rel=\"noreferrer\">here</a></p>\n\n<p>Also read more about other issues like the implementation IScrollInfo <a href=\"http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b077f10c-e600-493f-b526-f2996ce6cffc/\" rel=\"noreferrer\">here</a></p>\n\n<p>I also highly recommend that your do not create a new control template just to replace the layout panel... Rather do the following:</p>\n\n<pre><code>&lt;ListBox.ItemsPanel&gt;\n &lt;ItemsPanelTemplate&gt;\n &lt;WrapPanel Orientation=\"Horizontal\"/&gt;\n &lt;/ItemsPanelTemplate&gt;\n&lt;/ListBox.ItemsPanel&gt;\n</code></pre>\n\n<p>The advantage of doing this is that you do not need to wrap your listbox in a scrollviewer!</p>\n\n<p>[<strong>UPDATE</strong>] Also read <a href=\"http://www.codeproject.com/KB/WPF/CustomListBoxLayoutInWPF.aspx\" rel=\"noreferrer\">this</a> article by Josh Smith! To make the WrapPanel wrap... you also have to remember to disable horizontal scrolling...</p>\n\n<pre><code>&lt;Setter Property=\"ScrollViewer.HorizontalScrollBarVisibility\" Value=\"Disabled\" /&gt;\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25749/" ]
I met a problem when deveoping a photo viewer application. I use ListBox to Show Images, which is contained in a ObservableCollection. I bind the ListBox's ItemsSource to the ObservableCollection. ``` <DataTemplate DataType="{x:Type modeldata:ImageInfo}"> <Image Margin="6" Source="{Binding Thumbnail}" Width="{Binding ZoomBarWidth.Width, Source={StaticResource zoombarmanager}}" Height="{Binding ZoomBarWidth.Width, Source={StaticResource zoombarmanager}}"/> </DataTemplate> <Grid DataContext="{StaticResource imageinfolder}"> <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled"> <ListBox Name="PhotosListBox" IsSynchronizedWithCurrentItem="True" Style="{StaticResource PhotoListBoxStyle}" Margin="5" SelectionMode="Extended" ItemsSource="{Binding}" /> </ScrollViewer> ``` I also bind the Image'height in ListBox with a slider.(the slider's Value also bind to zoombarmanager.ZoomBarWidth.Width). But I found if the collection become larger, such as: contains more then 1000 images, If I use the slider to change the size of iamges, it become a bit slow. My Question is. 1. Why it become Slow? become it tries to zoom every images,or it just because notify("Width") is invoked more than 1000 times. 2. Is there any method to solve this kind of problem and make it faster. The PhotoListBoxStyle is like this: ``` <Style~~ TargetType="{x:Type ListBox}" x:Key="PhotoListBoxStyle"> <Setter Property="Foreground" Value="White" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListBox}" > <WrapPanel Margin="5" IsItemsHost="True" Orientation="Horizontal" VerticalAlignment="Top" HorizontalAlignment="Stretch" /> </ControlTemplate> </Setter.Value> </Setter> </Style~~> ``` But If I use the Style above, I have to use ScrollViewer outside ListBox, otherwise I have no idea how to get a smooth scrolling scrollerbar and the wrappanel seems have no default scrollerbar. Anyone help? It is said listbox with scrollviewer has poor performance.
The problem is that your new Layout Panel is the WrapPanel and it doesn't support Virtualization! It is possible to create your own Virtualized WrapPanel... Read more [here](http://jerryclin.wordpress.com/2008/02/06/making-a-virtualizing-wrappanel/) Also read more about other issues like the implementation IScrollInfo [here](http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b077f10c-e600-493f-b526-f2996ce6cffc/) I also highly recommend that your do not create a new control template just to replace the layout panel... Rather do the following: ``` <ListBox.ItemsPanel> <ItemsPanelTemplate> <WrapPanel Orientation="Horizontal"/> </ItemsPanelTemplate> </ListBox.ItemsPanel> ``` The advantage of doing this is that you do not need to wrap your listbox in a scrollviewer! [**UPDATE**] Also read [this](http://www.codeproject.com/KB/WPF/CustomListBoxLayoutInWPF.aspx) article by Josh Smith! To make the WrapPanel wrap... you also have to remember to disable horizontal scrolling... ``` <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" /> ```
181,853
<p>I am using Moq to mock my Repository layer so I can unit test.</p> <p>My repository layer Insert methods update the Id property of my entities when a successful db insert occurs.</p> <p>How do I configure moq to update the Id property of the entity when the Insert method is called? </p> <p>Repository code:-</p> <pre><code>void IAccountRepository.InsertAccount(AccountEntity account); </code></pre> <p>Unit Test:-</p> <pre><code>[TestInitialize()] public void MyTestInitialize() { accountRepository = new Mock&lt;IAccountRepository&gt;(); contactRepository = new Mock&lt;IContactRepository&gt;(); contractRepository = new Mock&lt;IContractRepository&gt;(); planRepository = new Mock&lt;IPlanRepository&gt;(); generator = new Mock&lt;NumberGenerator&gt;(); service = new ContractService(contractRepository.Object, accountRepository.Object, planRepository.Object, contactRepository.Object, generator.Object); } [TestMethod] public void SubmitNewContractTest() { // Setup Mock Objects planRepository .Expect(p =&gt; p.GetPlan(1)) .Returns(new PlanEntity() { Id = 1 }); generator .Expect(p =&gt; p.GenerateAccountNumber()) .Returns("AC0001"); // Not sure what to do here? // How to mock updating the Id field for Inserts? // // Creates a correctly populated NewContractRequest instance NewContractRequest request = CreateNewContractRequestFullyPopulated(); NewContractResponse response = service.SubmitNewContract(request); Assert.IsTrue(response.IsSuccessful); } </code></pre> <p>implementation snippet from ContractService class (WCF service contract).</p> <pre><code>AccountEntity account = new AccountEntity() { AccountName = request.Contact.Name, AccountNumber = accountNumber, BillingMethod = BillingMethod.CreditCard, IsInvoiceRoot = true, BillingAddressType = BillingAddressType.Postal, ContactId = request.Contact.Id.Value }; accountRepository.InsertAccount(account); if (account.Id == null) { // ERROR } </code></pre> <p>I apologise if this information may be a little lacking. I only started learning moq and mocking frameworks today. ac</p>
[ { "answer_id": 181863, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 4, "selected": true, "text": "<p>You can use the Callback method to mock side-effects. Something like:</p>\n\n<pre><code>accountRepository\n .Expect(r =&gt; r.InsertAccount(account))\n .Callback(() =&gt; account.ID = 1);\n</code></pre>\n\n<p>That's untested but it's along the right lines.</p>\n" }, { "answer_id": 185370, "author": "Rob Gray", "author_id": 5691, "author_profile": "https://Stackoverflow.com/users/5691", "pm_score": 2, "selected": false, "text": "<p>I'm not sure how that will work because account is created inside the method, so it's not the instance I'll be referring to when I set the value of ID to 1.</p>\n\n<p>Perhaps there's a flaw in my design and I should be checking for ID > 0 inside the IAccountRepository.InsertAccount implementation and then returning a bool if it's ok. Though then I've a problem with inserting an account that has a related object that needs to be insterted (and an Id genereated).</p>\n\n<p>I found this to be the answer to my problem</p>\n\n<pre><code>accountRepository\n .Expect(p =&gt; p.InsertAccount(It.Is&lt;AccountEntity&gt;(x =&gt; x.Id == null)))\n .Callback&lt;AccountEntity&gt;(a =&gt; a.Id = 1);\n</code></pre>\n\n<p>thanks.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5691/" ]
I am using Moq to mock my Repository layer so I can unit test. My repository layer Insert methods update the Id property of my entities when a successful db insert occurs. How do I configure moq to update the Id property of the entity when the Insert method is called? Repository code:- ``` void IAccountRepository.InsertAccount(AccountEntity account); ``` Unit Test:- ``` [TestInitialize()] public void MyTestInitialize() { accountRepository = new Mock<IAccountRepository>(); contactRepository = new Mock<IContactRepository>(); contractRepository = new Mock<IContractRepository>(); planRepository = new Mock<IPlanRepository>(); generator = new Mock<NumberGenerator>(); service = new ContractService(contractRepository.Object, accountRepository.Object, planRepository.Object, contactRepository.Object, generator.Object); } [TestMethod] public void SubmitNewContractTest() { // Setup Mock Objects planRepository .Expect(p => p.GetPlan(1)) .Returns(new PlanEntity() { Id = 1 }); generator .Expect(p => p.GenerateAccountNumber()) .Returns("AC0001"); // Not sure what to do here? // How to mock updating the Id field for Inserts? // // Creates a correctly populated NewContractRequest instance NewContractRequest request = CreateNewContractRequestFullyPopulated(); NewContractResponse response = service.SubmitNewContract(request); Assert.IsTrue(response.IsSuccessful); } ``` implementation snippet from ContractService class (WCF service contract). ``` AccountEntity account = new AccountEntity() { AccountName = request.Contact.Name, AccountNumber = accountNumber, BillingMethod = BillingMethod.CreditCard, IsInvoiceRoot = true, BillingAddressType = BillingAddressType.Postal, ContactId = request.Contact.Id.Value }; accountRepository.InsertAccount(account); if (account.Id == null) { // ERROR } ``` I apologise if this information may be a little lacking. I only started learning moq and mocking frameworks today. ac
You can use the Callback method to mock side-effects. Something like: ``` accountRepository .Expect(r => r.InsertAccount(account)) .Callback(() => account.ID = 1); ``` That's untested but it's along the right lines.
181,894
<p>I'm testing the speed of some queries in MySQL. The database is caching these queries making it difficult for me to get reliable results when testing how fast these queries are.</p> <p>Is there a way to disable caching for a query?</p> <p>System: MySQL 4 on Linux webhosting, I have access to PHPMyAdmin.</p> <p>Thanks</p>
[ { "answer_id": 181905, "author": "Jarod Elliott", "author_id": 1061, "author_profile": "https://Stackoverflow.com/users/1061", "pm_score": 9, "selected": false, "text": "<p>Try using the <a href=\"https://dev.mysql.com/doc/refman/5.7/en/query-cache-in-select.html\" rel=\"noreferrer\">SQL_NO_CACHE</a> (MySQL 5.7) option in your query.\n(MySQL 5.6 users click <a href=\"https://dev.mysql.com/doc/refman/5.6/en/query-cache-in-select.html\" rel=\"noreferrer\">HERE</a> )</p>\n\n<p>eg.</p>\n\n<pre><code>SELECT SQL_NO_CACHE * FROM TABLE\n</code></pre>\n\n<p>This will stop MySQL caching the results, however be aware that other OS and disk caches may also impact performance. These are harder to get around.</p>\n" }, { "answer_id": 190348, "author": "djt", "author_id": 26677, "author_profile": "https://Stackoverflow.com/users/26677", "pm_score": 5, "selected": false, "text": "<p>You can also run the follow command to reset the query cache.</p>\n\n<pre><code>RESET QUERY CACHE\n</code></pre>\n" }, { "answer_id": 654103, "author": "Jinesh", "author_id": 44573, "author_profile": "https://Stackoverflow.com/users/44573", "pm_score": 2, "selected": false, "text": "<p>If you want to disable the Query cache set the 'query_cache_size' to 0 in your mysql configuration file . If its set 0 mysql wont use the query cache.</p>\n" }, { "answer_id": 1257976, "author": "wbharding", "author_id": 153610, "author_profile": "https://Stackoverflow.com/users/153610", "pm_score": 4, "selected": false, "text": "<p>One problem with the </p>\n\n<pre><code>SELECT SQL_NO_CACHE * FROM TABLE\n</code></pre>\n\n<p>method is that it seems to only prevent the result of your query from being cached. However, if you're querying a database that is actively being used with the query you want to test, then other clients may cache your query, affecting your results. I am continuing to research ways around this, will edit this post if I figure one out.</p>\n" }, { "answer_id": 5416153, "author": "barbushin", "author_id": 341260, "author_profile": "https://Stackoverflow.com/users/341260", "pm_score": 5, "selected": false, "text": "<p>There is also configuration option: query_cache_size=0</p>\n\n<blockquote>\n <p>To disable the query cache at server startup, set the query_cache_size system variable to 0. By disabling the query cache code, there is no noticeable overhead. If you build MySQL from source, query cache capabilities can be excluded from the server entirely by invoking configure with the --without-query-cache option.</p>\n</blockquote>\n\n<p>See <a href=\"http://dev.mysql.com/doc/refman/5.1/en/query-cache.html\" rel=\"noreferrer\">http://dev.mysql.com/doc/refman/5.1/en/query-cache.html</a></p>\n" }, { "answer_id": 6408485, "author": "mediobit", "author_id": 732290, "author_profile": "https://Stackoverflow.com/users/732290", "pm_score": 6, "selected": false, "text": "<p>Any reference to current date/time will disable the query cache for that selection:</p>\n\n<pre><code>SELECT *,NOW() FROM TABLE\n</code></pre>\n\n<p>See \"Prerequisites and Notes for MySQL Query Cache Use\" @ <a href=\"http://dev.mysql.com/tech-resources/articles/mysql-query-cache.html\">http://dev.mysql.com/tech-resources/articles/mysql-query-cache.html</a></p>\n" }, { "answer_id": 6706731, "author": "John Carter", "author_id": 8331, "author_profile": "https://Stackoverflow.com/users/8331", "pm_score": 7, "selected": false, "text": "<p>Another alternative that only affects the current connection:</p>\n\n<pre><code>SET SESSION query_cache_type=0;\n</code></pre>\n" }, { "answer_id": 8862462, "author": "newtover", "author_id": 68998, "author_profile": "https://Stackoverflow.com/users/68998", "pm_score": 2, "selected": false, "text": "<p>Using a user-defined variable within a query makes the query resuts uncacheable. I found it a much better indicator than using <code>SQL_NO_CACHE</code>. But you should put the variable in a place where the variable setting would not seriously affect the performance:</p>\n\n<pre><code>SELECT t.*\nFROM thetable t, (SELECT @a:=NULL) as init;\n</code></pre>\n" }, { "answer_id": 19727015, "author": "Sergio Costa", "author_id": 1887713, "author_profile": "https://Stackoverflow.com/users/1887713", "pm_score": 4, "selected": false, "text": "<p>I'd Use the following:</p>\n\n<pre><code>SHOW VARIABLES LIKE 'query_cache_type';\nSET SESSION query_cache_type = OFF;\nSHOW VARIABLES LIKE 'query_cache_type';\n</code></pre>\n" }, { "answer_id": 65108227, "author": "Ian", "author_id": 1429053, "author_profile": "https://Stackoverflow.com/users/1429053", "pm_score": 2, "selected": false, "text": "<p>Whilst some of the answers are good, there is a major caveat.</p>\n<p>The mysql queries may be prevented from being cached, but it won't prevent your underlying O.S caching disk accesses into memory. This can be a major slowdown for some queries especially if they need to pull data from spinning disks.</p>\n<p>So whilst it's good to use the methods above, I would also try and test with a different set of data/range each time, that's likely not been pulled from disk into disk/memory cache.</p>\n" }, { "answer_id": 70370487, "author": "Robert Máslo", "author_id": 12636646, "author_profile": "https://Stackoverflow.com/users/12636646", "pm_score": 0, "selected": false, "text": "<p>You must change SQL string. Because SQL string is a cache key.\nFor example, add a timestamp to a SQL comment.</p>\n<p>Function for PHP:</p>\n<pre><code>function db_RunSQL($SQL, $NoCacheMode=false)\n{\n$SQL = (($NoCacheMode) ? '/*'.time().'*/ ' : '') . $SQL;\nreturn mysqli_query(db_SavedConnect(), $SQL);\n}\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm testing the speed of some queries in MySQL. The database is caching these queries making it difficult for me to get reliable results when testing how fast these queries are. Is there a way to disable caching for a query? System: MySQL 4 on Linux webhosting, I have access to PHPMyAdmin. Thanks
Try using the [SQL\_NO\_CACHE](https://dev.mysql.com/doc/refman/5.7/en/query-cache-in-select.html) (MySQL 5.7) option in your query. (MySQL 5.6 users click [HERE](https://dev.mysql.com/doc/refman/5.6/en/query-cache-in-select.html) ) eg. ``` SELECT SQL_NO_CACHE * FROM TABLE ``` This will stop MySQL caching the results, however be aware that other OS and disk caches may also impact performance. These are harder to get around.
181,897
<p>I want to disable "Alert window" that I get from login page of one HTTPS site with "untrusted certificate".</p> <p>ServicePointManager is used for WebRequest/WebResponse:</p> <blockquote> <pre><code>&gt; public static bool &gt; ValidateServerCertificate(object &gt; sender, X509Certificate certificate, &gt; X509Chain chain, SslPolicyErrors &gt; sslPolicyErrors) { &gt; return true; } &gt; &gt; ServicePointManager.ServerCertificateValidationCallback &gt; = new RemoteCertificateValidationCallback(ValidateServerCertificate); </code></pre> </blockquote> <p><strong>but how can I use it with Webbrowser control?</strong></p>
[ { "answer_id": 182184, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>The ServicePointManager is for managed code; WebBrowser is a wrapper around shdocvw, so will almost certainly have a very different programming model.</p>\n\n<p><em>if</em> you can automate this (and I'm not sure that you can), I would expect to have to reference the COM version to get the full API (see: AxWebBrowser). WebBrowser only exposes a .NET-friendly subset of the full functionality - enough to get most common jobs done.</p>\n\n<p>One other option might be to get the data yourself (WebClient / WebRequest / etc), and simply push that html into the WebBrowser - but this will mess up external links etc.</p>\n" }, { "answer_id": 292570, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>As noted by Marc Gravell, I don't believe that it is possible to use ServicePointManager or ServicePoint classes in the WebBrowser Control, nor do you need to though.</p>\n\n<p>See my answer to your other post where you asked your original question.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25826/" ]
I want to disable "Alert window" that I get from login page of one HTTPS site with "untrusted certificate". ServicePointManager is used for WebRequest/WebResponse: > > > ``` > > public static bool > > ValidateServerCertificate(object > > sender, X509Certificate certificate, > > X509Chain chain, SslPolicyErrors > > sslPolicyErrors) { > > return true; } > > > > ServicePointManager.ServerCertificateValidationCallback > > = new RemoteCertificateValidationCallback(ValidateServerCertificate); > > ``` > > **but how can I use it with Webbrowser control?**
The ServicePointManager is for managed code; WebBrowser is a wrapper around shdocvw, so will almost certainly have a very different programming model. *if* you can automate this (and I'm not sure that you can), I would expect to have to reference the COM version to get the full API (see: AxWebBrowser). WebBrowser only exposes a .NET-friendly subset of the full functionality - enough to get most common jobs done. One other option might be to get the data yourself (WebClient / WebRequest / etc), and simply push that html into the WebBrowser - but this will mess up external links etc.
181,901
<p>I try to add an addons system to my Windows.Net application using Reflection; but it fails when there is addon with dependencie.<br><br> Addon class have to implement an interface 'IAddon' and to have an empty constructor.<br> Main program load the addon using Reflection:</p> <pre><code>Assembly assembly = Assembly.LoadFile(@"C:\Temp\TestAddon\Addon.dll"); Type t = assembly.GetType("Test.MyAddon"); ConstructorInfo ctor = t.GetConstructor(new Type[] { }); IAddon addon= (IAddon) ctor.Invoke(new object[] { }); addon.StartAddon(); </code></pre> <p>It works great when addon do not use dependencie. But if my addon reference and use an another DLL (C:\Temp\TestAddon\MyTools.dll) that is saved near the addon in disk, it fails: <br> <em>System.IO.FileNotFoundException: Could not load file or assembly 'MyTools.dll' or one of its dependencies.</em> </p> <p>I do not wants to copy the addons DLL near my executable, how can i do to tell .Net runtime to search in "C:\Temp\TestAddon\" for any dependency?</p> <p>Note that adding </p> <pre><code>Assembly assembly = Assembly.LoadFile(@"C:\Temp\TestAddon\MyTools.dll"); </code></pre> <p>do not change anything.</p>
[ { "answer_id": 181907, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 1, "selected": false, "text": "<p>Couple of options:</p>\n\n<ol>\n<li>You can attach to <code>AppDomain.AssemblyResolve</code> to help the CLR resolve the assembly.</li>\n<li>You could look into isolating add-ins into their own <code>AppDomain</code> (see <code>System.AddIn</code> namespace and <a href=\"http://www.codeplex.com/clraddins\" rel=\"nofollow noreferrer\">this website</a>).</li>\n</ol>\n" }, { "answer_id": 181941, "author": "Andreas Tschager", "author_id": 24467, "author_profile": "https://Stackoverflow.com/users/24467", "pm_score": 7, "selected": true, "text": "<p>If <em>MyTools.dll</em> is located in the same directory as <em>Addon.dll</em>, all you need to do is call <code>Assembly.LoadFrom</code> instead of <code>Assembly.LoadFile</code> to make your code work. Otherwise, handling the <code>AppDomain.AssemblyResolve</code> event is the way to go.</p>\n" }, { "answer_id": 181952, "author": "Chris Canal", "author_id": 5802, "author_profile": "https://Stackoverflow.com/users/5802", "pm_score": 1, "selected": false, "text": "<p>Have you looked into using an <a href=\"http://en.wikipedia.org/wiki/Inversion_of_control\" rel=\"nofollow noreferrer\">Inversion Of Control</a> container? I use Castle Windsor with an external Boo file that lets me easily extend the applcation without having to recompile or worry about supplying dependencies</p>\n" }, { "answer_id": 181988, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "<p>You can use reflection to access the private <em><code>Assembly.</code><strong><code>_GetReferencedAssemblies()</code></strong></em>.</p>\n\n<p>Although, the method <em>could</em> change in a future version of the .NET framework, it doesn't seem likely—ASP.NET heavily depends on it, though it's possible they could move it from <code>mscorlib</code> to <code>System.Web</code> which is the only assembly that I know of from where the method is referred to.</p>\n" }, { "answer_id": 182801, "author": "Olivier de Rivoyre", "author_id": 26071, "author_profile": "https://Stackoverflow.com/users/26071", "pm_score": 1, "selected": false, "text": "<p>Assembly.LoadFrom works well until I try to use a webService in my addon, I had had a \"<em>Unable to cast object of type 'X' to type 'X'</em>\" exception.</p>\n\n<p>It's ugly, but i will use Assembly.LoadFile with the AppDomain.AssemblyResolve.</p>\n\n<p>Thanks guys.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26071/" ]
I try to add an addons system to my Windows.Net application using Reflection; but it fails when there is addon with dependencie. Addon class have to implement an interface 'IAddon' and to have an empty constructor. Main program load the addon using Reflection: ``` Assembly assembly = Assembly.LoadFile(@"C:\Temp\TestAddon\Addon.dll"); Type t = assembly.GetType("Test.MyAddon"); ConstructorInfo ctor = t.GetConstructor(new Type[] { }); IAddon addon= (IAddon) ctor.Invoke(new object[] { }); addon.StartAddon(); ``` It works great when addon do not use dependencie. But if my addon reference and use an another DLL (C:\Temp\TestAddon\MyTools.dll) that is saved near the addon in disk, it fails: *System.IO.FileNotFoundException: Could not load file or assembly 'MyTools.dll' or one of its dependencies.* I do not wants to copy the addons DLL near my executable, how can i do to tell .Net runtime to search in "C:\Temp\TestAddon\" for any dependency? Note that adding ``` Assembly assembly = Assembly.LoadFile(@"C:\Temp\TestAddon\MyTools.dll"); ``` do not change anything.
If *MyTools.dll* is located in the same directory as *Addon.dll*, all you need to do is call `Assembly.LoadFrom` instead of `Assembly.LoadFile` to make your code work. Otherwise, handling the `AppDomain.AssemblyResolve` event is the way to go.
181,912
<p>There is a long running habit here where I work that the connection string lives in the web.config, a Sql Connection object is instantiated in a using block with that connection string and passed to the DataObjects constructor (via a CreateInstance Method as the constructor is private). Something like this:</p> <pre><code>using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString)) { DataObject foo = DataObject.CreateInstance(conn); foo.someProperty = "some value"; foo.Insert(); } </code></pre> <p>This all smells to me.. I don't know. Shouldn't the DataLayer class library be responsible for Connection objects and Connection strings? I'd be grateful to know what others are doing or any good online articles about these kind of design decisions.</p> <p>Consider that the projects we work on are always Sql Server backends and that is extremely unlikely to change. So factory and provider pattern is not what I'm after. It's more about where responsibility lies and where config settings should be managed for data layer operation.</p>
[ { "answer_id": 181925, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 3, "selected": true, "text": "<p>I like to code the classes in my data access layer so that they have one constructor that takes an IDbConnection as a parameter, and another that takes a (connection) string.</p>\n\n<p>That way the calling code can either construct its own SqlConnection and pass it in (handy for integration tests), mock an IDbConnection and pass that in (handy for unit tests) or read a connection string from a configuration file (eg web.config) and pass that in.</p>\n" }, { "answer_id": 181926, "author": "cruizer", "author_id": 6441, "author_profile": "https://Stackoverflow.com/users/6441", "pm_score": 0, "selected": false, "text": "<p>this being a \"smell\" is relative. if you are pretty sure about coupling this particular piece of code to SQL Server and a web.config connection string entry then it's perfectly OK. if you are not into this kind of coupling, I agree that it is a code smell and is undesirable.</p>\n" }, { "answer_id": 181934, "author": "Tetha", "author_id": 17663, "author_profile": "https://Stackoverflow.com/users/17663", "pm_score": 1, "selected": false, "text": "<p>Hm, I think I agree that the datalayer should be responsible for managing such connection strings so the higher layers don't need to worry about this. However, I do not think that the SQLConnection should worry where the connection string comes from.</p>\n\n<p>I think, I would have a datalayer which provides certain DataInputs, that is, things that take a condition and return DataObjects. Such a DataInput now knows \"hey, this DataObjects are stored in THAT Database, and using the Configurations, I can use some connection-string to get an SQL-Connection from over there. </p>\n\n<p>That way you have encapsulated the entire process of \"How and where do the data objects come from?\" and the internals of the datalayer can still be tested properly. (And, as a side effect, you can easily use different databases, or even multiple different databases at the same time. Such flexibility that just pops up is a good sign(tm))</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2083160/" ]
There is a long running habit here where I work that the connection string lives in the web.config, a Sql Connection object is instantiated in a using block with that connection string and passed to the DataObjects constructor (via a CreateInstance Method as the constructor is private). Something like this: ``` using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString)) { DataObject foo = DataObject.CreateInstance(conn); foo.someProperty = "some value"; foo.Insert(); } ``` This all smells to me.. I don't know. Shouldn't the DataLayer class library be responsible for Connection objects and Connection strings? I'd be grateful to know what others are doing or any good online articles about these kind of design decisions. Consider that the projects we work on are always Sql Server backends and that is extremely unlikely to change. So factory and provider pattern is not what I'm after. It's more about where responsibility lies and where config settings should be managed for data layer operation.
I like to code the classes in my data access layer so that they have one constructor that takes an IDbConnection as a parameter, and another that takes a (connection) string. That way the calling code can either construct its own SqlConnection and pass it in (handy for integration tests), mock an IDbConnection and pass that in (handy for unit tests) or read a connection string from a configuration file (eg web.config) and pass that in.
181,928
<p>I have a treeview with nodes like this: "Foo (1234)", and want to allow the user to rename the nodes, but only the Foo part, without (1234). I first tried to change the node text in <code>BeforeLabelEdit</code> like this:</p> <pre><code>private void treeView1_BeforeLabelEdit(object sender, NodeLabelEditEventArgs e) { e.Node.Text = "Foo"; } </code></pre> <p>But when I click the node to edit it, "Foo (1234)" appears in the textbox.</p> <p>Okay, then let's try something else.</p> <p>I set <code>treeView1.LabelEdit</code> to false, and then do the following:</p> <pre><code>private void treeView1_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { if (treeView1.SelectedNode == treeView1.GetNodeAt(e.Location)) { treeView1.SelectedNode.Text = "Foo"; treeView1.LabelEdit = true; treeView1.SelectedNode.BeginEdit(); } } } </code></pre> <p>And then in <code>AfterLabelEdit</code>, I set <code>LabelEdit</code> back to false.</p> <p>And guess what? This doesn't work either. It changes the node text to "Foo" but the edit textbox does not appear.</p> <p>Any ideas? Thanks</p>
[ { "answer_id": 181935, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 2, "selected": false, "text": "<p>Heh - I struck that one a few years back. I even left a <a href=\"https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=94140\" rel=\"nofollow noreferrer\">suggestion on Connect</a> (vote for it!) to allow the label to be changed in BeforeLabelEdit.</p>\n\n<p>One option (in WinForms - it's a different story in WPF) is to use custom painting for your TreeNodes so that the actual label is still \"Foo\" and you custom draw the \" (1234)\" after it. It's a bit of a pain to get right though.</p>\n" }, { "answer_id": 253032, "author": "neo2862", "author_id": 23684, "author_profile": "https://Stackoverflow.com/users/23684", "pm_score": 4, "selected": true, "text": "<p>Finally I have found a <a href=\"http://www.codeproject.com/KB/tree/CustomizedLabelEdit.aspx\" rel=\"noreferrer\">solution</a> to this on <a href=\"http://www.codeproject.com\" rel=\"noreferrer\">CodeProject</a>. Among the comments at the bottom, you will also find a portable solution.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23684/" ]
I have a treeview with nodes like this: "Foo (1234)", and want to allow the user to rename the nodes, but only the Foo part, without (1234). I first tried to change the node text in `BeforeLabelEdit` like this: ``` private void treeView1_BeforeLabelEdit(object sender, NodeLabelEditEventArgs e) { e.Node.Text = "Foo"; } ``` But when I click the node to edit it, "Foo (1234)" appears in the textbox. Okay, then let's try something else. I set `treeView1.LabelEdit` to false, and then do the following: ``` private void treeView1_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { if (treeView1.SelectedNode == treeView1.GetNodeAt(e.Location)) { treeView1.SelectedNode.Text = "Foo"; treeView1.LabelEdit = true; treeView1.SelectedNode.BeginEdit(); } } } ``` And then in `AfterLabelEdit`, I set `LabelEdit` back to false. And guess what? This doesn't work either. It changes the node text to "Foo" but the edit textbox does not appear. Any ideas? Thanks
Finally I have found a [solution](http://www.codeproject.com/KB/tree/CustomizedLabelEdit.aspx) to this on [CodeProject](http://www.codeproject.com). Among the comments at the bottom, you will also find a portable solution.
181,930
<p>We have two Tables:</p> <ul> <li>Document: id, title, document_type_id, showon_id</li> <li>DocumentType: id, name</li> <li>Relationship: DocumentType hasMany Documents. (Document.document_type_id = DocumentType.id)</li> </ul> <p>We wish to retrieve a list of all document types for one given ShowOn_Id. </p> <p>We see two possiblities:</p> <pre><code>SELECT DocumentType.* FROM DocumentType WHERE DocumentType.id IN ( SELECT DISTINCT Document.document_type_id FROM Document WHERE showon_id = 42 ); SELECT DocumentType.* FROM DocumentType WHERE DocumentType.id IN ( SELECT Document.document_type_id FROM Document WHERE showon_id = 42 ); </code></pre> <p>Our question is: when and if is it better to use the DISTINCT to get the smaller record set versus retrieving the whole table and the IN statement walking the table to the first match. (We guess that's what it does ;-))</p> <p>Is this different for different databases, is there a common answer?</p> <p>Or is there a better way of doing it? (We are in .NET land)</p>
[ { "answer_id": 181974, "author": "wmasm", "author_id": 26079, "author_profile": "https://Stackoverflow.com/users/26079", "pm_score": 4, "selected": false, "text": "<p>You can use a join:</p>\n\n<pre><code>SELECT DISTINCT DocumentType.*\nFROM DocumentType\nINNER JOIN Document\nON DocumentType.id=Document.document_type_id\nWHERE Document.showon_id = 42\n</code></pre>\n\n<p>I think it's the best way to do it.</p>\n" }, { "answer_id": 182089, "author": "liggett78", "author_id": 19762, "author_profile": "https://Stackoverflow.com/users/19762", "pm_score": 2, "selected": true, "text": "<p>From my point of view it should not make any difference inside SQL Server (but who knows how this is implemented). </p>\n\n<p>Think of it this way: to return the resultset the server needs to go into the Document table and retrieve all document_type_id WHERE showon_id = 42. In the process of retrieving the document_type_ids (e.g. by index seeking) it puts them into a hash table. When this process has finished the hash table will contain distinct values anyway. After that the query execution goes inside the Document_Type table, scans the primary key and probes into the hash table. Note that this depends, e.g. maybe it's more efficient to not use a hash table, when the expected row count from the Document table it low compared to Document_Type, but in general you get the same query plan as for the query wmasm just suggested.</p>\n" }, { "answer_id": 183155, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 2, "selected": false, "text": "<p>Use an EXISTS. It sometimes is faster, but in my opinion, more readable than a DISTINCT and JOIN. Just for kicks, pls reply with the query plan for this query and the JOIN above, and see if anything is different (they may be optimized down to the same plan). If they are the same, I'd recommend the EXISTS as it is closer to a \"plain language\" description than a JOIN (because you don't want any of the data from Document, etc.)</p>\n\n<pre><code>SELECT whatever\n FROM DocumentType dt\n WHERE EXISTS( SELECT *\n FROM Document \n WHERE dt.id = document_type_id\n AND showon_id = 42)\n</code></pre>\n\n<p>To get the query plan (ref: <a href=\"http://msdn.microsoft.com/en-us/library/ms180765(SQL.90).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms180765(SQL.90).aspx</a>), do:</p>\n\n<pre><code>SET SHOWPLAN_TEXT ON\nGO\n\nSELECT ...\nGO\n</code></pre>\n" }, { "answer_id": 187328, "author": "Ben", "author_id": 5005, "author_profile": "https://Stackoverflow.com/users/5005", "pm_score": 0, "selected": false, "text": "<p>Follow up on <a href=\"https://stackoverflow.com/questions/181930/ms-sql-2k5-performance-distinct-or-full-table-in-where-in-statement#183155\">Matt's answer</a>:</p>\n\n<p>I've enabled the query plan and tested the following four different queries that have come up so far:</p>\n\n<ul>\n<li><p><code>SELECT DocumentType.* FROM DocumentType WHERE DocumentType.id IN (SELECT DISTINCT Document.document_type_id FROM Document WHERE showon_id = 42);</code></p></li>\n<li><p><code>SELECT DocumentType.* FROM DocumentType WHERE DocumentType.id IN (SELECT Document.document_type_id FROM Document WHERE showon_id = 42);</code></p></li>\n<li><p><code>SELECT DISTINCT DocumentType.* FROM DocumentType INNER JOIN Document ON DocumentType.id=Document.document_type_id WHERE Document.showon_id = 42;</code></p></li>\n<li><p><code>SELECT DocumentType.* FROM DocumentType WHERE EXISTS ( SELECT * FROM Document WHERE DocumentType.id=Document.document_type_id AND showon_id = 42);</code></p></li>\n</ul>\n\n<p>The query plan for all four queries turned out to be the same:</p>\n\n<pre><code> |--Hash Match(Right Semi Join, HASH:([Document].[document_type_id])=([DocumentType].[Id]))\n |--Hash Match(Inner Join, HASH:([Document].[Title], [Uniq1005])=([Document].[Title], [Uniq1005]), RESIDUAL:([Document].[Title] as [Document].[Title] = [Document].[Title] as [Document].[Title] AND [Uniq1005] = [Uniq1005]))\n | |--Index Seek(OBJECT:([Document].[IX_Document_3] AS [Document]), SEEK:([Document].[showon_id]=(1)) ORDERED FORWARD)\n | |--Index Scan(OBJECT:([Document].[IX_Document_1] AS [Document]))\n |--Table Scan(OBJECT:([DocumentType] AS [DocumentType]))\n</code></pre>\n\n<p>I am not sure what every line and element means, but it seems that from the performance perspective it does not matter how you construct the query for this kind of problem... </p>\n" }, { "answer_id": 188515, "author": "jjacka", "author_id": 26515, "author_profile": "https://Stackoverflow.com/users/26515", "pm_score": 2, "selected": false, "text": "<p>For the best performance you should use:</p>\n\n<pre><code>SELECT DISTINCT dt.* \nFROM \n DocumentType dt\n INNER JOIN Document d ON dt.id=d.document_type_id and d.showon_id = 42\n</code></pre>\n\n<p>Joins are very efficient at bridging multiple tables where as the nested query in the Where clause will need to perform a separate result selection that will filter down the From clause results. The join statement is also much more readable.</p>\n\n<p>I would also put an index on showon_id, in addition to the primary keys and foreign key relationship.</p>\n\n<p>My answer differs from wmasm's answer only by moving the showon_id filter up to the inner join. For MS SQL 2k5, I think the interpreter is smart enough to do this automatically, but you always want to work with the smallest result set possible. Bringing your filters up to inner join statements can limit the number of rows the query has to work with when joining many tables together. If you do this though, you should understand that this happens for every row comparison so complex filters (such as like x = '%a' or function calls) are better left for the Where clause so that the inner joins may filter out unnecessary comparisons.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5005/" ]
We have two Tables: * Document: id, title, document\_type\_id, showon\_id * DocumentType: id, name * Relationship: DocumentType hasMany Documents. (Document.document\_type\_id = DocumentType.id) We wish to retrieve a list of all document types for one given ShowOn\_Id. We see two possiblities: ``` SELECT DocumentType.* FROM DocumentType WHERE DocumentType.id IN ( SELECT DISTINCT Document.document_type_id FROM Document WHERE showon_id = 42 ); SELECT DocumentType.* FROM DocumentType WHERE DocumentType.id IN ( SELECT Document.document_type_id FROM Document WHERE showon_id = 42 ); ``` Our question is: when and if is it better to use the DISTINCT to get the smaller record set versus retrieving the whole table and the IN statement walking the table to the first match. (We guess that's what it does ;-)) Is this different for different databases, is there a common answer? Or is there a better way of doing it? (We are in .NET land)
From my point of view it should not make any difference inside SQL Server (but who knows how this is implemented). Think of it this way: to return the resultset the server needs to go into the Document table and retrieve all document\_type\_id WHERE showon\_id = 42. In the process of retrieving the document\_type\_ids (e.g. by index seeking) it puts them into a hash table. When this process has finished the hash table will contain distinct values anyway. After that the query execution goes inside the Document\_Type table, scans the primary key and probes into the hash table. Note that this depends, e.g. maybe it's more efficient to not use a hash table, when the expected row count from the Document table it low compared to Document\_Type, but in general you get the same query plan as for the query wmasm just suggested.
181,967
<p>I am currently working on a leave application (which is a subset of my e-scheduler project) and I have my database design as follows:</p> <pre><code>event (event_id, dtstart, dtend... *follows icalendar standard*) event_leave (event_id*, leave_type_id*, total_days) _leave_type (leave_type_id, name, max_carry_forward) _leave_allocation (leave_allocation_id, leave_type_id*, name, user_group_id, total_days, year) _leave_carry_forward(leave_carry_forward_id, leave_type_id*, user_id, year) </code></pre> <p>Does anyone here in stackoverflow also working on an e-leave app? mind to share your database design as I am looking for a better design than mine. The problem with my current design only occurs at the beginning of the year when the system is calculating the number of days that can be carried forward. </p> <p>In total I would have to run 1 + {$number_of users} * 2 queries (the first one to find out the number of allocation rules and the maximum carry forward quota. Then for each user, I need to find out the balance, and then to insert the balance to the database)</p>
[ { "answer_id": 182017, "author": "Dave Mateer", "author_id": 26086, "author_profile": "https://Stackoverflow.com/users/26086", "pm_score": 0, "selected": false, "text": "<p>There is always a better design!! </p>\n\n<p>Does your current design work? How many users do you expect (ie does it matter you would have to run x thousand queries).</p>\n\n<p>If the problem of the current design is only at the beginning of the year then perhaps you could live with it!</p>\n\n<p>Cheers</p>\n\n<p>NZS</p>\n" }, { "answer_id": 182149, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "<p>I'm not following the schema very well (it looks like each leave_type would have a carry forward? There's no user on the event* tables?) but you should be able to dynamically derive the balance at any point in time - including across years. </p>\n\n<p>AAMOF, normalization rules would require you to be able to <em>derive</em> the balance. If you then chose to <em>denormalize</em> for performance is up to you, but the design should support the calculated query. Given that, then calculating the year end carryforward is a single set based query.</p>\n\n<p>Edit: I had to change the schema a bit to accommodate this, and I chose to normalize to make the logic easier - but you can insert denormalization along the way for performance if you need to:</p>\n\n<p>First the tables that are important for this scenario...hopefully my pseudo-syntax will make sense:</p>\n\n<pre><code>User { User_Id (PK) }\n\n// Year may be a tricky business logic issue here...Do you charge the Start or End year\n// if the event crosses a year boundary? Or do you just do 2 different events?\n// You want year in this table, though, so you can do a FK reference to Leave_Allocation\n// Some RDBMS will let you do a FK from a View, though, so you could do that\nEvent { Event_Id (PK), User_Id, Leave_Type_Id, Year, DtStart, DtEnd, ... \n // Ensure that events are charged to leave the user has\n FK (User_Id, Leave_Type_Id, Year)-&gt;Leave_Allocation(User_Id, Leave_Type_Id, Year)\n}\n\nLeave_Type { Leave_Type_Id, Year, Max_Carry_Forward \n // Max_Carry_Forward would probably change per year\n PK (Leave_Type_Id, Year)\n}\n\n// Starting balance for each leave_type and user, per year\n// Not sure the name makes the most sense - I think of Allocated as used leave,\n// so I'd probably call this Leave_Starting_Balance or something\nLeave_Allocation { Leave_Type_Id (FK-&gt;Leave_Type.Leave_Type_Id), User_Id (FK-&gt;User.User_Id), Year, Total_Days \n PK (Leave_Type_Id, User_Id, Year)\n // Ensure that leave_type is defined for this year\n FK (Leave_Type_Id, Year)-&gt;Leave_Type(Leave_Type_Id, Year)\n}\n</code></pre>\n\n<p>And then, the views (which is where you may want to apply some denormalization):</p>\n\n<pre><code>/* Just sum up the Total_Days for an event to make some other calcs easier */\nCREATE VIEW Event_Leave AS\n SELECT\n Event_Id,\n User_Id,\n Leave_Type_Id,\n DATEDIFF(d, DtEnd, DtStart) as Total_Days,\n Year\n FROM Event\n\n/* Subtract sum of allocated leave (Event_Leave.Total_Days) from starting balance (Leave_Allocation) */\n/* to get the current unused balance of leave */\nCREATE VIEW Leave_Current_Balance AS\n SELECT\n Leave_Allocation.User_Id,\n Leave_Allocation.Leave_Type_Id,\n Leave_Allocation.Year,\n Leave_Allocation.Total_Days - SUM(Event_Leave.Total_Days) as Leave_Balance\n FROM Leave_Allocation\n LEFT OUTER JOIN Event_Leave ON\n Leave_Allocation.User_Id = Event_Leave.User_Id\n AND Leave_Allocation.Leave_Type_Id = Event_Leave.Leave_Type_Id\n AND Leave_Allocation.Year = Event_Leave.Year\n GROUP BY\n Leave_Allocation.User_Id,\n Leave_Allocation.Leave_Type_Id,\n Leave_Allocation.Year,\n Leave_Allocation.Total_Days\n</code></pre>\n\n<p>Now, our Leave CarryForward query is just the minimum of current balance or maximum carryforward as of midnight on 1/1.</p>\n\n<pre><code> SELECT\n User_Id,\n Leave_Type_Id,\n Year,\n /* This is T-SQL syntax...your RDBMS may be different, but should be able to do the same thing */\n /* If not, you'd do a UNION ALL to Max_Carry_Forward and select MIN(BalanceOrMax) */\n CASE \n WHEN Leave_Balance &lt; Max_Carry_Forward \n THEN Leave_Balance \n ELSE \n Max_Carry_Forward \n END as Leave_Carry_Forward\n FROM Leave_Current_Balance\n JOIN Leave_Type ON\n Leave_Current_Balance.Leave_Type_Id = Leave_Type.Leave_Type_Id\n /* This assumes max_carry_forward is how much you can carry_forward into the next year */\n /* eg,, a max_carry_forward of 300 hours for year 2008, means I can carry_forward up to 300 */\n /* hours into 2009. Otherwise, you'd join on Leave_Current_Balance.Year + 1 if it's how much */\n /* I can carry forward into *this* year. */\n AND Leave_Current_Balance.Year = Leave_Type.Year\n</code></pre>\n\n<p>So, at the end of the year, you'd insert the CarryForward balances back into LeaveAllocation with the new year.</p>\n" }, { "answer_id": 185657, "author": "Jeffrey04", "author_id": 5742, "author_profile": "https://Stackoverflow.com/users/5742", "pm_score": 0, "selected": false, "text": "<p>Further notes on my database design and some use cases.</p>\n\n<h1>Table Design</h1>\n\n<p>This is the main table (basically based on iCalendar schema) that stores event. The event may be a typical event, or a meeting, public holiday etc.</p>\n\n<pre><code>event (event_id (PK), dtstart, dtend, ... --other icalendar fields--)\n</code></pre>\n\n<p>If a particular type of event has extra information that I have to keep track, I decorate it with another table. For instance, the table to store e-leave specific information. (total_days is not a computed field as part of the requirements)</p>\n\n<pre><code>event_leave (event_id (PK/FK-&gt;event), total_days, leave_type_id (FK-&gt;leave_type))\n</code></pre>\n\n<p>Leave type table stores some information on each leave type. For instance, does the application needs approval/recommendation etc. Besides that, it also stores the maximum carry forward allowed. I assume the maximum carry forward would not be altered frequently.</p>\n\n<pre><code>leave_type (leave_type_id (PK), name, require_support, require_recommend, max_carry_forward)\n</code></pre>\n\n<p>Users are divided into groups, and each group will be given a number of days available for leave for <strong>some</strong> of the leave_type. Data stored in this table will be populated annually (a new revision for each year). It only stores the number of leave given for each <strong>group</strong>, not per user.</p>\n\n<pre><code>leave_allocation (leave_allocation_id, year(PK), leave_type_id (PK/FK-&gt;leave_type), total_days, group_id)\n</code></pre>\n\n<p>Next is the table to store carry forward information. This table will be populated once every year <strong>for each user</strong>. This table will be populated once a year as calculation on the fly is not easy. The formula of counting leave_carry_forward for the user is:</p>\n\n<pre><code>leave_carry_forward(2009) = min(leave_allocation(2008) + leave_carry_forward(2007) - leave_taken(2008), maximum_carry_forward());\n\nleave_carry_forward (leave_carry_forward_id, user_id, year, total_days)\n</code></pre>\n\n<h1>Some Example Use Cases and Solution</h1>\n\n<h2>Calculate Balance (WIP)</h2>\n\n<p>To calculate balance, I make a query to the view declared as follows</p>\n\n<pre><code>DROP VIEW IF EXISTS leave_remaining_days;\nCREATE OR REPLACE VIEW leave_remaining_days AS\n SELECT year, user_id, leave_type_id, SUM(total_days) as total_days\n FROM (\n SELECT allocated.year, usr.uid AS \"user_id\", allocated.leave_type_id, \n allocated.total_days\n FROM users usr\n JOIN app_event._leave_allocation allocated\n ON allocated.group_id = usr.group_id\n UNION\n SELECT EXTRACT(year FROM event.dtstart) AS \"year\", event.user_id, \n leave.leave_type_id, leave.total_days * -1 AS total_days\n FROM app_event.event event\n LEFT JOIN app_event.event_leave leave\n ON event.event_id = leave.event_id\n UNION\n SELECT year, user_id, leave_type_id, total_days\n FROM app_event._leave_carry_forward\n ) KKR\n GROUP BY year, user_id, leave_type_id;\n</code></pre>\n\n<h2>Populate leave_allocation table at the beginning of year</h2>\n\n<pre><code>public function populate_allocation($year) {\n return $this-&gt;db-&gt;query(sprintf(\n 'INSERT INTO %s (%s)' .\n \"SELECT '%s' AS year, %s \" .\n 'FROM %s ' .\n 'WHERE \"year\" = %s',\n 'event_allocation',\n 'year, leave_type_id, total_days ...', //(all the fields in the table)\n empty($year) ? date('Y') : $year,\n 'leave_type_id, total_days, ..', //(all fields except year)\n $this-&gt;__table,\n empty($year) ? date('Y') - 1 : $year - 1\n ))\n -&gt;count() &gt; 0; // using the database query builder in Kohana PHP framework\n}\n</code></pre>\n\n<h2>Populate leave_carry_forward table at the beginning of year</h2>\n\n<h3>Find out leave type assigned to the user</h3>\n\n<p>I would probably need to rename this view (I am bad in naming stuff...). It is actually a leave_allocation table for a user.</p>\n\n<pre><code>DROP VIEW IF EXISTS user_leave_type;\nCREATE OR REPLACE VIEW user_leave_type AS\n SELECT la.year, usr.uid AS user_id, lt.leave_type_id, lt.max_carry_forward\n FROM users usr\n JOIN app_event._leave_allocation la\n JOIN app_event._leave_type lt\n ON la.leave_type_id = lt.leave_type_id\n ON usr.group_id = la.group_id\n</code></pre>\n\n<h3>The actual query</h3>\n\n<pre><code>INSERT INTO leave_carry_forward (year, user_id, leave_type_id, total_days)\n SELECT '{$this_year}' AS year, user_id, leave_type_id, MIN(carry_forward) AS total_days\n FROM (\n SELECT year, user_id, leave_type_id, total_days AS carry_forward\n FROM leave_remaining_days\n UNION\n SELECT year, user_id, leave_type_id, max_carry_forward AS carry_forward\n FROM user_leave_type\n ) KKR\n WHERE year = {$last_year}\n GROUP BY year, user_id, leave_type_id;\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5742/" ]
I am currently working on a leave application (which is a subset of my e-scheduler project) and I have my database design as follows: ``` event (event_id, dtstart, dtend... *follows icalendar standard*) event_leave (event_id*, leave_type_id*, total_days) _leave_type (leave_type_id, name, max_carry_forward) _leave_allocation (leave_allocation_id, leave_type_id*, name, user_group_id, total_days, year) _leave_carry_forward(leave_carry_forward_id, leave_type_id*, user_id, year) ``` Does anyone here in stackoverflow also working on an e-leave app? mind to share your database design as I am looking for a better design than mine. The problem with my current design only occurs at the beginning of the year when the system is calculating the number of days that can be carried forward. In total I would have to run 1 + {$number\_of users} \* 2 queries (the first one to find out the number of allocation rules and the maximum carry forward quota. Then for each user, I need to find out the balance, and then to insert the balance to the database)
I'm not following the schema very well (it looks like each leave\_type would have a carry forward? There's no user on the event\* tables?) but you should be able to dynamically derive the balance at any point in time - including across years. AAMOF, normalization rules would require you to be able to *derive* the balance. If you then chose to *denormalize* for performance is up to you, but the design should support the calculated query. Given that, then calculating the year end carryforward is a single set based query. Edit: I had to change the schema a bit to accommodate this, and I chose to normalize to make the logic easier - but you can insert denormalization along the way for performance if you need to: First the tables that are important for this scenario...hopefully my pseudo-syntax will make sense: ``` User { User_Id (PK) } // Year may be a tricky business logic issue here...Do you charge the Start or End year // if the event crosses a year boundary? Or do you just do 2 different events? // You want year in this table, though, so you can do a FK reference to Leave_Allocation // Some RDBMS will let you do a FK from a View, though, so you could do that Event { Event_Id (PK), User_Id, Leave_Type_Id, Year, DtStart, DtEnd, ... // Ensure that events are charged to leave the user has FK (User_Id, Leave_Type_Id, Year)->Leave_Allocation(User_Id, Leave_Type_Id, Year) } Leave_Type { Leave_Type_Id, Year, Max_Carry_Forward // Max_Carry_Forward would probably change per year PK (Leave_Type_Id, Year) } // Starting balance for each leave_type and user, per year // Not sure the name makes the most sense - I think of Allocated as used leave, // so I'd probably call this Leave_Starting_Balance or something Leave_Allocation { Leave_Type_Id (FK->Leave_Type.Leave_Type_Id), User_Id (FK->User.User_Id), Year, Total_Days PK (Leave_Type_Id, User_Id, Year) // Ensure that leave_type is defined for this year FK (Leave_Type_Id, Year)->Leave_Type(Leave_Type_Id, Year) } ``` And then, the views (which is where you may want to apply some denormalization): ``` /* Just sum up the Total_Days for an event to make some other calcs easier */ CREATE VIEW Event_Leave AS SELECT Event_Id, User_Id, Leave_Type_Id, DATEDIFF(d, DtEnd, DtStart) as Total_Days, Year FROM Event /* Subtract sum of allocated leave (Event_Leave.Total_Days) from starting balance (Leave_Allocation) */ /* to get the current unused balance of leave */ CREATE VIEW Leave_Current_Balance AS SELECT Leave_Allocation.User_Id, Leave_Allocation.Leave_Type_Id, Leave_Allocation.Year, Leave_Allocation.Total_Days - SUM(Event_Leave.Total_Days) as Leave_Balance FROM Leave_Allocation LEFT OUTER JOIN Event_Leave ON Leave_Allocation.User_Id = Event_Leave.User_Id AND Leave_Allocation.Leave_Type_Id = Event_Leave.Leave_Type_Id AND Leave_Allocation.Year = Event_Leave.Year GROUP BY Leave_Allocation.User_Id, Leave_Allocation.Leave_Type_Id, Leave_Allocation.Year, Leave_Allocation.Total_Days ``` Now, our Leave CarryForward query is just the minimum of current balance or maximum carryforward as of midnight on 1/1. ``` SELECT User_Id, Leave_Type_Id, Year, /* This is T-SQL syntax...your RDBMS may be different, but should be able to do the same thing */ /* If not, you'd do a UNION ALL to Max_Carry_Forward and select MIN(BalanceOrMax) */ CASE WHEN Leave_Balance < Max_Carry_Forward THEN Leave_Balance ELSE Max_Carry_Forward END as Leave_Carry_Forward FROM Leave_Current_Balance JOIN Leave_Type ON Leave_Current_Balance.Leave_Type_Id = Leave_Type.Leave_Type_Id /* This assumes max_carry_forward is how much you can carry_forward into the next year */ /* eg,, a max_carry_forward of 300 hours for year 2008, means I can carry_forward up to 300 */ /* hours into 2009. Otherwise, you'd join on Leave_Current_Balance.Year + 1 if it's how much */ /* I can carry forward into *this* year. */ AND Leave_Current_Balance.Year = Leave_Type.Year ``` So, at the end of the year, you'd insert the CarryForward balances back into LeaveAllocation with the new year.
181,986
<p>Every software development professional (and especially project managers) has to deal with a never ending stream of e-mails. What is the best way of organising them in MS Outlook?</p> <p>Obviously some fancy issue tracking tools give more flexibility but I am interested in plain vanilla approach that can be deployed within most organisations. </p> <p>P.S. Finding e-mails is generally the least of the problems that needs to be addressed. Search nowdays is pretty good.</p>
[ { "answer_id": 181995, "author": "tloach", "author_id": 14092, "author_profile": "https://Stackoverflow.com/users/14092", "pm_score": 2, "selected": false, "text": "<p>any email that is auto-generated gets auto-filtered to its own folder. Separate folders for each project, and more for HR and general company junk. Basically the inbox should only contain things that need responses, once responded to messages move into a folder.</p>\n" }, { "answer_id": 181996, "author": "Jarod Elliott", "author_id": 1061, "author_profile": "https://Stackoverflow.com/users/1061", "pm_score": 0, "selected": false, "text": "<p>Folders! Nice and simple.</p>\n\n<p>I have found these to be invaluable over the years to help organise a separate emails on a customer or project basis. Even when there's multiple parties involved i only have to look in 2 folders at most to find what i'm after.</p>\n\n<p>Edit: Similar to what tloach said, i use the inbox essentailly as a todo list of things i still need to look at.</p>\n" }, { "answer_id": 181997, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 0, "selected": false, "text": "<p>1 folder per project.<br>\n1 folder for personal mails.<br>\n1 folder for support.</p>\n\n<p>Inbox for most other things.</p>\n\n<p>I usually set up rules to auto-direct mail into the right folders.</p>\n" }, { "answer_id": 182015, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 1, "selected": false, "text": "<p>Install <a href=\"http://www.lockergnome.com/windows/2004/07/26/microsoft-lookout-for-outlook/\" rel=\"nofollow noreferrer\">LookOut</a>, leave everything in the Inbox and just search for stuff.</p>\n\n<p>Ok, maybe do <em>some</em> organisation, but LookOut is pretty good, and the better the search, the less manual organisation you have to do, and that is a Good Thing, IMO.</p>\n" }, { "answer_id": 182030, "author": "Unsliced", "author_id": 2902, "author_profile": "https://Stackoverflow.com/users/2902", "pm_score": 0, "selected": false, "text": "<p>Files and folders, auto-filtering and a small inbox (i.e. <a href=\"http://www.43folders.com/izero\" rel=\"nofollow noreferrer\">Inbox Zero</a>) are all good practices, but ultimately it's all about being able to find emails when you need them and for that there's only one answer for Outlook at the moment. </p>\n\n<p>Install <a href=\"http://www.xobni.com/\" rel=\"nofollow noreferrer\">Xobni</a>. </p>\n" }, { "answer_id": 182049, "author": "Osama Al-Maadeed", "author_id": 25544, "author_profile": "https://Stackoverflow.com/users/25544", "pm_score": 0, "selected": false, "text": "<p>I use <a href=\"http://www.microsoft.com/windows/products/winfamily/desktopsearch/default.mspx\" rel=\"nofollow noreferrer\">Windows Desktop Search</a>.</p>\n\n<p>I have a huge offline PST where I move everything, and I can easily find anything by searching.</p>\n" }, { "answer_id": 182062, "author": "Shoban", "author_id": 12178, "author_profile": "https://Stackoverflow.com/users/12178", "pm_score": 1, "selected": false, "text": "<p>i use folders!!! we usually get tasks which have unique number!! so folders are named after task numbers!!</p>\n\n<p>Finished task's folders move to archive!! simple and yet powerful! I found it useful and following it for the past 3+years</p>\n" }, { "answer_id": 182085, "author": "Dror Helper", "author_id": 11361, "author_profile": "https://Stackoverflow.com/users/11361", "pm_score": 0, "selected": false, "text": "<ul>\n<li>Use folders - one for each subject ex. project X, Marketing, Personal, TODO etc.</li>\n<li>I use Xobni as well to quickly find emails from specific sender.</li>\n<li>Two \"Special\" folders: \"Inbox\" for emails sent to me and \"Inbox-CC\" for emails I'm CC'd. New emails arrive to one of those folders and then I decide where to store them.</li>\n</ul>\n" }, { "answer_id": 182097, "author": "Dave Van den Eynde", "author_id": 455874, "author_profile": "https://Stackoverflow.com/users/455874", "pm_score": 1, "selected": false, "text": "<p>I simply have two folders: my inbox, and a subfolder called \"archive\". My inbox is my todo-list. If any message needs further attention, or has some action that needs to be completed, or I'm waiting for an answer for something, it stays in the inbox. If it's handled, I move it to the archive.</p>\n\n<p>Therefore, if it's in the inbox, it reminds me of the stuff that I still need to do everytime I check my e-mail.</p>\n\n<p>Search indexing in Outlook with Vista makes searching through e-mails just as much fun as it is with Google Mail, so you can apply the same strategy as they did. Why delete an e-mail? </p>\n\n<p>Also, I turn off auto-archiving and keep all e-mails local with me.</p>\n" }, { "answer_id": 182146, "author": "RichS", "author_id": 6247, "author_profile": "https://Stackoverflow.com/users/6247", "pm_score": 1, "selected": false, "text": "<p>I use the same principles as this GTD article - <a href=\"http://lifehacker.com/software/geek-to-live/getting-things-done-with-google-notebook-256844.php\" rel=\"nofollow noreferrer\">link text</a></p>\n\n<p>Essentially, I keep my Inbox clear, and move everything to the folders as mentioned in the article. Search is good enough these days that you don't need endless sub-folders.</p>\n" }, { "answer_id": 182228, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 1, "selected": false, "text": "<p>Everybody seems to suggest folders; I suggest Categories.</p>\n\n<p>I have 1 active pst and 1 pst per archived year, every mail is assigned one or more categories. Adjust folder view to group by category.</p>\n\n<p>The main advantage is that you can assign several categories to a single mail.</p>\n\n<p>Everything that still needs attention is in the inbox without categories.</p>\n\n<p>Oh yes, and Rules! As already mentioned, rules for automated emails, as well as a rule for known senders, which files incoming mail into a special inbox folder.</p>\n" }, { "answer_id": 182337, "author": "Paul Woodward", "author_id": 16894, "author_profile": "https://Stackoverflow.com/users/16894", "pm_score": 2, "selected": false, "text": "<p>I keep anything that needs my attention in my Inbox and move everything completed to my Saved Folder.</p>\n\n<p>I have just started using Categories as of Monday and I think they are something that more people need to be aware of.</p>\n\n<p>I have a few rules which detect Project Names from the Subject and auto assign to the correct Category with my Inbox set to Group by Category.</p>\n\n<p>Finally I use Google Desktop for Searching - much quicker and easier although does not like me moving my messages to my Saved Folder.</p>\n" }, { "answer_id": 195942, "author": "Stephen Bailey", "author_id": 15385, "author_profile": "https://Stackoverflow.com/users/15385", "pm_score": 2, "selected": false, "text": "<p>Depending on the amt of mail you receive I have 2 strategies that can be used together:</p>\n\n<p>1) <strong>As most people suggest above, use your inbox as your todo list, and keep it clean. have 1 folder for Archived mails, and use all the search tools for searching!</strong></p>\n\n<p>2) <strong>If you get HUGE amts of mail, then use a filter to move mails that you are only CC'ed on to another folder. Then only check that folder N times a day ( I used N=3, morning, lunch &amp; home time )</strong></p>\n\n<p>You will be amazed how much time it saves you, esp if you find that you feel drawn to reading mails that are in your Inbox trying to keep you Inbox clean.</p>\n\n<p>This stop non-urgent mails from disrupting your flow, and is just quicker because you can now read the entire thread of the conversion by the people who were in the TO list. </p>\n\n<p>HTH</p>\n" }, { "answer_id": 195968, "author": "Scott James", "author_id": 6715, "author_profile": "https://Stackoverflow.com/users/6715", "pm_score": 4, "selected": true, "text": "<p>Within my main inbox I have 3 sub folers: Do, Done, Defer and 3 macros to move the selected folder into the relevent folder. (alt-1 moves the selected mail to done and then selects the next mail). Each day I quickly filter my inbox into the three folders. I can process several hundred mails in 20 mins or so.</p>\n\n<p>Do, something I expect to process today.\nDone, something I don't care about/have read and understood, I dont expect to refer back to these today.\nDefer, something I will do something about but not today.</p>\n\n<p>At the end of processing I expect my inbox to be empty. </p>\n\n<p>At the end of the day all mail items in Do move to Defer (I dont want to keep things in \nDone overnight).</p>\n\n<p>At the start of the day all items in Defer are filtered using the rules above, I dont want to leave things in Defer for more then a day or 2. If stuff hangs around for too long I will add it to my diary to process later.</p>\n\n<p>At the end of the day all mail in Done is copied into an archive folder based on the month/year. Done is just a parking place for things to be archived.</p>\n\n<p>I use a tool to index my archive, I actually use X1 but google desktop is an excellent alternative.</p>\n\n<p>I filter out any important facts i would like to refer back to in outlook notes.</p>\n\n<p>I filter out any tasks I would like to recal into omni focus (<a href=\"http://www.omnigroup.com/applications/omnifocus/\" rel=\"noreferrer\">http://www.omnigroup.com/applications/omnifocus/</a>) the best GTD I have found.</p>\n\n<p>I DO NOT EVER use my inbox as a todo list or a mechanism for recording subtle facts I want to recall later. I know a lot of people do but IMHO its just a bad way to be. </p>\n\n<p>(cross posted to LJ).</p>\n\n<p>EDIT.</p>\n\n<p>Oh per a post above I also filter any mail not posted to me directly, by the mailing list the mail was sent to. I give different amounts of attention to each mailing list. I do follow the mechanism above for each mailing list but some I glance at and some I process in detail.</p>\n\n<p>ReEDIT</p>\n\n<p>In comments I was asked to provide the source for the macros I mentioned above. I DONT suggest this is seen as an example of good VBA, I am pretty sure it was sourced from the interweb and adapted for my purposes. It has worked reliably for many years.</p>\n\n<pre><code>Sub MoveToDone()\n On Error Resume Next\n\n Dim objFolder As Outlook.MAPIFolder, objInbox As Outlook.MAPIFolder\n Dim objNS As Outlook.NameSpace, objItem As Outlook.MailItem\n\n Set objNS = Application.GetNamespace(\"MAPI\")\n Set objInbox = objNS.GetDefaultFolder(olFolderInbox)\n Set objFolder = objInbox.Folders(\"Done\")\n\n 'Assume this is a mail folder\n\n If objFolder Is Nothing Then\n MsgBox \"This folder doesn't exist!\", vbOKOnly + vbExclamation, \"INVALID FOLDER\"\n End If\n\n If Application.ActiveExplorer.Selection.Count = 0 Then\n 'Require that this procedure be called only when a message is selected\n MsgBox \"No msgs selected\", vbOKOnly + vbExclamation, \"NO_MSG_SELECTED\"\n Exit Sub\n End If\n\n For Each objItem In Application.ActiveExplorer.Selection\n If objFolder.DefaultItemType = olMailItem Then\n If objItem.Class = olMail Then\n objItem.Move objFolder\n End If\n End If\n Next\n\n\n Set objItem = Nothing\n Set objFolder = Nothing\n Set objInbox = Nothing\n Set objNS = Nothing\n\nEnd Sub\n</code></pre>\n" }, { "answer_id": 201588, "author": "Mark Nold", "author_id": 4134, "author_profile": "https://Stackoverflow.com/users/4134", "pm_score": 0, "selected": false, "text": "<p>Merlin Mann has spent a load of time exploring this as <a href=\"http://www.43folders.com/izero\" rel=\"nofollow noreferrer\">Inbox Zero</a>. There's a great video <a href=\"http://video.google.com/videoplay?docid=973149761529535925&amp;hl=en\" rel=\"nofollow noreferrer\">presentation at Google</a> which is well worthwhile watching.</p>\n" }, { "answer_id": 234240, "author": "aesdanae", "author_id": 26198, "author_profile": "https://Stackoverflow.com/users/26198", "pm_score": 0, "selected": false, "text": "<p>I'm an extreme sorter and have had an interesting time reorganizing my boss's email patterns - she gets 500 emails per day. After spam. And requires that all of her email remain in Outlook (meaning transferring, say, emails form 2001 into an archive file is out). It's still an organic process, but the most effective, and most easily adopted by her, have been to:</p>\n\n<p>1) Use folders to separate functional areas. For example: A Company or Work folder containing Contracts (with a subfolder for each active contract), Business Development (proposals/leads), and Personal Development (education and conference materials, receipts, etc). Outside of the Company folder is a Personal folder for non-work related emails. </p>\n\n<p>My only rule of thumb is embrace the use of folders, but don't go crazy with the subfolders. It's one thing to separate your M&amp;Ms from your Snickers and Dairy Milks, another to separate the colors of your M&amp;Ms.</p>\n\n<p>2) Categories suck. They are not labels or tags. They are deficient. That said, there's little else that can help you highlight/color emails except maybe flags in Outlook 2003. I have a rule set up to categories any email that is sent from other employees within the company, so they don't get overlooked.</p>\n\n<p>Once that's done: Rules, Rules, Rules. I haven't found a limit. I've got all manner of highly refined Spam filters first, followed by News filters that move all the lists and newsletters and RFP announcements to a news folder and mark them as read (unread messages denote priority and require attention; news is optional - it's procrastination, not work). Then there is a rule for each contract filtering any email from the customer domain to the appropriate contract folder.</p>\n\n<p>And of course I would say read <a href=\"http://www.43folders.com/izero\" rel=\"nofollow noreferrer\">Inbox Zero</a> (specifically <a href=\"http://www.43folders.com/2006/03/14/delete\" rel=\"nofollow noreferrer\">this one</a>) and <a href=\"http://zenhabits.net/2007/01/email-zen-clear-out-your-inbox/\" rel=\"nofollow noreferrer\" title=\"Email Zen\">Email Zen</a> and take what nuggets of goodness mean the most to you before proceeding.</p>\n" }, { "answer_id": 234275, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 0, "selected": false, "text": "<p>I just keep it all in my Inbox and let it auto-archive. That way I can sort and search the Inbox to find anything. Google Desktop Search helps too.</p>\n\n<p>I know some people who fastidiously reassign their emails into a huge hierarchy of folders. They can never find anything more than 2 days old! \"Maybe I put it under Project X; no, maybe under Oracle Issues; no, ...\"</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22088/" ]
Every software development professional (and especially project managers) has to deal with a never ending stream of e-mails. What is the best way of organising them in MS Outlook? Obviously some fancy issue tracking tools give more flexibility but I am interested in plain vanilla approach that can be deployed within most organisations. P.S. Finding e-mails is generally the least of the problems that needs to be addressed. Search nowdays is pretty good.
Within my main inbox I have 3 sub folers: Do, Done, Defer and 3 macros to move the selected folder into the relevent folder. (alt-1 moves the selected mail to done and then selects the next mail). Each day I quickly filter my inbox into the three folders. I can process several hundred mails in 20 mins or so. Do, something I expect to process today. Done, something I don't care about/have read and understood, I dont expect to refer back to these today. Defer, something I will do something about but not today. At the end of processing I expect my inbox to be empty. At the end of the day all mail items in Do move to Defer (I dont want to keep things in Done overnight). At the start of the day all items in Defer are filtered using the rules above, I dont want to leave things in Defer for more then a day or 2. If stuff hangs around for too long I will add it to my diary to process later. At the end of the day all mail in Done is copied into an archive folder based on the month/year. Done is just a parking place for things to be archived. I use a tool to index my archive, I actually use X1 but google desktop is an excellent alternative. I filter out any important facts i would like to refer back to in outlook notes. I filter out any tasks I would like to recal into omni focus (<http://www.omnigroup.com/applications/omnifocus/>) the best GTD I have found. I DO NOT EVER use my inbox as a todo list or a mechanism for recording subtle facts I want to recall later. I know a lot of people do but IMHO its just a bad way to be. (cross posted to LJ). EDIT. Oh per a post above I also filter any mail not posted to me directly, by the mailing list the mail was sent to. I give different amounts of attention to each mailing list. I do follow the mechanism above for each mailing list but some I glance at and some I process in detail. ReEDIT In comments I was asked to provide the source for the macros I mentioned above. I DONT suggest this is seen as an example of good VBA, I am pretty sure it was sourced from the interweb and adapted for my purposes. It has worked reliably for many years. ``` Sub MoveToDone() On Error Resume Next Dim objFolder As Outlook.MAPIFolder, objInbox As Outlook.MAPIFolder Dim objNS As Outlook.NameSpace, objItem As Outlook.MailItem Set objNS = Application.GetNamespace("MAPI") Set objInbox = objNS.GetDefaultFolder(olFolderInbox) Set objFolder = objInbox.Folders("Done") 'Assume this is a mail folder If objFolder Is Nothing Then MsgBox "This folder doesn't exist!", vbOKOnly + vbExclamation, "INVALID FOLDER" End If If Application.ActiveExplorer.Selection.Count = 0 Then 'Require that this procedure be called only when a message is selected MsgBox "No msgs selected", vbOKOnly + vbExclamation, "NO_MSG_SELECTED" Exit Sub End If For Each objItem In Application.ActiveExplorer.Selection If objFolder.DefaultItemType = olMailItem Then If objItem.Class = olMail Then objItem.Move objFolder End If End If Next Set objItem = Nothing Set objFolder = Nothing Set objInbox = Nothing Set objNS = Nothing End Sub ```
181,994
<p>In order to verify the data coming from the <a href="http://code.google.com/apis/safebrowsing/developers_guide.html" rel="nofollow noreferrer">Google Safe Browsing API</a>, you can calculate a Message Authentication Code (MAC) for each update. The instructions to do this (from Google) are:</p> <blockquote> <p>The MAC is computed from an MD5 Digest over the following information: client_key|separator|table data|separator|client_key. The separator is the string:coolgoog: - that is a colon followed by "coolgoog" followed by a colon. The resulting 128-bit MD5 digest is websafe base-64 encoded.</p> </blockquote> <p>There's also example data to check against:</p> <pre><code>client key: "8eirwN1kTwCzgWA2HxTaRQ==" </code></pre> <p>response:</p> <pre><code>[goog-black-hash 1.180 update][mac=dRalfTU+bXwUhlk0NCGJtQ==] +8070465bdf3b9c6ad6a89c32e8162ef1 +86fa593a025714f89d6bc8c9c5a191ac +bbbd7247731cbb7ec1b3a5814ed4bc9d *Note that there are tabs at the end of each line. </code></pre> <p>I'm unable to get a match. Please either point out where I'm going wrong, or just write the couple of lines of Python code necessary to do this!</p> <p>FWIW, I expected to be able to do something like this:</p> <pre><code>&gt;&gt;&gt; s = "+8070465bdf3b9c6ad6a89c32e8162ef1\t\n+86fa593a025714f89d6bc8c9c5a191ac\t\n+bbbd7247731cbb7ec1b3a5814ed4bc9d\t" &gt;&gt;&gt; c = "8eirwN1kTwCzgWA2HxTaRQ==" &gt;&gt;&gt; hashlib.md5("%s%s%s%s%s" % (c, ":coolgoog:", s, ":coolgoog:", c)).digest().encode("base64") 'qfb50mxpHrS82yTofPkcEg==\n' </code></pre> <p>But as you can see, 'qfb50mxpHrS82yTofPkcEg==\n' != 'dRalfTU+bXwUhlk0NCGJtQ=='.</p>
[ { "answer_id": 182099, "author": "Anders Waldenborg", "author_id": 24082, "author_profile": "https://Stackoverflow.com/users/24082", "pm_score": 2, "selected": true, "text": "<pre><code>c=\"8eirwN1kTwCzgWA2HxTaRQ==\".decode('base64')\n</code></pre>\n" }, { "answer_id": 184617, "author": "Tony Meyer", "author_id": 4966, "author_profile": "https://Stackoverflow.com/users/4966", "pm_score": 2, "selected": false, "text": "<p>Anders' answer gives the necessary information, but isn't that clear: the client key needs to be decoded before it is combined. (The example above is also missing a newline at the end of the final table data).</p>\n\n<p>So the working code is:</p>\n\n<pre><code>&gt;&gt;&gt; s = \"+8070465bdf3b9c6ad6a89c32e8162ef1\\t\\n+86fa593a025714f89d6bc8c9c5a191ac\\t\\n+bbbd7247731cbb7ec1b3a5814ed4bc9d\\t\\n\"\n&gt;&gt;&gt; c = \"8eirwN1kTwCzgWA2HxTaRQ==\".decode('base64') \n&gt;&gt;&gt; hashlib.md5(\"%s%s%s%s%s\" % (c, \":coolgoog:\", s, \":coolgoog:\", c)).digest().encode(\"base64\")\n'dRalfTU+bXwUhlk0NCGJtQ==\\n'\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/181994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4966/" ]
In order to verify the data coming from the [Google Safe Browsing API](http://code.google.com/apis/safebrowsing/developers_guide.html), you can calculate a Message Authentication Code (MAC) for each update. The instructions to do this (from Google) are: > > The MAC is computed from an MD5 Digest > over the following information: > client\_key|separator|table > data|separator|client\_key. The > separator is the string:coolgoog: - > that is a colon followed by "coolgoog" > followed by a colon. The resulting > 128-bit MD5 digest is websafe base-64 > encoded. > > > There's also example data to check against: ``` client key: "8eirwN1kTwCzgWA2HxTaRQ==" ``` response: ``` [goog-black-hash 1.180 update][mac=dRalfTU+bXwUhlk0NCGJtQ==] +8070465bdf3b9c6ad6a89c32e8162ef1 +86fa593a025714f89d6bc8c9c5a191ac +bbbd7247731cbb7ec1b3a5814ed4bc9d *Note that there are tabs at the end of each line. ``` I'm unable to get a match. Please either point out where I'm going wrong, or just write the couple of lines of Python code necessary to do this! FWIW, I expected to be able to do something like this: ``` >>> s = "+8070465bdf3b9c6ad6a89c32e8162ef1\t\n+86fa593a025714f89d6bc8c9c5a191ac\t\n+bbbd7247731cbb7ec1b3a5814ed4bc9d\t" >>> c = "8eirwN1kTwCzgWA2HxTaRQ==" >>> hashlib.md5("%s%s%s%s%s" % (c, ":coolgoog:", s, ":coolgoog:", c)).digest().encode("base64") 'qfb50mxpHrS82yTofPkcEg==\n' ``` But as you can see, 'qfb50mxpHrS82yTofPkcEg==\n' != 'dRalfTU+bXwUhlk0NCGJtQ=='.
``` c="8eirwN1kTwCzgWA2HxTaRQ==".decode('base64') ```
182,011
<p>When accessing an object in a DataTable retrieved from a database, are there any reasons not to cast the object into your desired type, or are there reasons to use convert? I know the rule is cast when we know what data type we're working with, and convert when attempting to change the data type to something it isn't. Presuming we know what data type is stored in a column, cast seems appropriate, but are there any DB type issues that mean we can't rely on this?</p>
[ { "answer_id": 182029, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": true, "text": "<p>I would always cast, for the reasons you state. The gotchas I'm aware of that you need to handle are:</p>\n\n<ol>\n<li><p>You obviously need to be able to handle DBNulls (e.g. by testing with Convert.IsDBNull)</p></li>\n<li><p>In the case of ExecuteScalar I believe you need to check for null as well as DBNull.</p></li>\n<li><p>SQL Servers @@IDENTITY and SCOPE_IDENTITY functions return numeric (decimal) even for columns that are declared as INT. In this case you can cast twice \"(int)(decimal)value\" or handle it in the T-SQL code, e.g.:\n.</p>\n\n<p>INSERT INTO MyTable ...\nSELECT AutoIdColumn FROM MyTable WHERE AutoIdColumn = SCOPE_IDENTITY()</p></li>\n</ol>\n\n<p>or</p>\n\n<pre><code>INSERT INTO MyTable ...\nSELECT CAST(SCOPE_IDENTITY() AS INT)\n</code></pre>\n" }, { "answer_id": 182031, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 0, "selected": false, "text": "<p>Both <code>CAST</code> and <code>CONVERT</code> are used to explicitly to convert an expression of one data type to another. However, with <code>CONVERT</code> you can specify the <strong>format</strong> style as well.</p>\n\n<p>Syntax for CAST:</p>\n\n<pre><code>CAST ( expression AS data_type [ (length ) ])\n</code></pre>\n\n<p>Syntax for CONVERT:</p>\n\n<pre><code>CONVERT ( data_type [ ( length ) ] , expression [ , style ] )\n</code></pre>\n" }, { "answer_id": 328254, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>When retreiving from RDBMS you should let the database driver handle marshalling between native and requested type.</p>\n\n<p>CAST is sanctioned by SQL standards and works on the highest number of RDBMS platforms. </p>\n\n<p>CONVERT is avaliable on fewer platforms.</p>\n\n<p>If you have multi-platform conciderations CONVERT should only be used for special cases such as custom formatting that cannot be accomplished with CAST.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2179408/" ]
When accessing an object in a DataTable retrieved from a database, are there any reasons not to cast the object into your desired type, or are there reasons to use convert? I know the rule is cast when we know what data type we're working with, and convert when attempting to change the data type to something it isn't. Presuming we know what data type is stored in a column, cast seems appropriate, but are there any DB type issues that mean we can't rely on this?
I would always cast, for the reasons you state. The gotchas I'm aware of that you need to handle are: 1. You obviously need to be able to handle DBNulls (e.g. by testing with Convert.IsDBNull) 2. In the case of ExecuteScalar I believe you need to check for null as well as DBNull. 3. SQL Servers @@IDENTITY and SCOPE\_IDENTITY functions return numeric (decimal) even for columns that are declared as INT. In this case you can cast twice "(int)(decimal)value" or handle it in the T-SQL code, e.g.: . INSERT INTO MyTable ... SELECT AutoIdColumn FROM MyTable WHERE AutoIdColumn = SCOPE\_IDENTITY() or ``` INSERT INTO MyTable ... SELECT CAST(SCOPE_IDENTITY() AS INT) ```
182,035
<p>Internet explorer 6 seems totally ignore CSS classes or rules on select, option or optgroup tags.</p> <p>Is there a way to bypass that limitation (except install a recent version of IE) ?</p> <p><strong>Edit</strong> : to be more precise, I'm trying to build a hierarchy between options like that example:</p> <p>Here's the HTML snippet :</p> <pre><code>&lt;select name="hierarchicalList" multiple="multiple"&gt; &lt;option class="group niv0"&gt;Os developers&lt;/option&gt; &lt;option class="group niv1"&gt;Linux&lt;/option&gt; &lt;option class="user niv2"&gt;Linus Torvald&lt;/option&gt; &lt;option class="user niv2"&gt;Alan Cox&lt;/option&gt; &lt;option class="group niv1"&gt;Windows&lt;/option&gt; &lt;option class="user niv2"&gt;Paul Allen&lt;/option&gt; &lt;option class="user niv2"&gt;Bill Gates&lt;/option&gt; &lt;option class="group niv1"&gt;Mac Os&lt;/option&gt; &lt;option class="user niv2"&gt;Steve Wozniaz&lt;/option&gt; &lt;/select&gt; </code></pre> <p>And here's CSS rules, that works fine on a recent browser (like FF3) but not working at all on IE6 :</p> <pre><code> select option { line-height: 10px; } select option.group { font-weight: bold; background: url(path_to_group_icon.gif) no-repeat; padding-left: 18px; } select option.user { background: url(path_to_user_icon.gif) no-repeat; padding-left: 18px; } select option.niv0 { margin-left: 0px; } select option.niv1 { margin-left: 10px; } select option.niv2 { margin-left: 20px; } </code></pre>
[ { "answer_id": 182054, "author": "Gene", "author_id": 22673, "author_profile": "https://Stackoverflow.com/users/22673", "pm_score": 2, "selected": false, "text": "<p>IE6 css implementation for options is buggy (as is the css implementation as a whole for IE6) But you CAN style options with css. I just tested changing option and select tags bgcolor and it worked as expected. The only component I know of that can not be styled is the file input.</p>\n" }, { "answer_id": 182109, "author": "CJM", "author_id": 6898, "author_profile": "https://Stackoverflow.com/users/6898", "pm_score": 1, "selected": false, "text": "<p>Yes you can style them (to some extent). I sometimes change the font, background-color and color styles.</p>\n\n<p>What were you trying to achieve?</p>\n\n<p>CSS and HTML snippets would be useful.</p>\n" }, { "answer_id": 182119, "author": "domgblackwell", "author_id": 16954, "author_profile": "https://Stackoverflow.com/users/16954", "pm_score": 3, "selected": false, "text": "<p>A very detailed guide to what does and does not work with form element styling is in the articles <a href=\"http://www.456bereastreet.com/archive/200409/styling_form_controls/\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://www.456bereastreet.com/archive/200409/styling_form_controls/\" rel=\"nofollow noreferrer\">here</a>. From my commercial experience cross-browser form layouts that work on IE6 are not imposssible (although you do need to test carefully). An executive summary is that you can control sizes and colours but trying to micro-manage things like text alignment is a losing battle. </p>\n" }, { "answer_id": 183213, "author": "Matt", "author_id": 17020, "author_profile": "https://Stackoverflow.com/users/17020", "pm_score": 4, "selected": true, "text": "<p>This won't do exactly what you want, but rather than using CSS, you could just use a number of</p>\n\n<pre><code>&amp;nbsp ; \n</code></pre>\n\n<p>for the indents, or dashes so:</p>\n\n<p>Level 1</p>\n\n<p>-Level 2</p>\n\n<p>--Level 3</p>\n\n<p>etc.</p>\n\n<p>If you don't particularly like that, you could surround them with </p>\n\n<pre><code>&lt;!--[if lt IE 7]&gt;&lt;![endif]--&gt; \n</code></pre>\n\n<p>or </p>\n\n<pre><code>&lt;!--[if IE 6]&gt;&lt;![endif]--&gt; \n</code></pre>\n\n<p>So it would look like</p>\n\n<pre><code>Level 1\n&lt;!--[if lt IE 7]&gt;-&lt;![endif]--&gt;Level 2 \n&lt;!--[if lt IE 7]&gt;--&lt;![endif]--&gt; Level 3\n</code></pre>\n\n<p>Then you could have the CSS for modern browsers.</p>\n" }, { "answer_id": 183420, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "<p>You could emulate the whole thing using a drop-down menu script instead. It would give you complete control.</p>\n" }, { "answer_id": 186536, "author": "paulgreg", "author_id": 3122, "author_profile": "https://Stackoverflow.com/users/3122", "pm_score": 2, "selected": false, "text": "<p>From <a href=\"http://msdn.microsoft.com/en-us/library/ms535877(VS.85).aspx#\" rel=\"nofollow noreferrer\">MSDN reference</a> : </p>\n\n<blockquote>\n <p>Except for background-color and color,\n style settings applied through the\n style object for the option element\n are ignored. In addition, style\n settings applied directly to\n individual options override those\n applied to the containing SELECT\n element as a whole.</p>\n</blockquote>\n\n<p>Ok, so... There's no way to get that working on IE...</p>\n\n<p>Thanks Matt for the nbsp; idea. I will surely use that work-around.</p>\n" }, { "answer_id": 204775, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Take a look at the optgroup tag to group entries inside a select tag.\nLook here: <a href=\"http://www.netmechanic.com/news/vol4/html_no20.htm\" rel=\"nofollow noreferrer\">http://www.netmechanic.com/news/vol4/html_no20.htm</a> for an example</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3122/" ]
Internet explorer 6 seems totally ignore CSS classes or rules on select, option or optgroup tags. Is there a way to bypass that limitation (except install a recent version of IE) ? **Edit** : to be more precise, I'm trying to build a hierarchy between options like that example: Here's the HTML snippet : ``` <select name="hierarchicalList" multiple="multiple"> <option class="group niv0">Os developers</option> <option class="group niv1">Linux</option> <option class="user niv2">Linus Torvald</option> <option class="user niv2">Alan Cox</option> <option class="group niv1">Windows</option> <option class="user niv2">Paul Allen</option> <option class="user niv2">Bill Gates</option> <option class="group niv1">Mac Os</option> <option class="user niv2">Steve Wozniaz</option> </select> ``` And here's CSS rules, that works fine on a recent browser (like FF3) but not working at all on IE6 : ``` select option { line-height: 10px; } select option.group { font-weight: bold; background: url(path_to_group_icon.gif) no-repeat; padding-left: 18px; } select option.user { background: url(path_to_user_icon.gif) no-repeat; padding-left: 18px; } select option.niv0 { margin-left: 0px; } select option.niv1 { margin-left: 10px; } select option.niv2 { margin-left: 20px; } ```
This won't do exactly what you want, but rather than using CSS, you could just use a number of ``` &nbsp ; ``` for the indents, or dashes so: Level 1 -Level 2 --Level 3 etc. If you don't particularly like that, you could surround them with ``` <!--[if lt IE 7]><![endif]--> ``` or ``` <!--[if IE 6]><![endif]--> ``` So it would look like ``` Level 1 <!--[if lt IE 7]>-<![endif]-->Level 2 <!--[if lt IE 7]>--<![endif]--> Level 3 ``` Then you could have the CSS for modern browsers.
182,040
<p>I want to create a route in my rails application along the lines of</p> <pre><code>/panda/blog /tiger/blog /dog/blog </code></pre> <p>where panda, tiger, and dog are all permalinks (for an animal class)</p> <p>The normal way of doing this</p> <pre><code>map.resources :animals do |animal| animal.resource :blog end </code></pre> <p>would create routes along the lines of</p> <pre><code>/animals/panda/blog /animals/tiger/blog /animals/dog/blog </code></pre> <p>But i do not want the first segment, as it will always be the same. </p> <p>I know I could do this by manual routing, but I want to know how to do using rails resources, as having animals and blogs is a requirement for me.</p>
[ { "answer_id": 182093, "author": "Bartosz Blimke", "author_id": 18715, "author_profile": "https://Stackoverflow.com/users/18715", "pm_score": 1, "selected": false, "text": "<p>You can use this plugin:</p>\n\n<p><a href=\"http://github.com/caring/default_routing/tree/master\" rel=\"nofollow noreferrer\">http://github.com/caring/default_routing/tree/master</a></p>\n" }, { "answer_id": 6201691, "author": "edgerunner", "author_id": 311941, "author_profile": "https://Stackoverflow.com/users/311941", "pm_score": 4, "selected": true, "text": "<p>In rails 3.x, you can add <code>path =&gt; \"\"</code> to any <code>resource</code> or <code>resources</code> call to remove the first segment from the generated path.</p>\n\n<pre><code>resources :animals, :path =&gt; \"\"\n</code></pre>\n\n<hr>\n\n<pre><code>$ rake routes\n\n animals GET / {:action=&gt;\"index\", :controller=&gt;\"animals\"}\n POST / {:action=&gt;\"create\", :controller=&gt;\"animals\"}\n new_animal GET /new(.:format) {:action=&gt;\"new\", :controller=&gt;\"animals\"}\nedit_animal GET /:id/edit(.:format) {:action=&gt;\"edit\", :controller=&gt;\"animals\"}\n animal GET /:id(.:format) {:action=&gt;\"show\", :controller=&gt;\"animals\"}\n PUT /:id(.:format) {:action=&gt;\"update\", :controller=&gt;\"animals\"}\n DELETE /:id(.:format) {:action=&gt;\"destroy\", :controller=&gt;\"animals\"}\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7473/" ]
I want to create a route in my rails application along the lines of ``` /panda/blog /tiger/blog /dog/blog ``` where panda, tiger, and dog are all permalinks (for an animal class) The normal way of doing this ``` map.resources :animals do |animal| animal.resource :blog end ``` would create routes along the lines of ``` /animals/panda/blog /animals/tiger/blog /animals/dog/blog ``` But i do not want the first segment, as it will always be the same. I know I could do this by manual routing, but I want to know how to do using rails resources, as having animals and blogs is a requirement for me.
In rails 3.x, you can add `path => ""` to any `resource` or `resources` call to remove the first segment from the generated path. ``` resources :animals, :path => "" ``` --- ``` $ rake routes animals GET / {:action=>"index", :controller=>"animals"} POST / {:action=>"create", :controller=>"animals"} new_animal GET /new(.:format) {:action=>"new", :controller=>"animals"} edit_animal GET /:id/edit(.:format) {:action=>"edit", :controller=>"animals"} animal GET /:id(.:format) {:action=>"show", :controller=>"animals"} PUT /:id(.:format) {:action=>"update", :controller=>"animals"} DELETE /:id(.:format) {:action=>"destroy", :controller=>"animals"} ```
182,044
<p>Can anyone give me an example of what the Artifact paths setting defined for a build configuration could look like if I want to create two artifacts dist and source where I am using the sln 2008 build runner and building my projects using the default bin/Release?</p> <pre> **/Source/Code/MyProject/bin/Release/*.* => dist **/*.* => source </pre> <p>I get two artifact roots dist and source but under dist I get the whole directory structure (Source/Code/MyProject/bin/Release) which I don't want and under source I get the whole thing along with obj and bin/Release which I do not want.</p> <p>Can you give some advice on how to do this correctly?</p> <p>Do I need to change the target location for all the projects I am building to be able to get this thing to work?</p>
[ { "answer_id": 190573, "author": "Scott Cowan", "author_id": 253, "author_profile": "https://Stackoverflow.com/users/253", "pm_score": 5, "selected": false, "text": "<p>So you'll just need:</p>\n\n<pre><code>Source\\Code\\MyProject\\bin\\Release\\* =&gt; dist\nSource\\**\\* =&gt; source\n</code></pre>\n\n<p>This will put all the files in release into a artifact folder called dist and everything in Source into a artifact folder called source.</p>\n\n<p>If you have subfolders in Release try:</p>\n\n<pre><code>Source\\Code\\MyProject\\bin\\Release\\**\\* =&gt; dist\n</code></pre>\n" }, { "answer_id": 1922877, "author": "user233173", "author_id": 233173, "author_profile": "https://Stackoverflow.com/users/233173", "pm_score": 0, "selected": false, "text": "<p>According to TeamCity documentation; it should be like this:</p>\n\n<pre><code>file_name|directory_name|Ant-like wildcard [ =&gt; target_directory ]\n</code></pre>\n\n<p>So.. </p>\n\n<pre><code>Source\\Code\\MyProject\\bin\\Release|**\\* =&gt; dist (| not \\)\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15771/" ]
Can anyone give me an example of what the Artifact paths setting defined for a build configuration could look like if I want to create two artifacts dist and source where I am using the sln 2008 build runner and building my projects using the default bin/Release? ``` **/Source/Code/MyProject/bin/Release/*.* => dist **/*.* => source ``` I get two artifact roots dist and source but under dist I get the whole directory structure (Source/Code/MyProject/bin/Release) which I don't want and under source I get the whole thing along with obj and bin/Release which I do not want. Can you give some advice on how to do this correctly? Do I need to change the target location for all the projects I am building to be able to get this thing to work?
So you'll just need: ``` Source\Code\MyProject\bin\Release\* => dist Source\**\* => source ``` This will put all the files in release into a artifact folder called dist and everything in Source into a artifact folder called source. If you have subfolders in Release try: ``` Source\Code\MyProject\bin\Release\**\* => dist ```
182,060
<p>I have webservice which is passed an array of ints. I'd like to do the select statement as follows but keep getting errors. Do I need to change the array to a string?</p> <pre><code>[WebMethod] public MiniEvent[] getAdminEvents(int buildingID, DateTime startDate) { command.CommandText = @"SELECT id, startDateTime, endDateTime From tb_bookings WHERE buildingID IN (@buildingIDs) AND startDateTime &lt;= @fromDate"; SqlParameter buildID = new SqlParameter("@buildingIDs", buildingIDs); } </code></pre>
[ { "answer_id": 182065, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 1, "selected": false, "text": "<p>Visit <a href=\"https://stackoverflow.com/questions/43249/t-sql-stored-procedure-that-accepts-multiple-id-values\">T-SQL stored procedure that accepts multiple Id values</a> for ideas on how to do this.</p>\n" }, { "answer_id": 182092, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 5, "selected": false, "text": "<p>You can't (unfortunately) do that. A Sql Parameter can only be a single value, so you'd have to do:</p>\n\n<pre><code>WHERE buildingID IN (@buildingID1, @buildingID2, @buildingID3...)\n</code></pre>\n\n<p>Which, of course, requires you to know how many building ids there are, or to dynamically construct the query.</p>\n\n<p>As a workaround*, I've done the following:</p>\n\n<pre><code>WHERE buildingID IN (@buildingID)\n\ncommand.CommandText = command.CommandText.Replace(\n \"@buildingID\", \n string.Join(buildingIDs.Select(b =&gt; b.ToString()), \",\")\n);\n</code></pre>\n\n<p>which will replace the text of the statement with the numbers, ending up as something like:</p>\n\n<pre><code>WHERE buildingID IN (1,2,3,4)\n</code></pre>\n\n<ul>\n<li>Note that this is getting close to a Sql injection vulnerability, but since it's an int array is safe. Arbitrary strings are <em>not</em> safe, but there's no way to embed Sql statements in an integer (or datetime, boolean, etc).</li>\n</ul>\n" }, { "answer_id": 183068, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 3, "selected": false, "text": "<p><strong>NOTE:</strong> I am not generally for using unparameterized queries. IN THIS INSTANCE, however, given that we are dealing with an integer array, you <em>could</em> do such a thing and it would be more efficient. However, given that everyone seems to want to downgrade the answer because it doesn't meet their criteria of valid advice, I will submit another answer that performs horribly but would probably run in LINK2SQL.</p>\n\n<p>Assuming, as your question states, that you have an array of ints, you can use the following code to return a string that would contain a comma delimited list that SQL would accept:</p>\n\n<pre><code>private string SQLArrayToInString(Array a)\n{\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i &lt; a.GetUpperBound(0); i++)\n sb.AppendFormat(\"{0},\", a.GetValue(i));\n string retVal = sb.ToString();\n return retVal.Substring(0, retVal.Length - 1);\n}\n</code></pre>\n\n<p>Then, I would recommend you skip trying to parameterize the command <em>given that this is an array of ints</em> and just use:</p>\n\n<pre><code>command.CommandText = @\"SELECT id,\n startDateTime, endDateTime From\n tb_bookings WHERE buildingID IN\n (\" + SQLArrayToInString(buildingIDs) + \") AND startDateTime &lt;=\n @fromDate\";\n</code></pre>\n" }, { "answer_id": 205854, "author": "Chris Porter", "author_id": 13495, "author_profile": "https://Stackoverflow.com/users/13495", "pm_score": 0, "selected": false, "text": "<blockquote>\n<p>[WebMethod]</p>\n<p>public MiniEvent[] getAdminEvents(int <b>buildingID</b>, DateTime startDate)</p>\n<p>...</p>\n<p>SqlParameter buildID= new SqlParameter(&quot;@buildingIDs&quot;, <b>buildingIDs</b>);</p>\n</blockquote>\n<p>Perhaps I'm being over detailed, but this method accepts a single int, not an array of ints. If you expect to pass in an array, you will need to update your method definition to have an int array. Once you get that array, you will need to convert the array to a string if you plan to use it in a SQL query.</p>\n" }, { "answer_id": 205875, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 3, "selected": false, "text": "<p>First you're going to need a function and a sproc. The function will split your data and return a table:</p>\n\n<pre><code>CREATE function IntegerCommaSplit(@ListofIds nvarchar(1000))\nreturns @rtn table (IntegerValue int)\nAS\nbegin\nWhile (Charindex(',',@ListofIds)&gt;0)\nBegin\n Insert Into @Rtn \n Select ltrim(rtrim(Substring(@ListofIds,1,Charindex(',',@ListofIds)-1)))\n Set @ListofIds = Substring(@ListofIds,Charindex(',',@ListofIds)+len(','),len(@ListofIds))\nend\nInsert Into @Rtn \n Select ltrim(rtrim(@ListofIds))\nreturn \nend\n</code></pre>\n\n<p>Next you need a sproc to use that:</p>\n\n<pre><code>create procedure GetAdminEvents \n @buildingids nvarchar(1000),\n @startdate datetime\nas\nSELECT id,startDateTime, endDateTime From\n tb_bookings t INNER JOIN \ndbo.IntegerCommaSplit(@buildingids) i\non i.IntegerValue = t.id\n WHERE startDateTime &lt;= @fromDate\n</code></pre>\n\n<p>Finally, your code:</p>\n\n<pre><code>[WebMethod]\n public MiniEvent[] getAdminEvents(int[] buildingIDs, DateTime startDate)\n command.CommandText = @\"exec GetAdminEvents\";\n SqlParameter buildID= new SqlParameter(\"@buildingIDs\", buildingIDs);\n</code></pre>\n\n<p>That goes way beyond what your question asked but it will do what you need.</p>\n\n<p><strong>Note:</strong> should you pass in anything that's not an int, the whole database function will fail. I leave the error handling for that as an exercise for the end user.</p>\n" }, { "answer_id": 15191562, "author": "Nishant", "author_id": 2089165, "author_profile": "https://Stackoverflow.com/users/2089165", "pm_score": 2, "selected": false, "text": "<p>A superfast XML Method which requires no unsafe code or user defined functions :</p>\n\n<p>You can use a stored procedure and pass the comma separated list of Building IDs : </p>\n\n<pre><code>Declare @XMLList xml\nSET @XMLList=cast('&lt;i&gt;'+replace(@buildingIDs,',','&lt;/i&gt;&lt;i&gt;')+'&lt;/i&gt;' as xml)\nSELECT x.i.value('.','varchar(5)') from @XMLList.nodes('i') x(i))\n</code></pre>\n\n<p>All credit goes to Guru <a href=\"http://beyondrelational.com/modules/2/blogs/114/posts/14617/delimited-string-tennis-anyone.aspx\" rel=\"nofollow\">Brad Schulz's Blog</a></p>\n" }, { "answer_id": 31456449, "author": "Igo Soares", "author_id": 5123926, "author_profile": "https://Stackoverflow.com/users/5123926", "pm_score": 0, "selected": false, "text": "<p>You can use this. Execute in SQLServer to create a function on your DB (Only once):</p>\n\n<pre><code>IF EXISTS(\n SELECT *\n FROM sysobjects\n WHERE name = 'FN_RETORNA_ID_FROM_VARCHAR_TO_TABLE_INT')\nBEGIN\n DROP FUNCTION FN_RETORNA_ID_FROM_VARCHAR_TO_TABLE_INT\nEND\nGO\n\nCREATE FUNCTION [dbo].FN_RETORNA_ID_FROM_VARCHAR_TO_TABLE_INT (@IDList VARCHAR(8000))\nRETURNS\n @IDListTable TABLE (ID INT)\nAS\nBEGIN\n\n DECLARE\n --@IDList VARCHAR(100),\n @LastCommaPosition INT,\n @NextCommaPosition INT,\n @EndOfStringPosition INT,\n @StartOfStringPosition INT,\n @LengthOfString INT,\n @IDString VARCHAR(100),\n @IDValue INT\n\n --SET @IDList = '11,12,113'\n\n SET @LastCommaPosition = 0\n SET @NextCommaPosition = -1\n\n IF LTRIM(RTRIM(@IDList)) &lt;&gt; ''\n BEGIN\n\n WHILE(@NextCommaPosition &lt;&gt; 0)\n BEGIN\n\n SET @NextCommaPosition = CHARINDEX(',',@IDList,@LastCommaPosition + 1)\n\n IF @NextCommaPosition = 0\n SET @EndOfStringPosition = LEN(@IDList)\n ELSE\n SET @EndOfStringPosition = @NextCommaPosition - 1\n\n SET @StartOfStringPosition = @LastCommaPosition + 1\n SET @LengthOfString = (@EndOfStringPosition + 1) - @StartOfStringPosition\n\n SET @IDString = SUBSTRING(@IDList,@StartOfStringPosition,@LengthOfString) \n\n IF @IDString &lt;&gt; ''\n INSERT @IDListTable VALUES(@IDString)\n\n SET @LastCommaPosition = @NextCommaPosition\n\n END --WHILE(@NextCommaPosition &lt;&gt; 0)\n\n END --IF LTRIM(RTRIM(@IDList)) &lt;&gt; ''\n\n RETURN\n\nErrorBlock:\n\n RETURN\n\nEND --FUNCTION\n</code></pre>\n\n<p>After create the function you have to call this on your code:</p>\n\n<pre><code>command.CommandText = @\"SELECT id,\n startDateTime, endDateTime From\n tb_bookings WHERE buildingID IN\n (SELECT ID FROM FN_RETORNA_ID_FROM_VARCHAR_TO_TABLE_INT(@buildingIDs))) AND startDateTime &lt;=\n @fromDate\";\n\ncommand.Parameters.Add(new SqlParameter(){\n DbType = DbType.String,\n ParameterName = \"@buildingIDs\",\n Value = \"1,2,3,4,5\" //Enter the parameters here separated with commas\n });\n</code></pre>\n\n<p>This function get the text inner commas on \"array\" and make an table with this values as int, called ID. When this function is on you DB you can use in any project.</p>\n\n<hr>\n\n<p>Thanks to Microsoft MSDN.</p>\n\n<p>Igo S Ventura</p>\n\n<p>Microsoft MVA</p>\n\n<p>Sistema Ari de Sá</p>\n\n<p>[email protected]</p>\n\n<p>P.S.: I'm from Brazil. Apologize my english... XD</p>\n" }, { "answer_id": 39169627, "author": "Gonçalo Dinis", "author_id": 5758761, "author_profile": "https://Stackoverflow.com/users/5758761", "pm_score": 1, "selected": false, "text": "<p>I use that approach and works for me.</p>\n\n<p>My variable act = my list of ID's at string.</p>\n\n<blockquote>\n <p>act = \"1, 2, 3, 4\"</p>\n</blockquote>\n\n<pre><code> command = new SqlCommand(\"SELECT x FROM y WHERE x.id IN (@actions)\", conn); \n command.Parameters.AddWithValue(\"@actions\", act);\n command.CommandText = command.CommandText.Replace(\"@actions\", act);\n</code></pre>\n" }, { "answer_id": 40803195, "author": "Nyerguds", "author_id": 395685, "author_profile": "https://Stackoverflow.com/users/395685", "pm_score": 0, "selected": false, "text": "<p>Here's a Linq solution I thought up. It'll automatically insert all items in the list as parameters @item0, @item1, @item2, @item3, etc.</p>\n\n<pre><code>[WebMethod]\npublic MiniEvent[] getAdminEvents(Int32[] buildingIDs, DateTime startDate)\n{\n // Gets a list with numbers from 0 to the max index in buildingIDs,\n // then transforms it into a list of strings using those numbers.\n String idParamString = String.Join(\", \", (Enumerable.Range(0, buildingIDs.Length).Select(i =&gt; \"@item\" + i)).ToArray());\n command.CommandText = @\"SELECT id,\n startDateTime, endDateTime From\n tb_bookings WHERE buildingID IN\n (\" + idParamString + @\") AND startDateTime &lt;=\n @fromDate\";\n // Reproduce the same parameters in idParamString \n for (Int32 i = 0; i &lt; buildingIDs.Length; i++)\n command.Parameters.Add(new SqlParameter (\"@item\" + i, buildingIDs[i]));\n command.Parameters.Add(new SqlParameter(\"@fromDate\", startDate);\n // the rest of your code...\n}\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17510/" ]
I have webservice which is passed an array of ints. I'd like to do the select statement as follows but keep getting errors. Do I need to change the array to a string? ``` [WebMethod] public MiniEvent[] getAdminEvents(int buildingID, DateTime startDate) { command.CommandText = @"SELECT id, startDateTime, endDateTime From tb_bookings WHERE buildingID IN (@buildingIDs) AND startDateTime <= @fromDate"; SqlParameter buildID = new SqlParameter("@buildingIDs", buildingIDs); } ```
You can't (unfortunately) do that. A Sql Parameter can only be a single value, so you'd have to do: ``` WHERE buildingID IN (@buildingID1, @buildingID2, @buildingID3...) ``` Which, of course, requires you to know how many building ids there are, or to dynamically construct the query. As a workaround\*, I've done the following: ``` WHERE buildingID IN (@buildingID) command.CommandText = command.CommandText.Replace( "@buildingID", string.Join(buildingIDs.Select(b => b.ToString()), ",") ); ``` which will replace the text of the statement with the numbers, ending up as something like: ``` WHERE buildingID IN (1,2,3,4) ``` * Note that this is getting close to a Sql injection vulnerability, but since it's an int array is safe. Arbitrary strings are *not* safe, but there's no way to embed Sql statements in an integer (or datetime, boolean, etc).
182,066
<p>If I have two tables... Category and Pet. </p> <p>Is there a way in LINQ to SQL to make the result of the joined query map to a another strongly typed class (such as: PetWithCategoryName) so that I can strongly pass it to a MVC View?</p> <p>I currently have Category and Pet classes... should I make another one?</p> <p>Maybe I missing something here. Can any of you enlighten me?</p> <pre><code>from p in petTable join c in categoryTable on p.CategoryId equals c.Id where (c.Id == categoryId.Value) select new { p.Id, p.Name, p.Description, p.Price, CategoryName = c.Name } &lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;Database Name="PetShop" xmlns="http://schemas.microsoft.com/linqtosql/mapping/2007"&gt; &lt;Table Name="Category" Member="PetShop.Models.Category"&gt; &lt;Type Name="PetShop.Models.Category"&gt; &lt;Column Name="Id" Member="Id" IsDbGenerated="true" IsPrimaryKey="true" /&gt; &lt;Column Name="Name" Member="Name" /&gt; &lt;Column Name="Description" Member="Description" /&gt; &lt;/Type&gt; &lt;/Table&gt; &lt;Table Name="Pet" Member="PetShop.Models.Pet"&gt; &lt;Type Name="PetShop.Models.Pet"&gt; &lt;Column Name="Id" Member="Id" IsDbGenerated="true" IsPrimaryKey="true" /&gt; &lt;Column Name="Name" Member="Name" /&gt; &lt;Column Name="Description" Member="Description" /&gt; &lt;Column Name="ImageUrl" Member="ImageUrl" /&gt; &lt;Column Name="Price" Member="Price" /&gt; &lt;Column Name="CategoryId" Member="CategoryId" /&gt; &lt;Association Name="FK_Pet_Category" Member="Category" ThisKey="CategoryId" OtherKey="Id" IsForeignKey="true" /&gt; &lt;/Type&gt; &lt;/Table&gt; &lt;/Database&gt; </code></pre>
[ { "answer_id": 182292, "author": "Giovanni Galbo", "author_id": 4050, "author_profile": "https://Stackoverflow.com/users/4050", "pm_score": 1, "selected": false, "text": "<p>If you use the LoadWith LoadOption then your Pet query will do an eager load on categories, so that you will be able to do</p>\n\n<p>MyPet.Category.Name without incurring an extra query, so you'll have the data joined and strongly typed without the risk of running multiple queries for Categories as you loop or bind on the Pet collection.</p>\n\n<p>Or you can use stored procedures in Linq To SQL,the result is strongly typed.</p>\n" }, { "answer_id": 182359, "author": "Giovanni Galbo", "author_id": 4050, "author_profile": "https://Stackoverflow.com/users/4050", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>How would I go about using LoadWith? I'm not finding much help online. Any good resources? </p>\n</blockquote>\n\n<p>I found this online: <a href=\"http://blogs.msdn.com/wriju/archive/2007/10/04/linq-to-sql-change-in-datacontext-from-beta-1-to-beta-2.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/wriju/archive/2007/10/04/linq-to-sql-change-in-datacontext-from-beta-1-to-beta-2.aspx</a></p>\n\n<p>You would do something like:</p>\n\n<pre><code>var loadOption = new DataLoadOptions(); \nloadOption.LoadWith&lt;Pets&gt;(p =&gt; p.Category);\ndb.LoadOptions = loadOption; \n\nvar pets = from p in PetStoreContext.Pets\n select p;\n</code></pre>\n\n<p>And then your pets query will already include category, so no trip to the database happens when you try to access category.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4481/" ]
If I have two tables... Category and Pet. Is there a way in LINQ to SQL to make the result of the joined query map to a another strongly typed class (such as: PetWithCategoryName) so that I can strongly pass it to a MVC View? I currently have Category and Pet classes... should I make another one? Maybe I missing something here. Can any of you enlighten me? ``` from p in petTable join c in categoryTable on p.CategoryId equals c.Id where (c.Id == categoryId.Value) select new { p.Id, p.Name, p.Description, p.Price, CategoryName = c.Name } <?xml version="1.0" encoding="utf-8" ?> <Database Name="PetShop" xmlns="http://schemas.microsoft.com/linqtosql/mapping/2007"> <Table Name="Category" Member="PetShop.Models.Category"> <Type Name="PetShop.Models.Category"> <Column Name="Id" Member="Id" IsDbGenerated="true" IsPrimaryKey="true" /> <Column Name="Name" Member="Name" /> <Column Name="Description" Member="Description" /> </Type> </Table> <Table Name="Pet" Member="PetShop.Models.Pet"> <Type Name="PetShop.Models.Pet"> <Column Name="Id" Member="Id" IsDbGenerated="true" IsPrimaryKey="true" /> <Column Name="Name" Member="Name" /> <Column Name="Description" Member="Description" /> <Column Name="ImageUrl" Member="ImageUrl" /> <Column Name="Price" Member="Price" /> <Column Name="CategoryId" Member="CategoryId" /> <Association Name="FK_Pet_Category" Member="Category" ThisKey="CategoryId" OtherKey="Id" IsForeignKey="true" /> </Type> </Table> </Database> ```
> > How would I go about using LoadWith? I'm not finding much help online. Any good resources? > > > I found this online: <http://blogs.msdn.com/wriju/archive/2007/10/04/linq-to-sql-change-in-datacontext-from-beta-1-to-beta-2.aspx> You would do something like: ``` var loadOption = new DataLoadOptions(); loadOption.LoadWith<Pets>(p => p.Category); db.LoadOptions = loadOption; var pets = from p in PetStoreContext.Pets select p; ``` And then your pets query will already include category, so no trip to the database happens when you try to access category.
182,073
<p>I am receiving an error from the Oracle JDBC driver (ojdbc14_g.jar) when trying to obtain a connection to a 10g database. The driver has an oracle.jdbc.driver.OracleLog class which could help but the Oracle documentation is unclear how best to use it. Has anyone had any success using this class? If so, some guidance on its use would be appreciated.</p> <p>For info, the error I'm getting from the JDBC driver is:</p> <pre><code>java.sql.SQLException: No more data to read from socket at oracle.jdbc.driver.DatabaseError.throwSqlException (DatabaseError.java:112) at oracle.jdbc.driver.DatabaseError.throwSqlException (DatabaseError.java:146) at oracle.jdbc.driver.DatabaseError.throwSqlException (DatabaseError.java:208) at oracle.jdbc.driver.T4CMAREngine.unmarshalUB1 (T4CMAREngine.java:1118) at oracle.jdbc.driver.T4CMAREngine.unmarshalSB1 (T4CMAREngine.java:1070) at oracle.jdbc.driver.T4CTTIoauthenticate.receiveOsesskey (T4CTTIoauthenticate.java:266) at oracle.jdbc.driver.T4CConnection.logon (T4CConnection.java:357) at oracle.jdbc.driver.PhysicalConnection.&lt;init&gt; (PhysicalConnection.java:414) at oracle.jdbc.driver.T4CConnection.&lt;init&gt; (T4CConnection.java:165) at oracle.jdbc.driver.T4CDriverExtension.getConnection (T4CDriverExtension.java:35) at oracle.jdbc.driver.OracleDriver.connect (OracleDriver.java:801) at oracle.jdbc.pool.OracleDataSource.getPhysicalConnection (OracleDataSource.java:297) at oracle.jdbc.pool.OracleDataSource.getConnection (OracleDataSource.java:221) at oracle.jdbc.pool.OracleDataSource.getConnection (OracleDataSource.java:165) </code></pre>
[ { "answer_id": 182081, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>My initial thought would be to go with Javascript - if it's good enough for Google Maps, it's probably good enough for your app too.</p>\n" }, { "answer_id": 182153, "author": "slashnick", "author_id": 21030, "author_profile": "https://Stackoverflow.com/users/21030", "pm_score": 1, "selected": false, "text": "<p>Do you need to use canvas, what you're describing could be done with just javascript and the DOM. It would perform perfectly well unless there are a huge number of elements and it would be cross-browser compatible. For canvas you would require <a href=\"http://excanvas.sourceforge.net/\" rel=\"nofollow noreferrer\">exCanvas</a> to support IE which can sometimes slow things down.</p>\n" }, { "answer_id": 182239, "author": "erlando", "author_id": 4192, "author_profile": "https://Stackoverflow.com/users/4192", "pm_score": 1, "selected": false, "text": "<p>The best way would surely be Javascript. And I would even say that you should reconsider the use of canvas. It sounds like it could be done in pure DHTML. In that way you wouldn't lose support for IE.</p>\n\n<p>Consider using one of the javascript frameworks; Prototype or jQuery come to mind. It will ease your coding immensely. Given the development in javascript-engine performance (next versions of Webkit (Squirrelfish Extreme) and Mozilla (TraceMonkey) will be lightning fast) the worries about performance may be moot. </p>\n\n<p>Also if you decide that you can't do it without canvas consider using John Resig's <a href=\"http://ejohn.org/blog/processingjs/\" rel=\"nofollow noreferrer\">processing.js</a>.</p>\n" }, { "answer_id": 182512, "author": "Iain", "author_id": 11911, "author_profile": "https://Stackoverflow.com/users/11911", "pm_score": 3, "selected": true, "text": "<p>I don't think this is a question that will get you an objective answer - Flash developers will tell you Flash is better, web developers will say JavaScript. Trying to remain objective, I'd say that both technologies are suitable for what you describe, but have different advantages.</p>\n\n<p>Flash will definitely render faster, even on slow machines, and is much richer graphically.</p>\n\n<p>JavaScript is more accessible and works on a greater number of devices. Use a good JS framework though.</p>\n" }, { "answer_id": 185919, "author": "Leo", "author_id": 20689, "author_profile": "https://Stackoverflow.com/users/20689", "pm_score": 1, "selected": false, "text": "<p>I'd say go with flash (or DOM if you don't need the extra punch). Here's my reasoning:</p>\n\n<ul>\n<li><p>You can do cool transformations with canvas (skewing, rotations, gradient fade-ins in images, reflection effects, etc) that you can't with DOM. The downside is that doing these cool things is math heavy.</p></li>\n<li><p>Canvas doesn't work in IE. IE's equivalent (VML) apparently has a root-access security hole.</p></li>\n<li><p>The DOM has been around for longer than canvas and since it's more widely used (and depended upon), it's more optimized and polished than canvas. </p></li>\n<li><p>The Flash community has a lot of good free components available that may already do what exactly you want.</p></li>\n<li><p>Flash and DOM have a lot of good documentation and tutorials, canvas not so much.</p></li>\n<li><p>Flash can do pretty much everything that the DOM and canvas can, plus audio, video and grabbing input from your web cam.</p></li>\n</ul>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4023/" ]
I am receiving an error from the Oracle JDBC driver (ojdbc14\_g.jar) when trying to obtain a connection to a 10g database. The driver has an oracle.jdbc.driver.OracleLog class which could help but the Oracle documentation is unclear how best to use it. Has anyone had any success using this class? If so, some guidance on its use would be appreciated. For info, the error I'm getting from the JDBC driver is: ``` java.sql.SQLException: No more data to read from socket at oracle.jdbc.driver.DatabaseError.throwSqlException (DatabaseError.java:112) at oracle.jdbc.driver.DatabaseError.throwSqlException (DatabaseError.java:146) at oracle.jdbc.driver.DatabaseError.throwSqlException (DatabaseError.java:208) at oracle.jdbc.driver.T4CMAREngine.unmarshalUB1 (T4CMAREngine.java:1118) at oracle.jdbc.driver.T4CMAREngine.unmarshalSB1 (T4CMAREngine.java:1070) at oracle.jdbc.driver.T4CTTIoauthenticate.receiveOsesskey (T4CTTIoauthenticate.java:266) at oracle.jdbc.driver.T4CConnection.logon (T4CConnection.java:357) at oracle.jdbc.driver.PhysicalConnection.<init> (PhysicalConnection.java:414) at oracle.jdbc.driver.T4CConnection.<init> (T4CConnection.java:165) at oracle.jdbc.driver.T4CDriverExtension.getConnection (T4CDriverExtension.java:35) at oracle.jdbc.driver.OracleDriver.connect (OracleDriver.java:801) at oracle.jdbc.pool.OracleDataSource.getPhysicalConnection (OracleDataSource.java:297) at oracle.jdbc.pool.OracleDataSource.getConnection (OracleDataSource.java:221) at oracle.jdbc.pool.OracleDataSource.getConnection (OracleDataSource.java:165) ```
I don't think this is a question that will get you an objective answer - Flash developers will tell you Flash is better, web developers will say JavaScript. Trying to remain objective, I'd say that both technologies are suitable for what you describe, but have different advantages. Flash will definitely render faster, even on slow machines, and is much richer graphically. JavaScript is more accessible and works on a greater number of devices. Use a good JS framework though.
182,082
<p>I cureently have a set up like below </p> <pre><code>Public ClassA property _classB as ClassB End Class Public ClassB property _someProperty as someProperty End Class </code></pre> <p>what I want to do is to databind object A to a gridview with one of the columns being databound to ClassB._someProperty. When I try to databind it as Classb._someProperty I get a "Field or Property not found on Selected Datasource" error</p> <p>I have tried to use the objectContainerDataSource and also directly binding to the gridview with no success. </p> <p>Has anyone come across this in the past?</p>
[ { "answer_id": 182113, "author": "Neil Hewitt", "author_id": 22178, "author_profile": "https://Stackoverflow.com/users/22178", "pm_score": 2, "selected": false, "text": "<p>Ordinary databinding doesn't generally allow for expressions. Under the hood the datagrid is using reflection (rather the executing code the way DataBinder.Eval does on an ASP.NET page) to find the property that you specify to bind to a column. To do what you want it would need to evaluate the binding as an expression, work out that you were looking for a parent -> child relation, and then reflect down to that level. AFAIK the inbuilt databinding on the grid is too dumb to know how to do this.</p>\n\n<p>I've had the same issue recently, and my solution was to do a LINQ projection and bind that to the grid instead. Something like the following (in C# because I'm not comfortable with the LINQ syntax in VB):</p>\n\n<pre><code>IList&lt;ClassA&gt; listOfClassAObjects = GetMyListOfClassAObjectsFromSomewhere();\nvar projection = from ClassA a in listOfClassAObjects\n select new { SomeProperty = a.SomeProperty, \n SomeOtherProperty = a.SomeOtherProperty,\n SomePropertyFromB = a.ClassB.SomeProperty };\ndatagrid.DataSource = projection;\ndatagrid.DataBind();\n</code></pre>\n\n<p>You'll get back a list of anonymous types containing that projection, and you can bind the appropriate column to <code>SomePropertyFromB</code>.</p>\n\n<p>For extra encapsulation (if you do this a lot) put the projection into an extension method so you can do something like </p>\n\n<pre><code>var data = GetMyListOfClassAObjectsFromSomewhere().ProjectionForDataGrid();\ndatagrid.DataSource = data;\ndatagrid.DataBind();\n</code></pre>\n" }, { "answer_id": 182929, "author": "Dean", "author_id": 11802, "author_profile": "https://Stackoverflow.com/users/11802", "pm_score": 1, "selected": true, "text": "<p>I found the way to do this is to use a template field and eval (see below)</p>\n\n<p>Set the datafield as property classB and then:</p>\n\n<pre><code>&lt;asp:TemplateField HeaderText=\"_someProperty\"&gt;\n&lt;ItemTemplate&gt; \n &lt;%#Eval(\"classB._someProperty\")%&gt;\n\n&lt;/ItemTemplate&gt;\n&lt;/asp:TemplateField&gt;\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11802/" ]
I cureently have a set up like below ``` Public ClassA property _classB as ClassB End Class Public ClassB property _someProperty as someProperty End Class ``` what I want to do is to databind object A to a gridview with one of the columns being databound to ClassB.\_someProperty. When I try to databind it as Classb.\_someProperty I get a "Field or Property not found on Selected Datasource" error I have tried to use the objectContainerDataSource and also directly binding to the gridview with no success. Has anyone come across this in the past?
I found the way to do this is to use a template field and eval (see below) Set the datafield as property classB and then: ``` <asp:TemplateField HeaderText="_someProperty"> <ItemTemplate> <%#Eval("classB._someProperty")%> </ItemTemplate> </asp:TemplateField> ```
182,130
<p>I want to record user states and then be able to report historically based on the record of changes we've kept. I'm trying to do this in SQL (using PostgreSQL) and I have a proposed structure for recording user changes like the following.</p> <pre><code>CREATE TABLE users ( userid SERIAL NOT NULL PRIMARY KEY, name VARCHAR(40), status CHAR NOT NULL ); CREATE TABLE status_log ( logid SERIAL, userid INTEGER NOT NULL REFERENCES users(userid), status CHAR NOT NULL, logcreated TIMESTAMP ); </code></pre> <p>That's my proposed table structure, based on the data.</p> <p>For the status field 'a' represents an active user and 's' represents a suspended user,</p> <pre><code>INSERT INTO status_log (userid, status, logcreated) VALUES (1, 's', '2008-01-01'); INSERT INTO status_log (userid, status, logcreated) VALUES (1, 'a', '2008-02-01'); </code></pre> <p>So this user was suspended on 1st Jan and active again on 1st of February.</p> <p>If I wanted to get a suspended list of customers on 15th January 2008, then userid 1 should show up. If I get a suspended list of customers on 15th February 2008, then userid 1 should not show up.</p> <p>1) Is this the best way to structure this data for this kind of query?</p> <p>2) How do I query the data in either this structure or in your proposed modified structure so that I can simply have a date (say 15th January) and find a list of customers that had an active status on that date in SQL only? Is this a job for SQL?</p>
[ { "answer_id": 182255, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 3, "selected": true, "text": "<p>This can be done, but would be a lot more efficient if you stored the end date of each log. With your model you have to do something like:</p>\n\n<pre><code>select l1.userid\nfrom status_log l1\nwhere l1.status='s'\nand l1.logcreated = (select max(l2.logcreated)\n from status_log l2\n where l2.userid = l1.userid\n and l2.logcreated &lt;= date '2008-02-15'\n );\n</code></pre>\n\n<p>With the additional column it woud be more like:</p>\n\n<pre><code>select userid\nfrom status_log\nwhere status='s'\nand logcreated &lt;= date '2008-02-15'\nand logsuperseded &gt;= date '2008-02-15';\n</code></pre>\n\n<p>(Apologies for any syntax errors, I don't know Postgresql.)</p>\n\n<p>To address some further issues raised by Phil:</p>\n\n<blockquote>\n <p>A user might get moved from active, to suspended, to cancelled, to active again. This is a simplified version, in reality, there are even more states and people can be moved directly from one state to another.</p>\n</blockquote>\n\n<p>This would appear in the table like this:</p>\n\n<pre><code>userid from to status\nFRED 2008-01-01 2008-01-31 s\nFRED 2008-02-01 2008-02-07 c\nFRED 2008-02-08 a\n</code></pre>\n\n<p>I used a null for the \"to\" date of the current record. I could have used a future date like 2999-12-31 but null is preferable in some ways.</p>\n\n<blockquote>\n <p>Additionally, there would be no \"end date\" for the current status either, so I think this slightly breaks your query?</p>\n</blockquote>\n\n<p>Yes, my query would have to be re-written as</p>\n\n<pre><code>select userid\nfrom status_log\nwhere status='s'\nand logcreated &lt;= date '2008-02-15'\nand (logsuperseded is null or logsuperseded &gt;= date '2008-02-15');\n</code></pre>\n\n<p>A downside of this design is that whenever the user's status changes you have to end date their current status_log as well as create a new one. However, that isn't difficult, and I think the query advantage probably outweighs this.</p>\n" }, { "answer_id": 182880, "author": "Philip Reynolds", "author_id": 1087, "author_profile": "https://Stackoverflow.com/users/1087", "pm_score": 0, "selected": false, "text": "<p>@Tony the \"end\" date isn't necessarily applicable.</p>\n\n<p>A user might get moved from active, to suspended, to cancelled, to active again. This is a simplified version, in reality, there are even more states and people can be moved directly from one state to another.</p>\n\n<p>Additionally, there would be no \"end date\" for the current status either, so I think this slightly breaks your query?</p>\n" }, { "answer_id": 184724, "author": "JeremyDWill", "author_id": 12603, "author_profile": "https://Stackoverflow.com/users/12603", "pm_score": 0, "selected": false, "text": "<p>@Phil</p>\n\n<p>I like Tony's solution. It seems to most approriately model the situation described. Any particular user has a status for a given period of time (a minute, an hour, a day, etc.), but it is for a duration, not an instant in time. Since you want to know who was active during a certain period of time, modeling the information as a duration seems like the best approach.</p>\n\n<p>I am not sure that additional statuses are a problem. If someone is active, then suspended, then cancelled, then active again, each of those statuses would be applicable for a given duration, would they not? It may be a vey short duration, such as a few seconds or a minute, but they would still be for a length of time.</p>\n\n<p>Are you concerned that a person's status can change multiple times in a given day, but you want to know who was active for a given day? If so, then you just need to more specifically define what it means to be active on a given day. If it is enough that they were active for any part of that day, then Tony's answer works well as is. If they would have to be active for a certain amount of time in a given day, then Tony's solution could be modified to simply determine the length of time (in hours, or minutes, or days), and adding further restrictions in the WHERE clause to retrieve for the proper date, status, and length of time in that status.</p>\n\n<p>As for there being no \"end date\" for the current status, that is no problem either as long as the end date were nullable. Simply use something like this \"WHERE enddate &lt;= '2008-08-15' or enddate is null\".</p>\n" }, { "answer_id": 184747, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 1, "selected": false, "text": "<p>Does Postgres support analytic queries? This would give the active users on 2008-02-15</p>\n\n<pre><code>select userid\nfrom\n(\nselect logid, \n userid, \n status, \n logcreated,\n max(logcreated) over (partition by userid) max_logcreated_by_user\nfrom status_log\nwhere logcreated &lt;= date '2008-02-15'\n)\nwhere logcreated = max_logcreated_by_user\n and status = 'a'\n/\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1087/" ]
I want to record user states and then be able to report historically based on the record of changes we've kept. I'm trying to do this in SQL (using PostgreSQL) and I have a proposed structure for recording user changes like the following. ``` CREATE TABLE users ( userid SERIAL NOT NULL PRIMARY KEY, name VARCHAR(40), status CHAR NOT NULL ); CREATE TABLE status_log ( logid SERIAL, userid INTEGER NOT NULL REFERENCES users(userid), status CHAR NOT NULL, logcreated TIMESTAMP ); ``` That's my proposed table structure, based on the data. For the status field 'a' represents an active user and 's' represents a suspended user, ``` INSERT INTO status_log (userid, status, logcreated) VALUES (1, 's', '2008-01-01'); INSERT INTO status_log (userid, status, logcreated) VALUES (1, 'a', '2008-02-01'); ``` So this user was suspended on 1st Jan and active again on 1st of February. If I wanted to get a suspended list of customers on 15th January 2008, then userid 1 should show up. If I get a suspended list of customers on 15th February 2008, then userid 1 should not show up. 1) Is this the best way to structure this data for this kind of query? 2) How do I query the data in either this structure or in your proposed modified structure so that I can simply have a date (say 15th January) and find a list of customers that had an active status on that date in SQL only? Is this a job for SQL?
This can be done, but would be a lot more efficient if you stored the end date of each log. With your model you have to do something like: ``` select l1.userid from status_log l1 where l1.status='s' and l1.logcreated = (select max(l2.logcreated) from status_log l2 where l2.userid = l1.userid and l2.logcreated <= date '2008-02-15' ); ``` With the additional column it woud be more like: ``` select userid from status_log where status='s' and logcreated <= date '2008-02-15' and logsuperseded >= date '2008-02-15'; ``` (Apologies for any syntax errors, I don't know Postgresql.) To address some further issues raised by Phil: > > A user might get moved from active, to suspended, to cancelled, to active again. This is a simplified version, in reality, there are even more states and people can be moved directly from one state to another. > > > This would appear in the table like this: ``` userid from to status FRED 2008-01-01 2008-01-31 s FRED 2008-02-01 2008-02-07 c FRED 2008-02-08 a ``` I used a null for the "to" date of the current record. I could have used a future date like 2999-12-31 but null is preferable in some ways. > > Additionally, there would be no "end date" for the current status either, so I think this slightly breaks your query? > > > Yes, my query would have to be re-written as ``` select userid from status_log where status='s' and logcreated <= date '2008-02-15' and (logsuperseded is null or logsuperseded >= date '2008-02-15'); ``` A downside of this design is that whenever the user's status changes you have to end date their current status\_log as well as create a new one. However, that isn't difficult, and I think the query advantage probably outweighs this.
182,133
<p>I've never been so good at design because there are so many different possibilities and they all have pros and cons and I'm never sure which to go with. Anyway, here's my problem, I have a need for many different loosly related classes to have validation. However, some of these classes will need extra information to do the validation. I want to have a method <code>validate</code> that can be used to validate a Object and I want to determine if an Object is validatable with an interface, say <code>Validatable</code>. The following are the two basic solutions I can have.</p> <pre><code>interface Validatable { public void validate() throws ValidateException; } interface Object1Validatable { public void validate(Object1Converse converse) throws ValidateException; } class Object1 implements Object1Validatable { ... public void validate() throws ValidateException { throw new UnsupportedOperationException(); } } class Object2 implements Validatable { ... public void validate() throws ValidateException { ... } } </code></pre> <p>This is the first solution whereby I have a general global interface that something that's validatable implements and I could use <code>validate()</code> to validate, but Object1 doesn't support this so it's kind of defunc, but Object2 does support it and so may many other classes.</p> <p>Alternatively I could have the following which would leave me without a top level interface.</p> <pre><code>interface Object1Validatable { public void validate(Object1Converse converse) throws ValidateException; } class Object1 implements Object1Validatable { ... public void validate(Object1Converse converse) throws ValidateException { ... } } interface Object2Validatable { public void validate() throws ValidateException; } class Object2 implements Object2Validatable { ... public void validate() throws ValidateException { ... } } </code></pre> <p>I think the main problem I have is that I'm kind of stuck on the idea of having a top level interface so that I can at least say X or Y Object is validatable.</p>
[ { "answer_id": 182156, "author": "Jean", "author_id": 7898, "author_profile": "https://Stackoverflow.com/users/7898", "pm_score": 2, "selected": false, "text": "<p>what about this : </p>\n\n<pre><code>interface Validatable {\n void validate(Validator v);\n}\n\nclass Object1 implements Validatable{\n void validate(Validator v){\n v.foo\n v.bar\n }\n}\nclass Object1Converse implements Validator{\n //....\n}\nclass Object2 implements Validatable{\n void validate(Validator v){\n //do whatever you need and ingore validator ? \n }\n}\n</code></pre>\n\n<p>What do you care if Object2 receives an unneeded argument ? if it is able to operatee correctly without it it can just ignore it right ?</p>\n\n<p>If you are worried about introducing an unneeded dependency between object2 and Object1Converse then simply specify an interface to decouple them and use that as the validator. </p>\n\n<p>Now I must add that having a mixed model where you have both object able to self validate and object which need external state information to validate sounds weird. </p>\n\n<p>care to illustrate ?</p>\n" }, { "answer_id": 182157, "author": "Chris Kimpton", "author_id": 48310, "author_profile": "https://Stackoverflow.com/users/48310", "pm_score": 0, "selected": false, "text": "<p>Perhaps the <a href=\"http://commons.apache.org/validator/\" rel=\"nofollow noreferrer\">apache commons validator</a> project would be useful here - either directly or as a model for how to attack your problem. They effectively have a parallel set of objects that do the validation - so there is no interface on the objects, just the presence/absence of a related validator for the object/class.</p>\n" }, { "answer_id": 182161, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 0, "selected": false, "text": "<p>This is in C#, but the same ideas can certainly be implemented in many other languages.</p>\n\n<pre><code>public class MyClass {\n //Properties and methods here\n}\n\npublic class MyClassValidator : IValidator&lt;MyClass&gt; {\n IList&lt;IValidatorError&gt; IValidator.Validate(MyClass obj) {\n //Perform some checks here\n }\n}\n\n//...\n\npublic void RegisterValidators() {\n Validators.Add&lt;MyClassValidator&gt;();\n}\n\n//...\n\npublic void PerformSomeLogic() {\n var myobj = new MyClass { };\n //Set some properties, call some methods, etc.\n var v = Validators.Get&lt;MyClass&gt;();\n if(v.GetErrors(myobj).Count() &gt; 0)\n throw new Exception();\n SaveToDatabase(myobj);\n}\n</code></pre>\n" }, { "answer_id": 182190, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 0, "selected": false, "text": "<p>As simple solution to the \"can an object be validated\" problem is to add a third interface.</p>\n\n<p>This third interface is an empty one that parents both of the others, meaning you can just check against that interface (Assuming you aren't worried about someone spoofing being validate-able), and then iteratively check against the possible validation interfaces if you need to actually validate.</p>\n\n<p>Example:</p>\n\n<pre><code>interface Validateable\n{\n}\n\ninterface EmptyValidateable inherits Validateable //Or is it implements?\n{\n void validate() throws ValidateException;\n}\n\ninterface Objectvalidateable inherits Validateable\n{\n void validate(Object validateObj);\n}\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6414/" ]
I've never been so good at design because there are so many different possibilities and they all have pros and cons and I'm never sure which to go with. Anyway, here's my problem, I have a need for many different loosly related classes to have validation. However, some of these classes will need extra information to do the validation. I want to have a method `validate` that can be used to validate a Object and I want to determine if an Object is validatable with an interface, say `Validatable`. The following are the two basic solutions I can have. ``` interface Validatable { public void validate() throws ValidateException; } interface Object1Validatable { public void validate(Object1Converse converse) throws ValidateException; } class Object1 implements Object1Validatable { ... public void validate() throws ValidateException { throw new UnsupportedOperationException(); } } class Object2 implements Validatable { ... public void validate() throws ValidateException { ... } } ``` This is the first solution whereby I have a general global interface that something that's validatable implements and I could use `validate()` to validate, but Object1 doesn't support this so it's kind of defunc, but Object2 does support it and so may many other classes. Alternatively I could have the following which would leave me without a top level interface. ``` interface Object1Validatable { public void validate(Object1Converse converse) throws ValidateException; } class Object1 implements Object1Validatable { ... public void validate(Object1Converse converse) throws ValidateException { ... } } interface Object2Validatable { public void validate() throws ValidateException; } class Object2 implements Object2Validatable { ... public void validate() throws ValidateException { ... } } ``` I think the main problem I have is that I'm kind of stuck on the idea of having a top level interface so that I can at least say X or Y Object is validatable.
what about this : ``` interface Validatable { void validate(Validator v); } class Object1 implements Validatable{ void validate(Validator v){ v.foo v.bar } } class Object1Converse implements Validator{ //.... } class Object2 implements Validatable{ void validate(Validator v){ //do whatever you need and ingore validator ? } } ``` What do you care if Object2 receives an unneeded argument ? if it is able to operatee correctly without it it can just ignore it right ? If you are worried about introducing an unneeded dependency between object2 and Object1Converse then simply specify an interface to decouple them and use that as the validator. Now I must add that having a mixed model where you have both object able to self validate and object which need external state information to validate sounds weird. care to illustrate ?
182,160
<p>I'm new to Spring Security. How do I add an event listener which will be called as a user logs in successfully? Also I need to get some kind of unique session ID in this listener which should be available further on. I need this ID to synchronize with another server.</p>
[ { "answer_id": 182203, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": true, "text": "<p>You need to define a Spring Bean which implements <a href=\"http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/context/ApplicationListener.html\" rel=\"noreferrer\">ApplicationListener</a>.</p>\n\n<p>Then, in your code, do something like this:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public void onApplicationEvent(ApplicationEvent appEvent)\n{\n if (appEvent instanceof AuthenticationSuccessEvent)\n {\n AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) appEvent;\n UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal();\n\n // ....\n }\n}\n</code></pre>\n\n<p>Then, in your applicationContext.xml file, just define that bean and it will automatically start receiving events :)</p>\n" }, { "answer_id": 5957272, "author": "Wanderson Santos", "author_id": 128857, "author_profile": "https://Stackoverflow.com/users/128857", "pm_score": 3, "selected": false, "text": "<p>In Grails, with Spring Security Plugin, you can do this in Config.groovy:</p>\n\n<pre><code>grails.plugins.springsecurity.useSecurityEventListener = true\n\ngrails.plugins.springsecurity.onAuthenticationSuccessEvent = { e, appCtx -&gt;\n\n def session = SecurityRequestHolder.request.getSession(false)\n session.myVar = true\n\n}\n</code></pre>\n" }, { "answer_id": 14043376, "author": "user1857829", "author_id": 1857829, "author_profile": "https://Stackoverflow.com/users/1857829", "pm_score": 5, "selected": false, "text": "<p>Similar to Phill's answer, but modified to take Generics into consideration:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class AuthenticationListener implements ApplicationListener&lt;AuthenticationSuccessEvent&gt; {\n\n @Override\n public void onApplicationEvent(final AuthenticationSuccessEvent event) {\n\n // ...\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 18127973, "author": "John29", "author_id": 2324685, "author_profile": "https://Stackoverflow.com/users/2324685", "pm_score": 6, "selected": false, "text": "<p>The problem with AuthenticationSuccessEvent is it doesn't get published on remember-me login. If you're using remember-me authentication use InteractiveAuthenticationSuccessEvent instead, it works for normal login as well as for remember-me login.</p>\n\n<pre><code>@Component\npublic class LoginListener implements ApplicationListener&lt;InteractiveAuthenticationSuccessEvent&gt; {\n\n @Override\n public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event)\n {\n UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal();\n // ...\n }\n}\n</code></pre>\n" }, { "answer_id": 54063699, "author": "Sujit", "author_id": 10637296, "author_profile": "https://Stackoverflow.com/users/10637296", "pm_score": 3, "selected": false, "text": "<p>Another way using <code>@EventListener</code></p>\n\n<pre><code>@EventListener\npublic void doSomething(InteractiveAuthenticationSuccessEvent event) { // any spring event\n // your code \n\n}\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/578/" ]
I'm new to Spring Security. How do I add an event listener which will be called as a user logs in successfully? Also I need to get some kind of unique session ID in this listener which should be available further on. I need this ID to synchronize with another server.
You need to define a Spring Bean which implements [ApplicationListener](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/context/ApplicationListener.html). Then, in your code, do something like this: ```java public void onApplicationEvent(ApplicationEvent appEvent) { if (appEvent instanceof AuthenticationSuccessEvent) { AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) appEvent; UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal(); // .... } } ``` Then, in your applicationContext.xml file, just define that bean and it will automatically start receiving events :)
182,177
<p>Which Template-Engine and Ajax-Framework/-Toolkit is able to load template information from JAR-Files?</p>
[ { "answer_id": 182203, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": true, "text": "<p>You need to define a Spring Bean which implements <a href=\"http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/context/ApplicationListener.html\" rel=\"noreferrer\">ApplicationListener</a>.</p>\n\n<p>Then, in your code, do something like this:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public void onApplicationEvent(ApplicationEvent appEvent)\n{\n if (appEvent instanceof AuthenticationSuccessEvent)\n {\n AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) appEvent;\n UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal();\n\n // ....\n }\n}\n</code></pre>\n\n<p>Then, in your applicationContext.xml file, just define that bean and it will automatically start receiving events :)</p>\n" }, { "answer_id": 5957272, "author": "Wanderson Santos", "author_id": 128857, "author_profile": "https://Stackoverflow.com/users/128857", "pm_score": 3, "selected": false, "text": "<p>In Grails, with Spring Security Plugin, you can do this in Config.groovy:</p>\n\n<pre><code>grails.plugins.springsecurity.useSecurityEventListener = true\n\ngrails.plugins.springsecurity.onAuthenticationSuccessEvent = { e, appCtx -&gt;\n\n def session = SecurityRequestHolder.request.getSession(false)\n session.myVar = true\n\n}\n</code></pre>\n" }, { "answer_id": 14043376, "author": "user1857829", "author_id": 1857829, "author_profile": "https://Stackoverflow.com/users/1857829", "pm_score": 5, "selected": false, "text": "<p>Similar to Phill's answer, but modified to take Generics into consideration:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class AuthenticationListener implements ApplicationListener&lt;AuthenticationSuccessEvent&gt; {\n\n @Override\n public void onApplicationEvent(final AuthenticationSuccessEvent event) {\n\n // ...\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 18127973, "author": "John29", "author_id": 2324685, "author_profile": "https://Stackoverflow.com/users/2324685", "pm_score": 6, "selected": false, "text": "<p>The problem with AuthenticationSuccessEvent is it doesn't get published on remember-me login. If you're using remember-me authentication use InteractiveAuthenticationSuccessEvent instead, it works for normal login as well as for remember-me login.</p>\n\n<pre><code>@Component\npublic class LoginListener implements ApplicationListener&lt;InteractiveAuthenticationSuccessEvent&gt; {\n\n @Override\n public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event)\n {\n UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal();\n // ...\n }\n}\n</code></pre>\n" }, { "answer_id": 54063699, "author": "Sujit", "author_id": 10637296, "author_profile": "https://Stackoverflow.com/users/10637296", "pm_score": 3, "selected": false, "text": "<p>Another way using <code>@EventListener</code></p>\n\n<pre><code>@EventListener\npublic void doSomething(InteractiveAuthenticationSuccessEvent event) { // any spring event\n // your code \n\n}\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Which Template-Engine and Ajax-Framework/-Toolkit is able to load template information from JAR-Files?
You need to define a Spring Bean which implements [ApplicationListener](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/context/ApplicationListener.html). Then, in your code, do something like this: ```java public void onApplicationEvent(ApplicationEvent appEvent) { if (appEvent instanceof AuthenticationSuccessEvent) { AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) appEvent; UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal(); // .... } } ``` Then, in your applicationContext.xml file, just define that bean and it will automatically start receiving events :)
182,181
<p>I'm trying to call the SQL statement below but get the following error:</p> <blockquote> <p>System.Data.SqlClient.SqlException: Conversion failed when converting the varchar value '+@buildingIDs+' to data type int.</p> </blockquote> <pre><code>@"SELECT id, startDateTime, endDateTime FROM tb_bookings WHERE buildingID IN ('+@buildingIDs+') AND startDateTime &lt;= @fromDate"; </code></pre> <p><code>buildingID</code> is an <code>int</code> type column in the db. Will I need to pass the IDs as an array of ints?</p>
[ { "answer_id": 182219, "author": "Bravax", "author_id": 13911, "author_profile": "https://Stackoverflow.com/users/13911", "pm_score": -1, "selected": false, "text": "<p>It's trying to compare an int with the string value '+@buildingsIDs+'<br>\nSo it tries to convert the string to convert it to an int and fails.</p>\n\n<p>So do the following:<br>\n<code>\nbuildingsIDs = \"1, 5, 6\";<br>\n@\"SELECT id, startDateTime, endDateTime From tb_bookings WHERE buildingID IN (\" + buildingIDs + \") AND startDateTime &lt;= @fromDate\";\n</code></p>\n" }, { "answer_id": 182276, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 3, "selected": true, "text": "<p>Bravax's way is a bit dangerous. I'd go with the following so you don't get attacked with SQL Injections:</p>\n\n<pre><code>int[] buildingIDs = new int[] { 1, 2, 3 };\n\n/***/ @\"SELECT id, startDateTime, endDateTime From tb_bookings WHERE buildingID IN (\" +\n string.Join(\", \", buildingIDs.Select(id =&gt; id.ToString()).ToArray())\n + \") AND startDateTime &lt;= @fromDate\"; \n</code></pre>\n" }, { "answer_id": 182293, "author": "Vijesh VP", "author_id": 22016, "author_profile": "https://Stackoverflow.com/users/22016", "pm_score": 0, "selected": false, "text": "<p>I would rather suggest to go for a stored procedure, if possilble, and pass the lists of IDs as xml. You can get more details on this approach from <strong><a href=\"http://weblogs.asp.net/jgalloway/archive/2007/02/16/passing-lists-to-sql-server-2005-with-xml-parameters.aspx\" rel=\"nofollow noreferrer\">here</a></strong>.</p>\n" }, { "answer_id": 182300, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "<p>Note that LINQ can do this via Contains (which maps to IN). With regular TSQL, another option is to pass down the list as a CSV (etc) varchar, and use a table-valued UDF to split the varchar into pieces. This allows you to use a single TSQL query (doing an INNER JOIN to the UDF result).</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17510/" ]
I'm trying to call the SQL statement below but get the following error: > > System.Data.SqlClient.SqlException: Conversion failed when converting > the varchar value '+@buildingIDs+' to data type int. > > > ``` @"SELECT id, startDateTime, endDateTime FROM tb_bookings WHERE buildingID IN ('+@buildingIDs+') AND startDateTime <= @fromDate"; ``` `buildingID` is an `int` type column in the db. Will I need to pass the IDs as an array of ints?
Bravax's way is a bit dangerous. I'd go with the following so you don't get attacked with SQL Injections: ``` int[] buildingIDs = new int[] { 1, 2, 3 }; /***/ @"SELECT id, startDateTime, endDateTime From tb_bookings WHERE buildingID IN (" + string.Join(", ", buildingIDs.Select(id => id.ToString()).ToArray()) + ") AND startDateTime <= @fromDate"; ```
182,192
<p>ModRewrite can easily handle stripping the www off the front of my domain.<br> In .htaccess:</p> <pre><code>RewriteEngine On RewriteCond %{HTTPS} on RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^(.*)$ https://%1/$1 [R=301,L] RewriteCond %{HTTPS} off RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L] </code></pre> <p>But with SSL, the certificate check comes before the .htaccess rewrite, causing certificate error.<br> I would rather not buy an SSL certificate for the www only to redirect it.<br> Can you offer me a smarter solution? (btw EV Certificates are not available as wildcards)</p>
[ { "answer_id": 182205, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<p>You can get certificates with multiple domain names in them. Get one with <code>mydomain.com</code> and <code>www.mydomain.com</code>. I think it's also possible to buy \"wildcard\" certificates that will match any subdomain, but they cost much more.</p>\n" }, { "answer_id": 182265, "author": "Huibert Gill", "author_id": 1254442, "author_profile": "https://Stackoverflow.com/users/1254442", "pm_score": 1, "selected": false, "text": "<p>Depending on your situation you could look into <a href=\"http://www.cacert.org\" rel=\"nofollow noreferrer\">cacert</a>.</p>\n\n<p>After you are assured by enough people to gain 50 'points',\nyou can create your own server certs, as many as you want.</p>\n\n<p>Normaly you will be 'assured' by someone by meeting with him/her in real life, and showing some kind of ID (drivers license, passport).</p>\n\n<p>For more info read the site, or you pm me.</p>\n" }, { "answer_id": 193601, "author": "Jolyon", "author_id": 11740, "author_profile": "https://Stackoverflow.com/users/11740", "pm_score": 1, "selected": false, "text": "<p>In your situation, two options show promise:<br>\n1) When a secure connection is required, link to <a href=\"https://domain.com\" rel=\"nofollow noreferrer\">https://domain.com</a><br>\nKeeping part of your .htaccess redirection</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTPS} off\nRewriteCond %{HTTP_HOST} ^www\\.(.+)$ [NC]\nRewriteRule ^(.*)$ http://%1/$1 [R=301,L]\n</code></pre>\n\n<p>will prevent www.domain.com, and hopefully minimise <a href=\"https://www.domain.com\" rel=\"nofollow noreferrer\">https://www.domain.com</a><br>\n2) As others have suggested, get a separate certificate for <a href=\"https://www.domain.com\" rel=\"nofollow noreferrer\">https://www.domain.com</a><br>\n<a href=\"http://startssl.com\" rel=\"nofollow noreferrer\">startssl.com</a> have free certificates, suitable for a redirection only job like this.</p>\n" }, { "answer_id": 274099, "author": "Robert", "author_id": 35675, "author_profile": "https://Stackoverflow.com/users/35675", "pm_score": 1, "selected": false, "text": "<p>Many SSL Certificate providers, including DigiCert, GlobalSign, and possibly GoDaddy, will put the www in a certificate for free as a Subject Alternative Name. This means the certificate will work for both paypal.com and www.paypal.com. You can then just forward all traffic from <a href=\"https://www.paypal.com\" rel=\"nofollow noreferrer\">https://www.paypal.com</a> to <a href=\"https://paypal.com\" rel=\"nofollow noreferrer\">https://paypal.com</a>.</p>\n" }, { "answer_id": 10645117, "author": "arieltools", "author_id": 143866, "author_profile": "https://Stackoverflow.com/users/143866", "pm_score": 0, "selected": false, "text": "<p>What you are trying to do is impossible. If a user accesses www.domain.cc over SSL, then you will get a certificate error if you do not have a valid SSL certificate - even if all you want to do is redirect them to the correct site. </p>\n\n<p>You will either need a new certificate for www.domain.cc, or convince your registrar to give you a wildcard certificate for *.domain.cc, or one with multiple subjectAltName properties. See <a href=\"http://www.crsr.net/Notes/Apache-HTTPS-virtual-host.html\" rel=\"nofollow\">http://www.crsr.net/Notes/Apache-HTTPS-virtual-host.html</a> </p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11740/" ]
ModRewrite can easily handle stripping the www off the front of my domain. In .htaccess: ``` RewriteEngine On RewriteCond %{HTTPS} on RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^(.*)$ https://%1/$1 [R=301,L] RewriteCond %{HTTPS} off RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L] ``` But with SSL, the certificate check comes before the .htaccess rewrite, causing certificate error. I would rather not buy an SSL certificate for the www only to redirect it. Can you offer me a smarter solution? (btw EV Certificates are not available as wildcards)
You can get certificates with multiple domain names in them. Get one with `mydomain.com` and `www.mydomain.com`. I think it's also possible to buy "wildcard" certificates that will match any subdomain, but they cost much more.
182,229
<p>I'd like to run a script to populate my database. I'd like to access it through the Django database API.</p> <p>The only problem is that I don't know what I would need to import to gain access to this.</p> <p>How can this be achieved?</p>
[ { "answer_id": 182275, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 0, "selected": false, "text": "<p>In addition to your own models files, you need to import your settings module as well.</p>\n" }, { "answer_id": 182345, "author": "kender", "author_id": 4172, "author_profile": "https://Stackoverflow.com/users/4172", "pm_score": 5, "selected": true, "text": "<p>Import your settings module too</p>\n\n<pre><code>import os\nos.environ[\"DJANGO_SETTINGS_MODULE\"] = \"mysite.settings\"\n\nfrom mysite.polls.models import Poll, Choice\n</code></pre>\n\n<p>should do the trick.</p>\n" }, { "answer_id": 182790, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>If you use the <code>shell</code> argument to the <code>manage.py</code> script in your project directory, you don't have to import the settings manually:</p>\n\n<pre><code>$ cd mysite/\n$ ./manage.py shell\nPython 2.5.2 (r252:60911, Jun 10 2008, 10:35:34) \n[GCC 4.0.1 (Apple Inc. build 5465)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n&gt;&gt;&gt; from myapp.models import *\n&gt;&gt;&gt;\n</code></pre>\n\n<p>For non-interactive use you could implement a <a href=\"http://docs.djangoproject.com/en/dev/howto/custom-management-commands/\" rel=\"nofollow noreferrer\">custom command</a> and run it with <code>manage.py</code>.</p>\n" }, { "answer_id": 184898, "author": "Sam Corder", "author_id": 2351, "author_profile": "https://Stackoverflow.com/users/2351", "pm_score": 3, "selected": false, "text": "<p>This is what I have at the top of one my data loading scripts.</p>\n\n<pre><code>import string\nimport sys\ntry:\n import settings # Assumed to be in the same directory.\n #settings.DISABLE_TRANSACTION_MANAGEMENT = True\nexcept ImportError:\n sys.stderr.write(\"Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\\nYou'll have to run django-admin.py, passing it your settings module.\\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\\n\" % __file__)\nsys.exit(1)\n\n#Setup the django environment with the settings module.\nimport django\nimport django.core.management\ndjango.core.management.setup_environ(settings)\n\nfrom django.db import transaction\n</code></pre>\n\n<p>This should all execute before you do much else in your script.</p>\n\n<p>Another method is to use fixtures and manage.py. Though if you are just trying to accomplish a bulk data load to initialize a database this should work fine.</p>\n\n<p>Also depending on what you are doing you may or may not want to do it all in one transaction. Uncomment the transaction line above and structure your code similar to this.</p>\n\n<pre><code>transaction.enter_transaction_management()\ntry:\n #Do some stuff\n transaction.commit()\nfinally:\n transaction.rollback()\n pass\ntransaction.leave_transaction_management()\n</code></pre>\n" }, { "answer_id": 7870288, "author": "Thomas", "author_id": 374250, "author_profile": "https://Stackoverflow.com/users/374250", "pm_score": 1, "selected": false, "text": "<p>The cleanest solution is to add django extensions.</p>\n\n<pre>\n(virt1)tsmets@calvin:~/Documents/prive/rugby-club/proposal/kitu$ yolk -l\nDjango - 1.3.1 - active \nPygments - 1.4 - active \nPython - 2.6.5 - active development (/usr/lib/python2.6/lib-dynload)\ndjango-extensions - 0.7.1 - active \npip - 1.0.2 - active \nsetuptools - 0.6c11 - active \nwsgiref - 0.1.2 - active development (/usr/lib/python2.6)\nyolk - 0.4.1 - active \n</pre>\n\n<p>The list of possible commands is then extended with among other things the runscript command.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15616/" ]
I'd like to run a script to populate my database. I'd like to access it through the Django database API. The only problem is that I don't know what I would need to import to gain access to this. How can this be achieved?
Import your settings module too ``` import os os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings" from mysite.polls.models import Poll, Choice ``` should do the trick.
182,243
<p>I am trying to recreate a Perl script in C# but have a problem creating a checksum value that a target system needs.</p> <p>In Perl this checksum is calculated using the <code>unpack</code> function:</p> <pre><code>while (&lt;PACKAGE&gt;) { $checksum += unpack("%32C*", $_); } $checksum %= 32767; close(PACKAGE); </code></pre> <p>where <code>PACKAGE</code> is the .tar file input stream</p> <p>I need to replicate this in C# but can't find a means of replicating that <code>unpack</code> function.</p> <p>All help appreciated!</p> <p>(I know there are much better checksum calculations available but can't change target system so can't change calculation) </p>
[ { "answer_id": 182254, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 3, "selected": false, "text": "<p>There seems to be a library in Mono called <a href=\"http://www.mono-project.com/Mono_DataConvert\" rel=\"nofollow noreferrer\">DataConvert</a> that was written to provide facilities similar to Perl's pack/unpack. Does this do what you need?</p>\n" }, { "answer_id": 182257, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 2, "selected": false, "text": "<p>Perkl's unpack is described <a href=\"http://www.perl.com/doc/manual/html/pod/perlfunc/unpack.html\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://www.catonmat.net/blog/wp-content/plugins/wp-downloadMonitor/user_uploads/perl.pack.unpack.printf.cheat.sheet.pdf\" rel=\"nofollow noreferrer\">here</a>. From that you should be able to write an equivalent in C#.</p>\n" }, { "answer_id": 182266, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "<p>To supplement Mitch Wheat's comment, here's a Java implementation (which does a single block only). I'm sure you'll find a way to convert it into C#, and to do multiple blocks.</p>\n\n<pre><code>int sum = 0;\nfor (byte b : buffer) {\n sum += (int) b &amp; 255;\n}\nreturn sum % 32767;\n</code></pre>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 185057, "author": "piCookie", "author_id": 8763, "author_profile": "https://Stackoverflow.com/users/8763", "pm_score": 0, "selected": false, "text": "<p>In my testing here, unpack with %32C appears to be the additive sum of the bytes, limited to 32 bits.</p>\n\n<pre><code>print unpack(\"%32C*\", 'A');\n65\nprint unpack(\"%32C*\", 'AA');\n130\n</code></pre>\n\n<p>It shouldn't be hard to reproduce that.</p>\n" }, { "answer_id": 28964314, "author": "Guillermo Veneranda", "author_id": 4653939, "author_profile": "https://Stackoverflow.com/users/4653939", "pm_score": 0, "selected": false, "text": "<p>Based on the comments of Chris Jester-Young and piCookie, I developed the following function. I hope you find it useful.</p>\n\n<pre><code>int fileCheckSum(const char *fileName)\n{\n FILE *fp;\n long fileSize;\n char *fileBuffer;\n size_t result;\n int sum = 0;\n long index;\n\n fp = fopen(fileName, \"rb\");\n if (fp == NULL)\n {\n fputs (\"File error\",stderr); \n exit (1);\n }\n\n fseek(fp, 0L, SEEK_END);\n fileSize = ftell(fp);\n fseek(fp, 0L, SEEK_SET);\n\n fileBuffer = (char*) malloc (sizeof(char) * fileSize); \n if (fileBuffer == NULL)\n {\n fputs (\"Memory error\",stderr);\n exit (2);\n }\n\n result = fread(fileBuffer, 1, fileSize, fp); \n if (result != fileSize)\n {\n fputs (\"Reading error\", stderr);\n if (fileBuffer != NULL)\n free(fileBuffer);\n\n exit (3);\n }\n\n for (index = 0; index &lt; fileSize; index++)\n {\n sum += fileBuffer[index] &amp; 255;\n }\n\n fclose(fp);\n if (fileBuffer != NULL)\n free(fileBuffer);\n\n return sum % 32767; \n}\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to recreate a Perl script in C# but have a problem creating a checksum value that a target system needs. In Perl this checksum is calculated using the `unpack` function: ``` while (<PACKAGE>) { $checksum += unpack("%32C*", $_); } $checksum %= 32767; close(PACKAGE); ``` where `PACKAGE` is the .tar file input stream I need to replicate this in C# but can't find a means of replicating that `unpack` function. All help appreciated! (I know there are much better checksum calculations available but can't change target system so can't change calculation)
There seems to be a library in Mono called [DataConvert](http://www.mono-project.com/Mono_DataConvert) that was written to provide facilities similar to Perl's pack/unpack. Does this do what you need?
182,253
<p>I love Python because it comes batteries included, and I use built-in functions, a lot, to do the dirty job for me.</p> <p>I have always been using happily the os.path module to deal with file path but recently I ended up with unexpected results on Python 2.5 under Ubuntu linux, while dealing with string that represent windows file paths :</p> <pre><code>filepath = r"c:\ttemp\FILEPA~1.EXE" print os.path.basename(filepath) 'c:\\ttemp\\FILEPA~1.EXE'] print os.path.splitdrive(filepath) ('', 'c:\ttemp\\FILEPA~1.EXE') </code></pre> <p>WTF ?</p> <p>It ends up the same way with filepath = u"c:\ttemp\FILEPA~1.EXE" and filepath = "c:\ttemp\FILEPA~1.EXE".</p> <p>Do you have a clue ? Ubuntu use UTF8 but I don't feel like it has something to do with it. Maybe my Python install is messed up but I did not perform any particular tweak on it that I can remember.</p>
[ { "answer_id": 182282, "author": "kender", "author_id": 4172, "author_profile": "https://Stackoverflow.com/users/4172", "pm_score": 2, "selected": false, "text": "<p>From a <code>os.path</code> documentation:</p>\n\n<p><strong>os.path.splitdrive(path)</strong><br>\nSplit the pathname path into a pair (drive, tail) where drive is either a drive specification or the empty string. On systems which do not use drive specifications, drive will always be the empty string. In all cases, drive + tail will be the same as path.</p>\n\n<p>If you running this on unix, it doesnt use drive specifications, hence - drive will be empty string. </p>\n\n<p>If you want to solve windows paths on any platform, you can just use a simple regexp:</p>\n\n<pre><code>import re\n(drive, tail) = re.compile('([a-zA-Z]\\:){0,1}(.*)').match(filepath).groups() \n</code></pre>\n\n<p><code>drive</code> will be a drive letter followed by <code>:</code> (eg. <code>c:</code>, <code>u:</code>) or <code>None</code>, and <code>tail</code> the whole rest :)</p>\n" }, { "answer_id": 182283, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 1, "selected": false, "text": "<p>See the documentation <a href=\"http://pydoc.org/2.5.1/posixpath.html\" rel=\"nofollow noreferrer\">here</a>, specifically: </p>\n\n<blockquote>\n <p>splitdrive(p) Split a pathname into\n drive and path. <strong>On Posix, drive is\n always empty.</strong></p>\n</blockquote>\n\n<p>So this won't work on a Linux box.</p>\n" }, { "answer_id": 182417, "author": "Moe", "author_id": 3051, "author_profile": "https://Stackoverflow.com/users/3051", "pm_score": 6, "selected": true, "text": "<p>If you want to manipulate Windows paths on linux you should use the ntpath module (this is the module that is imported as os.path on windows - posixpath is imported as os.path on linux)</p>\n\n<pre><code>&gt;&gt;&gt; import ntpath\n&gt;&gt;&gt; filepath = r\"c:\\ttemp\\FILEPA~1.EXE\"\n&gt;&gt;&gt; print ntpath.basename(filepath)\nFILEPA~1.EXE\n&gt;&gt;&gt; print ntpath.splitdrive(filepath)\n('c:', '\\\\ttemp\\\\FILEPA~1.EXE')\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9951/" ]
I love Python because it comes batteries included, and I use built-in functions, a lot, to do the dirty job for me. I have always been using happily the os.path module to deal with file path but recently I ended up with unexpected results on Python 2.5 under Ubuntu linux, while dealing with string that represent windows file paths : ``` filepath = r"c:\ttemp\FILEPA~1.EXE" print os.path.basename(filepath) 'c:\\ttemp\\FILEPA~1.EXE'] print os.path.splitdrive(filepath) ('', 'c:\ttemp\\FILEPA~1.EXE') ``` WTF ? It ends up the same way with filepath = u"c:\ttemp\FILEPA~1.EXE" and filepath = "c:\ttemp\FILEPA~1.EXE". Do you have a clue ? Ubuntu use UTF8 but I don't feel like it has something to do with it. Maybe my Python install is messed up but I did not perform any particular tweak on it that I can remember.
If you want to manipulate Windows paths on linux you should use the ntpath module (this is the module that is imported as os.path on windows - posixpath is imported as os.path on linux) ``` >>> import ntpath >>> filepath = r"c:\ttemp\FILEPA~1.EXE" >>> print ntpath.basename(filepath) FILEPA~1.EXE >>> print ntpath.splitdrive(filepath) ('c:', '\\ttemp\\FILEPA~1.EXE') ```
182,262
<p>Using Oracle, if a column value can be 'YES' or 'NO' is it possible to constrain a table so that only one row can have a 'YES' value?</p> <p>I would rather redesign the table structure but this is not possible.</p> <p>[UDPATE] Sadly, null values are not allowed in this table.</p>
[ { "answer_id": 182279, "author": "poezn", "author_id": 25842, "author_profile": "https://Stackoverflow.com/users/25842", "pm_score": 2, "selected": false, "text": "<p>It doesn't work on the table definition.</p>\n\n<p>However, if you update the table using a trigger calling a stored procedure, you could make sure that only one row contains \"YES\".</p>\n\n<ol>\n<li>Set all rows to \"NO\"</li>\n<li>Set the row you want to YES</li>\n</ol>\n" }, { "answer_id": 182299, "author": "yukondude", "author_id": 726, "author_profile": "https://Stackoverflow.com/users/726", "pm_score": 3, "selected": false, "text": "<p>This is a kludgy hack, but if the column allows NULLs, then you could use NULL in place of \"NO\" and use \"YES\" just as before. Apply a unique key constraint to that column, and you'll never get two \"YES\" values, but still have many NOs.</p>\n\n<p>Update: @Nick Pierpoint: suggested adding a check constraint so that the column values are restricted to just \"YES\" and NULL. The syntax is all worked out in his answer.</p>\n" }, { "answer_id": 182322, "author": "Matthias Meid", "author_id": 17713, "author_profile": "https://Stackoverflow.com/users/17713", "pm_score": 1, "selected": false, "text": "<p>Does Oracle support something like <strong>filtered indices</strong> (last week I heard that e.g. MSSQL2008 does)? Maybe you can define a <strong>unique key</strong> which applies only to rows with the value \"Yes\" in your column.</p>\n" }, { "answer_id": 182427, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 5, "selected": true, "text": "<p>Use a function-based index:</p>\n\n<pre><code>create unique index only_one_yes on mytable\n(case when col='YES' then 'YES' end);\n</code></pre>\n\n<p>Oracle only indexes keys that are not completely null, and the CASE expression here ensures that all the 'NO' values are changed to nulls and so not indexed.</p>\n" }, { "answer_id": 182459, "author": "Rimas Kudelis", "author_id": 25804, "author_profile": "https://Stackoverflow.com/users/25804", "pm_score": -1, "selected": false, "text": "<p>I guess I'd use a second table to point to the appropriate row in your current table. That other table could be used to store values of other variables too too.</p>\n" }, { "answer_id": 182490, "author": "Nick Pierpoint", "author_id": 4003, "author_profile": "https://Stackoverflow.com/users/4003", "pm_score": 2, "selected": false, "text": "<p>Following on from my comment to a previous answer by yukondude, I'd add a unique index and a check constraint:</p>\n\n<pre><code>create table mytest (\n yesorno varchar2(3 char)\n);\n\ncreate unique index uk_mytest_yesorno on mytest(yesorno);\n\nalter table mytest add constraint ck_mytest_yesorno check (yesorno is null or yesorno = 'YES');\n</code></pre>\n" }, { "answer_id": 183371, "author": "Guy", "author_id": 993, "author_profile": "https://Stackoverflow.com/users/993", "pm_score": 2, "selected": false, "text": "<p>You will want to check a Tom Kyte article with exactly this question being asked and his answer:</p>\n\n<p><a href=\"http://tkyte.blogspot.com/2008/05/another-of-day.html\" rel=\"nofollow noreferrer\">http://tkyte.blogspot.com/2008/05/another-of-day.html</a></p>\n\n<p>Summary: don't use triggers, don't use autonomous transactions, use two tables.</p>\n\n<p>If you use an Oracle database, then you MUST get to know <a href=\"http://asktom.oracle.com\" rel=\"nofollow noreferrer\">AskTom</a> and get his books.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26108/" ]
Using Oracle, if a column value can be 'YES' or 'NO' is it possible to constrain a table so that only one row can have a 'YES' value? I would rather redesign the table structure but this is not possible. [UDPATE] Sadly, null values are not allowed in this table.
Use a function-based index: ``` create unique index only_one_yes on mytable (case when col='YES' then 'YES' end); ``` Oracle only indexes keys that are not completely null, and the CASE expression here ensures that all the 'NO' values are changed to nulls and so not indexed.
182,278
<p>I would like to be able to write a Java class in one package which can access non-public methods of a class in another package without having to make it a subclass of the other class. Is this possible?</p>
[ { "answer_id": 182285, "author": "NR.", "author_id": 11701, "author_profile": "https://Stackoverflow.com/users/11701", "pm_score": 1, "selected": false, "text": "<p>Not using a keyword or so.</p>\n\n<p>You could \"cheat\" using reflection etc., but I wouldn't recommend \"cheating\".</p>\n" }, { "answer_id": 182320, "author": "Black", "author_id": 25234, "author_profile": "https://Stackoverflow.com/users/25234", "pm_score": 3, "selected": false, "text": "<p>As far as I know, it is not possible.</p>\n\n<p>Maybe, You could give us some more details about Your design. Questions like these are likely the result of design flaws.</p>\n\n<p>Just consider</p>\n\n<ul>\n<li>Why are those classes in different packages, if they are so closely related?</li>\n<li>Has A to access private members of B or should the operation be moved to class B and triggered by A?</li>\n<li>Is this really calling or is event-handling better?</li>\n</ul>\n" }, { "answer_id": 182324, "author": "Omar Kooheji", "author_id": 20400, "author_profile": "https://Stackoverflow.com/users/20400", "pm_score": 0, "selected": false, "text": "<p>If you want to access protected methods you could create a subclass of the class you want to use that exposes the methods you want to use as public (or internal to the namespace to be safer), and have an instance of that class in your class (use it as a proxy).</p>\n\n<p>As far as private methods are concerned (I think) you are out of luck. </p>\n" }, { "answer_id": 182370, "author": "David G", "author_id": 3150, "author_profile": "https://Stackoverflow.com/users/3150", "pm_score": 6, "selected": false, "text": "<p>The designers of Java explicitly rejected the idea of friend as it works in C++. You put your \"friends\" in the same package. Private, protected, and packaged security is enforced as part of the language design. </p>\n\n<p>James Gosling wanted Java to be C++ without the mistakes. I believe he felt that friend was a mistake because it violates OOP principles. Packages provide a reasonable way to organize components without being too purist about OOP.</p>\n\n<p>NR pointed out that you could cheat using reflection, but even that only works if you aren't using the SecurityManager. If you turn on Java standard security, you won't be able to cheat with reflection unless you write security policy to specifically allow it.</p>\n" }, { "answer_id": 183127, "author": "Ran Biron", "author_id": 931, "author_profile": "https://Stackoverflow.com/users/931", "pm_score": -1, "selected": false, "text": "<p>I once saw a reflection based solution that did \"friend checking\" at runtime using reflection and checking the call stack to see if the class calling the method was permitted to do so. Being a runtime check, it has the obvious drawback.</p>\n" }, { "answer_id": 316838, "author": "Matthew Murdoch", "author_id": 4023, "author_profile": "https://Stackoverflow.com/users/4023", "pm_score": 7, "selected": true, "text": "<p>The 'friend' concept is useful in Java, for example, to separate an API from its implementation. It is common for implementation classes to need access to API class internals but these should not be exposed to API clients. This can be achieved using the 'Friend Accessor' pattern as detailed below:</p>\n\n<p>The class exposed through the API:</p>\n\n<pre><code>package api;\n\npublic final class Exposed {\n static {\n // Declare classes in the implementation package as 'friends'\n Accessor.setInstance(new AccessorImpl());\n }\n\n // Only accessible by 'friend' classes.\n Exposed() {\n\n }\n\n // Only accessible by 'friend' classes.\n void sayHello() {\n System.out.println(\"Hello\");\n }\n\n static final class AccessorImpl extends Accessor {\n protected Exposed createExposed() {\n return new Exposed();\n }\n\n protected void sayHello(Exposed exposed) {\n exposed.sayHello();\n }\n }\n}\n</code></pre>\n\n<p>The class providing the 'friend' functionality:</p>\n\n<pre><code>package impl;\n\npublic abstract class Accessor {\n\n private static Accessor instance;\n\n static Accessor getInstance() {\n Accessor a = instance;\n if (a != null) {\n return a;\n }\n\n return createInstance();\n }\n\n private static Accessor createInstance() {\n try {\n Class.forName(Exposed.class.getName(), true, \n Exposed.class.getClassLoader());\n } catch (ClassNotFoundException e) {\n throw new IllegalStateException(e);\n }\n\n return instance;\n }\n\n public static void setInstance(Accessor accessor) {\n if (instance != null) {\n throw new IllegalStateException(\n \"Accessor instance already set\");\n }\n\n instance = accessor;\n }\n\n protected abstract Exposed createExposed();\n\n protected abstract void sayHello(Exposed exposed);\n}\n</code></pre>\n\n<p>Example access from a class in the 'friend' implementation package:</p>\n\n<pre><code>package impl;\n\npublic final class FriendlyAccessExample {\n public static void main(String[] args) {\n Accessor accessor = Accessor.getInstance();\n Exposed exposed = accessor.createExposed();\n accessor.sayHello(exposed);\n }\n}\n</code></pre>\n" }, { "answer_id": 348637, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I prefer delegation or composition or factory class (depending upon the issue that results in this problem) to avoid making it a public class. </p>\n\n<p>If it is a \"interface/implementation classes in different packages\" problem, then I would use a public factory class that would in the same package as the impl package and prevent the exposure of the impl class.</p>\n\n<p>If it is a \"I hate to make this class/method public just to provide this functionality for some other class in a different package\" problem, then I would use a public delegate class in the same package and expose only that part of the functionality needed by the \"outsider\" class.</p>\n\n<p>Some of these decisions are driven by the target server classloading architecture (OSGi bundle, WAR/EAR, etc.), deployment and package naming conventions. For example, the above proposed solution, 'Friend Accessor' pattern is clever for normal java applications. I wonder if it gets tricky to implement it in OSGi due to the difference in classloading style.</p>\n" }, { "answer_id": 1533414, "author": "eirikma", "author_id": 82991, "author_profile": "https://Stackoverflow.com/users/82991", "pm_score": 2, "selected": false, "text": "<p>The provided solution was perhaps not the simplest. Another approach is based on the same idea as in C++: private members are not accessible outside the package/private scope, except for a specific class that the owner makes a friend of itself. </p>\n\n<p>The class that needs friend access to a member should create a inner public abstract \"friend class\" that the class owning the hidden properties can export access to, by returning a subclass that implement the access-implementing methods. The \"API\" method of the friend class can be private so it is not accessible outside the class that needs friend access. Its only statement is a call to an abstract protected member that the exporting class implements. </p>\n\n<p>Here's the code:</p>\n\n<p>First the test that verifies that this actually works:</p>\n\n<pre><code>package application;\n\nimport application.entity.Entity;\nimport application.service.Service;\nimport junit.framework.TestCase;\n\npublic class EntityFriendTest extends TestCase {\n public void testFriendsAreOkay() {\n Entity entity = new Entity();\n Service service = new Service();\n assertNull(\"entity should not be processed yet\", entity.getPublicData());\n service.processEntity(entity);\n assertNotNull(\"entity should be processed now\", entity.getPublicData());\n }\n}\n</code></pre>\n\n<p>Then the Service that needs friend access to a package private member of Entity:</p>\n\n<pre><code>package application.service;\n\nimport application.entity.Entity;\n\npublic class Service {\n\n public void processEntity(Entity entity) {\n String value = entity.getFriend().getEntityPackagePrivateData();\n entity.setPublicData(value);\n }\n\n /**\n * Class that Entity explicitly can expose private aspects to subclasses of.\n * Public, so the class itself is visible in Entity's package.\n */\n public static abstract class EntityFriend {\n /**\n * Access method: private not visible (a.k.a 'friendly') outside enclosing class.\n */\n private String getEntityPackagePrivateData() {\n return getEntityPackagePrivateDataImpl();\n }\n\n /** contribute access to private member by implementing this */\n protected abstract String getEntityPackagePrivateDataImpl();\n }\n}\n</code></pre>\n\n<p>Finally: the Entity class that provides friendly access to a package private member only to the class application.service.Service. </p>\n\n<pre><code>package application.entity;\n\nimport application.service.Service;\n\npublic class Entity {\n\n private String publicData;\n private String packagePrivateData = \"secret\"; \n\n public String getPublicData() {\n return publicData;\n }\n\n public void setPublicData(String publicData) {\n this.publicData = publicData;\n }\n\n String getPackagePrivateData() {\n return packagePrivateData;\n }\n\n /** provide access to proteced method for Service'e helper class */\n public Service.EntityFriend getFriend() {\n return new Service.EntityFriend() {\n protected String getEntityPackagePrivateDataImpl() {\n return getPackagePrivateData();\n }\n };\n }\n}\n</code></pre>\n\n<p>Okay, I must admit it is a bit longer than \"friend service::Service;\" but it might be possible to shorten it while retaining compile-time checking by using annotations. </p>\n" }, { "answer_id": 4428099, "author": "daitangio", "author_id": 75540, "author_profile": "https://Stackoverflow.com/users/75540", "pm_score": 1, "selected": false, "text": "<p>In Java it is possible to have a \"package-related friendness\". \nThis can be userful for unit testing.\nIf you do not specify private/public/protected in front of a method, it will be \"friend in the package\".\nA class in the same package will be able to access it, but it will be private outside the class.</p>\n\n<p>This rule is not always known, and it is a good approximation of a C++ \"friend\" keyword.\nI find it a good replacement.</p>\n" }, { "answer_id": 6154633, "author": "Jeff Axelrod", "author_id": 403455, "author_profile": "https://Stackoverflow.com/users/403455", "pm_score": 4, "selected": false, "text": "<p>There are two solutions to your question that don't involve keeping all classes in the same package. </p>\n\n<p>The first is to use the Friend Accessor/<a href=\"http://wiki.apidesign.org/wiki/APIDesignPatterns:FriendPackages\" rel=\"nofollow noreferrer\">Friend Package</a> pattern described in (Practical API Design, Tulach 2008).</p>\n\n<p>The second is to use OSGi. There is an article <a href=\"http://www.1biznow.com/2009/02/hide-private-parts-of-your-bundle.html\" rel=\"nofollow noreferrer\">here</a> explaining how OSGi accomplishes this. </p>\n\n<p>Related Questions: <a href=\"https://stackoverflow.com/questions/5872124/how-to-hide-the-internal-structure-of-a-java-api-to-the-rest-of-the-world/6154321#6154321\">1</a>, <a href=\"https://stackoverflow.com/questions/4759692/hiding-classes-in-a-jar-file\">2</a>, and <a href=\"https://stackoverflow.com/questions/4647599/why-friend-directive-is-missing-in-java\">3</a>.</p>\n" }, { "answer_id": 7101728, "author": "AriG", "author_id": 899773, "author_profile": "https://Stackoverflow.com/users/899773", "pm_score": 2, "selected": false, "text": "<p>eirikma's answer is easy and excellent. I might add one more thing: instead of having a publicly accessible method, getFriend() to get a friend which cannot be used, you could go one step further and disallow getting the friend without a token: getFriend(Service.FriendToken). This FriendToken would be an inner public class with a private constructor, so that only Service could instantiate one.</p>\n" }, { "answer_id": 9878042, "author": "Sephiroth", "author_id": 966527, "author_profile": "https://Stackoverflow.com/users/966527", "pm_score": 1, "selected": false, "text": "<p>I think that friend classes in C++ are like inner-class concept in Java. Using inner-classes\nyou can actually define an enclosing class and an enclosed one. Enclosed class has full access to the public and private members of it's enclosing class.\nsee the following link:\n<a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html\" rel=\"nofollow\">http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html</a></p>\n" }, { "answer_id": 11999192, "author": "Casebash", "author_id": 165495, "author_profile": "https://Stackoverflow.com/users/165495", "pm_score": 0, "selected": false, "text": "<p>I agree that in most cases the friend keyword is unnecessary.</p>\n\n<ul>\n<li>Package-private (aka. default) is sufficient in most cases where you have a group of heavily intertwined classes</li>\n<li>For debug classes that want access to internals, I usually make the method private and access it via reflection. Speed usually isn't important here</li>\n<li>Sometimes, you implement a method that is a \"hack\" or otherwise which is subject to change. I make it public, but use @Deprecated to indicate that you shouldn't rely on this method existing.</li>\n</ul>\n\n<p>And finally, if it really is necessary, there is the friend accessor pattern mentioned in the other answers.</p>\n" }, { "answer_id": 18634125, "author": "Salomon BRYS", "author_id": 1269640, "author_profile": "https://Stackoverflow.com/users/1269640", "pm_score": 9, "selected": false, "text": "<p><strong>Here is a small trick that I use in JAVA to replicate C++ friend mechanism.</strong></p>\n\n<p>Lets say I have a class <code>Romeo</code> and another class <code>Juliet</code>. They are in different packages (family) for hatred reasons.</p>\n\n<p><code>Romeo</code> wants to <code>cuddle</code> <code>Juliet</code> and <code>Juliet</code> wants to only let <code>Romeo</code> <code>cuddle</code> her.</p>\n\n<p>In C++, <code>Juliet</code> would declare <code>Romeo</code> as a (lover) <code>friend</code> but there are no such things in java.</p>\n\n<p>Here are the classes and the trick :</p>\n\n<p>Ladies first :</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>package capulet;\n\nimport montague.Romeo;\n\npublic class Juliet {\n\n public static void cuddle(Romeo.Love love) {\n Objects.requireNonNull(love);\n System.out.println(\"O Romeo, Romeo, wherefore art thou Romeo?\");\n }\n\n}\n</code></pre>\n\n<p>So the method <code>Juliet.cuddle</code> is <code>public</code> but you need a <code>Romeo.Love</code> to call it. It uses this <code>Romeo.Love</code> as a \"signature security\" to ensure that only <code>Romeo</code> can call this method and checks that the love is real so that the runtime will throw a <code>NullPointerException</code> if it is <code>null</code>.</p>\n\n<p>Now boys :</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>package montague;\n\nimport capulet.Juliet;\n\npublic class Romeo {\n public static final class Love { private Love() {} }\n private static final Love love = new Love();\n\n public static void cuddleJuliet() {\n Juliet.cuddle(love);\n }\n}\n</code></pre>\n\n<p>The class <code>Romeo.Love</code> is public, but its constructor is <code>private</code>. Therefore anyone can see it, but only <code>Romeo</code> can construct it. I use a static reference so the <code>Romeo.Love</code> that is never used is only constructed once and does not impact optimization.</p>\n\n<p>Therefore, <code>Romeo</code> can <code>cuddle</code> <code>Juliet</code> and only he can because only he can construct and access a <code>Romeo.Love</code> instance, which is required by <code>Juliet</code> to <code>cuddle</code> her (or else she'll slap you with a <code>NullPointerException</code>).</p>\n" }, { "answer_id": 22948824, "author": "jpfx1342", "author_id": 1709144, "author_profile": "https://Stackoverflow.com/users/1709144", "pm_score": 0, "selected": false, "text": "<p>A method I've found for solving this problem is to create an accessor object, like so:</p>\n\n<pre><code>class Foo {\n private String locked;\n\n /* Anyone can get locked. */\n public String getLocked() { return locked; }\n\n /* This is the accessor. Anyone with a reference to this has special access. */\n public class FooAccessor {\n private FooAccessor (){};\n public void setLocked(String locked) { Foo.this.locked = locked; }\n }\n private FooAccessor accessor;\n\n /** You get an accessor by calling this method. This method can only\n * be called once, so calling is like claiming ownership of the accessor. */\n public FooAccessor getAccessor() {\n if (accessor != null)\n throw new IllegalStateException(\"Cannot return accessor more than once!\");\n return accessor = new FooAccessor();\n }\n}\n</code></pre>\n\n<p>The first code to call <code>getAccessor()</code> \"claims ownership\" of the accessor. Usually, this is code that creates the object.</p>\n\n<pre><code>Foo bar = new Foo(); //This object is safe to share.\nFooAccessor barAccessor = bar.getAccessor(); //This one is not.\n</code></pre>\n\n<p>This also has an advantage over C++'s friend mechanism, because it allows you to limit access on a <em>per-instance</em> level, as opposed to a <em>per-class</em> level. By controlling the accessor reference, you control access to the object. You can also create multiple accessors, and give different access to each, which allows fine-grained control over what code can access what:</p>\n\n<pre><code>class Foo {\n private String secret;\n private String locked;\n\n /* Anyone can get locked. */\n public String getLocked() { return locked; }\n\n /* Normal accessor. Can write to locked, but not read secret. */\n public class FooAccessor {\n private FooAccessor (){};\n public void setLocked(String locked) { Foo.this.locked = locked; }\n }\n private FooAccessor accessor;\n\n public FooAccessor getAccessor() {\n if (accessor != null)\n throw new IllegalStateException(\"Cannot return accessor more than once!\");\n return accessor = new FooAccessor();\n }\n\n /* Super accessor. Allows access to secret. */\n public class FooSuperAccessor {\n private FooSuperAccessor (){};\n public String getSecret() { return Foo.this.secret; }\n }\n private FooSuperAccessor superAccessor;\n\n public FooSuperAccessor getAccessor() {\n if (superAccessor != null)\n throw new IllegalStateException(\"Cannot return accessor more than once!\");\n return superAccessor = new FooSuperAccessor();\n }\n}\n</code></pre>\n\n<p>Finally, if you'd like things to be a bit more organized, you can create a reference object, which holds everything together. This allows you to claim all accessors with one method call, as well as keep them together with their linked instance. Once you have the reference, you can pass the accessors out to the code that needs it:</p>\n\n<pre><code>class Foo {\n private String secret;\n private String locked;\n\n public String getLocked() { return locked; }\n\n public class FooAccessor {\n private FooAccessor (){};\n public void setLocked(String locked) { Foo.this.locked = locked; }\n }\n public class FooSuperAccessor {\n private FooSuperAccessor (){};\n public String getSecret() { return Foo.this.secret; }\n }\n public class FooReference {\n public final Foo foo;\n public final FooAccessor accessor;\n public final FooSuperAccessor superAccessor;\n\n private FooReference() {\n this.foo = Foo.this;\n this.accessor = new FooAccessor();\n this.superAccessor = new FooSuperAccessor();\n }\n }\n\n private FooReference reference;\n\n /* Beware, anyone with this object has *all* the accessors! */\n public FooReference getReference() {\n if (reference != null)\n throw new IllegalStateException(\"Cannot return reference more than once!\");\n return reference = new FooReference();\n }\n}\n</code></pre>\n\n<p>After much head-banging (not the good kind), this was my final solution, and I very much like it. It is flexible, simple to use, and allows very good control over class access. (The <em>with reference only</em> access is very useful.) If you use protected instead of private for the accessors/references, sub-classes of Foo can even return extended references from <code>getReference</code>. It also doesn't require any reflection, so it can be used in any environment.</p>\n" }, { "answer_id": 31983744, "author": "intrepidis", "author_id": 847235, "author_profile": "https://Stackoverflow.com/users/847235", "pm_score": 2, "selected": false, "text": "<p>Here's a clear use-case example with a reusable <code>Friend</code> class. The benefit of this mechanism is simplicity of use. Maybe good for giving unit test classes more access than the rest of the application.</p>\n\n<p>To begin, here is an example of how to use the <code>Friend</code> class.</p>\n\n<pre><code>public class Owner {\n private final String member = \"value\";\n\n public String getMember(final Friend friend) {\n // Make sure only a friend is accepted.\n friend.is(Other.class);\n return member;\n }\n}\n</code></pre>\n\n<p>Then in another package you can do this:</p>\n\n<pre><code>public class Other {\n private final Friend friend = new Friend(this);\n\n public void test() {\n String s = new Owner().getMember(friend);\n System.out.println(s);\n }\n}\n</code></pre>\n\n<p>The <code>Friend</code> class is as follows.</p>\n\n<pre><code>public final class Friend {\n private final Class as;\n\n public Friend(final Object is) {\n as = is.getClass();\n }\n\n public void is(final Class c) {\n if (c == as)\n return;\n throw new ClassCastException(String.format(\"%s is not an expected friend.\", as.getName()));\n }\n\n public void is(final Class... classes) {\n for (final Class c : classes)\n if (c == as)\n return;\n is((Class)null);\n }\n}\n</code></pre>\n\n<p>However, the problem is that it can be abused like so:</p>\n\n<pre><code>public class Abuser {\n public void doBadThings() {\n Friend badFriend = new Friend(new Other());\n String s = new Owner().getMember(badFriend);\n System.out.println(s);\n }\n}\n</code></pre>\n\n<p>Now, it may be true that the <code>Other</code> class doesn't have any public constructors, therefore making the above <code>Abuser</code> code impossible. However, if your class <i>does</i> have a public constructor then it is probably advisable to duplicate the Friend class as an inner class. Take this <code>Other2</code> class as an example:</p>\n\n<pre><code>public class Other2 {\n private final Friend friend = new Friend();\n\n public final class Friend {\n private Friend() {}\n public void check() {}\n }\n\n public void test() {\n String s = new Owner2().getMember(friend);\n System.out.println(s);\n }\n}\n</code></pre>\n\n<p>And then the <code>Owner2</code> class would be like this:</p>\n\n<pre><code>public class Owner2 {\n private final String member = \"value\";\n\n public String getMember(final Other2.Friend friend) {\n friend.check();\n return member;\n }\n}\n</code></pre>\n\n<p>Notice that the <code>Other2.Friend</code> class has a private constructor, thus making this a much more secure way of doing it.</p>\n" }, { "answer_id": 38703299, "author": "Chris", "author_id": 6360153, "author_profile": "https://Stackoverflow.com/users/6360153", "pm_score": 1, "selected": false, "text": "<p>I think, the approach of using the friend accessor pattern is way too complicated. I had to face the same problem and I solved using the good, old copy constructor, known from C++, in Java:</p>\n\n<pre><code>public class ProtectedContainer {\n protected String iwantAccess;\n\n protected ProtectedContainer() {\n super();\n iwantAccess = \"Default string\";\n }\n\n protected ProtectedContainer(ProtectedContainer other) {\n super();\n this.iwantAccess = other.iwantAccess;\n }\n\n public int calcSquare(int x) {\n iwantAccess = \"calculated square\";\n return x * x;\n }\n}\n</code></pre>\n\n<p>In your application you could write the following code:</p>\n\n<pre><code>public class MyApp {\n\n private static class ProtectedAccessor extends ProtectedContainer {\n\n protected ProtectedAccessor() {\n super();\n }\n\n protected PrivateAccessor(ProtectedContainer prot) {\n super(prot);\n }\n\n public String exposeProtected() {\n return iwantAccess;\n }\n }\n}\n</code></pre>\n\n<p>The advantage of this method is that only your application has access to the protected data. It's not exactly a substitution of the friend keyword. But I think it's quite suitable when you write custom libraries and you need to access protected data.</p>\n\n<p>Whenever you have to deal with instances of ProtectedContainer you can wrap your ProtectedAccessor around it and you gain access.</p>\n\n<p>It also works with protected methods. You define them protected in your API. Later in your application you write a private wrapper class and expose the protected method as public. That's it.</p>\n" }, { "answer_id": 46681855, "author": "Raphael", "author_id": 539599, "author_profile": "https://Stackoverflow.com/users/539599", "pm_score": -1, "selected": false, "text": "<p>As of Java 9, modules can be used to make this a non-issue in many cases.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4023/" ]
I would like to be able to write a Java class in one package which can access non-public methods of a class in another package without having to make it a subclass of the other class. Is this possible?
The 'friend' concept is useful in Java, for example, to separate an API from its implementation. It is common for implementation classes to need access to API class internals but these should not be exposed to API clients. This can be achieved using the 'Friend Accessor' pattern as detailed below: The class exposed through the API: ``` package api; public final class Exposed { static { // Declare classes in the implementation package as 'friends' Accessor.setInstance(new AccessorImpl()); } // Only accessible by 'friend' classes. Exposed() { } // Only accessible by 'friend' classes. void sayHello() { System.out.println("Hello"); } static final class AccessorImpl extends Accessor { protected Exposed createExposed() { return new Exposed(); } protected void sayHello(Exposed exposed) { exposed.sayHello(); } } } ``` The class providing the 'friend' functionality: ``` package impl; public abstract class Accessor { private static Accessor instance; static Accessor getInstance() { Accessor a = instance; if (a != null) { return a; } return createInstance(); } private static Accessor createInstance() { try { Class.forName(Exposed.class.getName(), true, Exposed.class.getClassLoader()); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } return instance; } public static void setInstance(Accessor accessor) { if (instance != null) { throw new IllegalStateException( "Accessor instance already set"); } instance = accessor; } protected abstract Exposed createExposed(); protected abstract void sayHello(Exposed exposed); } ``` Example access from a class in the 'friend' implementation package: ``` package impl; public final class FriendlyAccessExample { public static void main(String[] args) { Accessor accessor = Accessor.getInstance(); Exposed exposed = accessor.createExposed(); accessor.sayHello(exposed); } } ```
182,287
<p>Why can't I pass the table name to a prepared PDO statement?</p> <pre><code>$stmt = $dbh-&gt;prepare('SELECT * FROM :table WHERE 1'); if ($stmt-&gt;execute(array(':table' =&gt; 'users'))) { var_dump($stmt-&gt;fetchAll()); } </code></pre> <p>Is there another safe way to insert a table name into a SQL query? With safe, I mean that I don't want to do</p> <pre><code>$sql = "SELECT * FROM $table WHERE 1" </code></pre>
[ { "answer_id": 182312, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 3, "selected": false, "text": "<p>Using the former isn't inherently more safe than the latter, you need to sanitize the input whether it's part of a parameter array or a simple variable. So I don't see anything wrong with using the latter form with <code>$table</code>, provided you make sure that the content of <code>$table</code> is safe (alphanum plus underscores?) before using it.</p>\n" }, { "answer_id": 182353, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 9, "selected": true, "text": "<p><strong>Table and Column names CANNOT be replaced by parameters in PDO.</strong></p>\n\n<p>In that case you will simply want to filter and sanitize the data manually. One way to do this is to pass in shorthand parameters to the function that will execute the query dynamically and then use a <code>switch()</code> statement to create a white list of valid values to be used for the table name or column name. That way no user input ever goes directly into the query. So for example:</p>\n\n<pre><code>function buildQuery( $get_var ) \n{\n switch($get_var)\n {\n case 1:\n $tbl = 'users';\n break;\n }\n\n $sql = \"SELECT * FROM $tbl\";\n}\n</code></pre>\n\n<p>By leaving no default case or using a default case that returns an error message you ensure that only values that you want used get used.</p>\n" }, { "answer_id": 15990488, "author": "IMSoP", "author_id": 157957, "author_profile": "https://Stackoverflow.com/users/157957", "pm_score": 7, "selected": false, "text": "<p>To understand <em>why</em> binding a table (or column) name doesn't work, you have to understand how the placeholders in prepared statements work: they are not simply substituted in as (suitably escaped) strings, and the resulting SQL executed. Instead, a DBMS asked to \"prepare\" a statement comes up with a complete query plan for how it would execute that query, including which tables and indexes it would use, which will be the same regardless of how you fill in the placeholders.</p>\n\n<p>The plan for <code>SELECT name FROM my_table WHERE id = :value</code> will be the same whatever you substitute for <code>:value</code>, but the seemingly similar <code>SELECT name FROM :table WHERE id = :value</code> cannot be planned, because the DBMS has no idea what table you're actually going to select from.</p>\n\n<p>This is not something an abstraction library like PDO can or should work around, either, since it would defeat the 2 key purposes of prepared statements: 1) to allow the database to decide in advance how a query will be run, and use the same plan multiple times; and 2) to prevent security issues by separating the logic of the query from the variable input.</p>\n" }, { "answer_id": 16305689, "author": "Don", "author_id": 207069, "author_profile": "https://Stackoverflow.com/users/207069", "pm_score": 4, "selected": false, "text": "<p>I see this is an old post, but I found it useful and thought I'd share a solution similar to what @kzqai suggested:</p>\n\n<p>I have a function that receives two parameters like...</p>\n\n<pre><code>function getTableInfo($inTableName, $inColumnName) {\n ....\n}\n</code></pre>\n\n<p>Inside I check against arrays I've set up to make sure only tables and columns with \"blessed\" tables are accessible:</p>\n\n<pre><code>$allowed_tables_array = array('tblTheTable');\n$allowed_columns_array['tblTheTable'] = array('the_col_to_check');\n</code></pre>\n\n<p>Then the PHP check before running PDO looks like...</p>\n\n<pre><code>if(in_array($inTableName, $allowed_tables_array) &amp;&amp; in_array($inColumnName,$allowed_columns_array[$inTableName]))\n{\n $sql = \"SELECT $inColumnName AS columnInfo\n FROM $inTableName\";\n $stmt = $pdo-&gt;prepare($sql); \n $stmt-&gt;execute();\n $result = $stmt-&gt;fetchAll(PDO::FETCH_ASSOC);\n}\n</code></pre>\n" }, { "answer_id": 23353392, "author": "Phil LaNasa", "author_id": 2374900, "author_profile": "https://Stackoverflow.com/users/2374900", "pm_score": 1, "selected": false, "text": "<p>Part of me wonders if you could provide your own custom sanitizing function as simple as this:</p>\n\n<pre><code>$value = preg_replace('/[^a-zA-Z_]*/', '', $value);\n</code></pre>\n\n<p>I haven't really thought through it, but it seems like removing anything except characters and underscores might work.</p>\n" }, { "answer_id": 25748686, "author": "man", "author_id": 1881655, "author_profile": "https://Stackoverflow.com/users/1881655", "pm_score": 0, "selected": false, "text": "<p>As for the main question in this thread, the other posts made it clear why we can't bind values to column names when preparing statements, so here is one solution:</p>\n\n<pre><code>class myPdo{\n private $user = 'dbuser';\n private $pass = 'dbpass';\n private $host = 'dbhost';\n private $db = 'dbname';\n private $pdo;\n private $dbInfo;\n public function __construct($type){\n $this-&gt;pdo = new PDO('mysql:host='.$this-&gt;host.';dbname='.$this-&gt;db.';charset=utf8',$this-&gt;user,$this-&gt;pass);\n if(isset($type)){\n //when class is called upon, it stores column names and column types from the table of you choice in $this-&gt;dbInfo;\n $stmt = \"select distinct column_name,column_type from information_schema.columns where table_name='sometable';\";\n $stmt = $this-&gt;pdo-&gt;prepare($stmt);//not really necessary since this stmt doesn't contain any dynamic values;\n $stmt-&gt;execute();\n $this-&gt;dbInfo = $stmt-&gt;fetchAll(PDO::FETCH_ASSOC);\n }\n }\n public function pdo_param($col){\n $param_type = PDO::PARAM_STR;\n foreach($this-&gt;dbInfo as $k =&gt; $arr){\n if($arr['column_name'] == $col){\n if(strstr($arr['column_type'],'int')){\n $param_type = PDO::PARAM_INT;\n break;\n }\n }\n }//for testing purposes i only used INT and VARCHAR column types. Adjust to your needs...\n return $param_type;\n }\n public function columnIsAllowed($col){\n $colisAllowed = false;\n foreach($this-&gt;dbInfo as $k =&gt; $arr){\n if($arr['column_name'] === $col){\n $colisAllowed = true;\n break;\n }\n }\n return $colisAllowed;\n }\n public function q($data){\n //$data is received by post as a JSON object and looks like this\n //{\"data\":{\"column_a\":\"value\",\"column_b\":\"value\",\"column_c\":\"value\"},\"get\":\"column_x\"}\n $data = json_decode($data,TRUE);\n $continue = true;\n foreach($data['data'] as $column_name =&gt; $value){\n if(!$this-&gt;columnIsAllowed($column_name)){\n $continue = false;\n //means that someone possibly messed with the post and tried to get data from a column that does not exist in the current table, or the column name is a sql injection string and so on...\n break;\n }\n }\n //since $data['get'] is also a column, check if its allowed as well\n if(isset($data['get']) &amp;&amp; !$this-&gt;columnIsAllowed($data['get'])){\n $continue = false;\n }\n if(!$continue){\n exit('possible injection attempt');\n }\n //continue with the rest of the func, as you normally would\n $stmt = \"SELECT DISTINCT \".$data['get'].\" from sometable WHERE \";\n foreach($data['data'] as $k =&gt; $v){\n $stmt .= $k.' LIKE :'.$k.'_val AND ';\n }\n $stmt = substr($stmt,0,-5).\" order by \".$data['get'];\n //$stmt should look like this\n //SELECT DISTINCT column_x from sometable WHERE column_a LIKE :column_a_val AND column_b LIKE :column_b_val AND column_c LIKE :column_c_val order by column_x\n $stmt = $this-&gt;pdo-&gt;prepare($stmt);\n //obviously now i have to bindValue()\n foreach($data['data'] as $k =&gt; $v){\n $stmt-&gt;bindValue(':'.$k.'_val','%'.$v.'%',$this-&gt;pdo_param($k));\n //setting PDO::PARAM... type based on column_type from $this-&gt;dbInfo\n }\n $stmt-&gt;execute();\n return $stmt-&gt;fetchAll(PDO::FETCH_ASSOC);//or whatever\n }\n}\n$pdo = new myPdo('anything');//anything so that isset() evaluates to TRUE.\nvar_dump($pdo-&gt;q($some_json_object_as_described_above));\n</code></pre>\n\n<p>The above is just an example, so needless to say, copy->paste won't work. Adjust for your needs.\nNow this may not provide 100% security, but it allows some control over the column names when they \"come in\" as dynamic strings and may be changed on users end. Furthermore, there is no need to build some array with your table column names and types since they are extracted from the information_schema.</p>\n" }, { "answer_id": 53210496, "author": "Funk Forty Niner", "author_id": 1415724, "author_profile": "https://Stackoverflow.com/users/1415724", "pm_score": 2, "selected": false, "text": "<p><em>(Late answer, consult my side note).</em></p>\n\n<p>The same rule applies when trying to create a \"database\".</p>\n\n<p>You cannot use a prepared statement to bind a database.</p>\n\n<p>I.e.:</p>\n\n<pre><code>CREATE DATABASE IF NOT EXISTS :database\n</code></pre>\n\n<p>will not work. Use a safelist instead.</p>\n\n<p><strong>Side note:</strong> I added this answer (as a community wiki) because it often used to close questions with, where some people posted questions similar to this in trying to bind a <strong>database</strong> and not a table and/or column.</p>\n" }, { "answer_id": 69846926, "author": "totalnoob", "author_id": 9588276, "author_profile": "https://Stackoverflow.com/users/9588276", "pm_score": -1, "selected": false, "text": "<p>Short answer is NO you cannot use dynamic table name, field names, etc in the Prepared execute statement with PDO because it adds quotes to them which will break the query. But if you can sanitize them, then you can safely plop them right in the query itself just like you would with MySQLi anyway.</p>\n<p>The correct way to do this is with mysqli's mysqli_real_escape_string() function because the mysql_real_escape_string was removed from PHP hastily without any consideration into how that affects dynamic structure applications.</p>\n<pre><code>$unsanitized_table_name = &quot;users' OR '1'='1&quot;; //SQL Injection attempt\n$sanitized_table_name = sanitize_input($unsanitized_table_name);\n\n$stmt = $dbh-&gt;prepare(&quot;SELECT * FROM {$unsanitized_table_name} WHERE 1&quot;); //&lt;--- REALLY bad idea\n$stmt = $dbh-&gt;prepare(&quot;SELECT * FROM {$sanitized_table_name} WHERE 1&quot;); //&lt;--- Not ideal but hey, at least you're safe.\n\n//PDO Cant sanitize everything so we limp along with mysqli instead\nfunction sanitize_input($string)\n{\n $mysqli = new mysqli(&quot;localhost&quot;,&quot;UsahName&quot;,&quot;Passerrrd&quot;);\n $string = $mysqli-&gt;real_escape_string($string);\n\n return $string;\n}\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6681/" ]
Why can't I pass the table name to a prepared PDO statement? ``` $stmt = $dbh->prepare('SELECT * FROM :table WHERE 1'); if ($stmt->execute(array(':table' => 'users'))) { var_dump($stmt->fetchAll()); } ``` Is there another safe way to insert a table name into a SQL query? With safe, I mean that I don't want to do ``` $sql = "SELECT * FROM $table WHERE 1" ```
**Table and Column names CANNOT be replaced by parameters in PDO.** In that case you will simply want to filter and sanitize the data manually. One way to do this is to pass in shorthand parameters to the function that will execute the query dynamically and then use a `switch()` statement to create a white list of valid values to be used for the table name or column name. That way no user input ever goes directly into the query. So for example: ``` function buildQuery( $get_var ) { switch($get_var) { case 1: $tbl = 'users'; break; } $sql = "SELECT * FROM $tbl"; } ``` By leaving no default case or using a default case that returns an error message you ensure that only values that you want used get used.
182,349
<p>I am trying to find the index of a substring in a string that matches another string under a specific culture (provided from a System.CultureInfo). </p> <p>For example the string "ass" matches the substring "aß" in "straße" under a German culture.</p> <p>I can find the index of the start of the match using</p> <pre><code>culture.CompareInfo.IndexOf(value, substring); </code></pre> <p>but without resorting to brute force, is there an easy way of identifying that 2 characters were matched, and not 3?</p>
[ { "answer_id": 182366, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 0, "selected": false, "text": "<p>Does regular expressions handle that distinction of ss vs. ß?</p>\n" }, { "answer_id": 182376, "author": "Dave Van den Eynde", "author_id": 455874, "author_profile": "https://Stackoverflow.com/users/455874", "pm_score": 2, "selected": false, "text": "<p>If you use a capture group, you can capture the exact match that was found, and from that you can determine how many characters were matched.</p>\n\n<p>I'm a bit timestressed right now to give an example, so I hope you can figure it out from my description.</p>\n\n<p>Perhaps I'll ammend my answer later.</p>\n\n<p>Dave</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19995/" ]
I am trying to find the index of a substring in a string that matches another string under a specific culture (provided from a System.CultureInfo). For example the string "ass" matches the substring "aß" in "straße" under a German culture. I can find the index of the start of the match using ``` culture.CompareInfo.IndexOf(value, substring); ``` but without resorting to brute force, is there an easy way of identifying that 2 characters were matched, and not 3?
If you use a capture group, you can capture the exact match that was found, and from that you can determine how many characters were matched. I'm a bit timestressed right now to give an example, so I hope you can figure it out from my description. Perhaps I'll ammend my answer later. Dave
182,372
<p>What is the easiest way to check if events have been logged in the eventlog during a period of time?</p> <p>I want to perform a series of automated test steps and then check if any errors were logged to the Application Event Log, ignoring a few sources that I'm not interested in. I can use System.Diagnostics.EventLog and then look at the Entries collection, but it doesn't seem very useable for this scenario. For instance Entries.Count can get smaller over time if the event log is removing old entries. I'd prefer some way to either query the log or monitor it for changes during a period of time. e.g. </p> <pre><code>DateTime start = DateTime.Now; // do some stuff... foreach(EventLogEntry entry in CleverSolution.EventLogEntriesSince(start, "Application")) { // Now I can do stuff with entry, or ignore if its Source is one // that I don't care about. // ... } </code></pre>
[ { "answer_id": 182590, "author": "Tim Farley", "author_id": 4425, "author_profile": "https://Stackoverflow.com/users/4425", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx\" rel=\"nofollow noreferrer\">System.Diagnostics.EventLog</a> class really is the right way to do this.</p>\n\n<p>Your main objection seems to be that the log can remove old entries in some cases. But you say this is in a software testing scenario. Can't you arrange to configure your test systems such that the logs are large enough to contain all entries and the removal of old entries won't occur during your tests? </p>\n" }, { "answer_id": 182716, "author": "Rory", "author_id": 8479, "author_profile": "https://Stackoverflow.com/users/8479", "pm_score": 0, "selected": false, "text": "<p>Well the solution I've come up with does use <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx\" rel=\"nofollow noreferrer\">System.Diagnostics.EventLog</a> and simply iterating over all events to filter for the ones I want. I guess this is straightforward, I just thought there would have been a more efficient interface for this. Any suggestions or improvements very welcome!</p>\n\n<p>I've created a method to return event log entries since a certain time: </p>\n\n<pre><code>/// &lt;summary&gt;\n/// Steps through each of the entries in the specified event log and returns any that were written \n/// after the given point in time. \n/// &lt;/summary&gt;\n/// &lt;param name=\"logName\"&gt;The event log to inspect, eg \"Application\"&lt;/param&gt;\n/// &lt;param name=\"writtenSince\"&gt;The point in time to return entries from&lt;/param&gt;\n/// &lt;param name=\"type\"&gt;The type of entry to return, or null for all entry types&lt;/param&gt;\n/// &lt;returns&gt;A list of all entries of interest, which may be empty if there were none in the event log.&lt;/returns&gt;\npublic List&lt;EventLogEntry&gt; GetEventLogEntriesSince(string logName, DateTime writtenSince, EventLogEntryType type)\n{\n List&lt;EventLogEntry&gt; results = new List&lt;EventLogEntry&gt;();\n EventLog eventLog = new System.Diagnostics.EventLog(logName);\n foreach (EventLogEntry entry in eventLog.Entries)\n {\n if (entry.TimeWritten &gt; writtenSince &amp;&amp; (type==null || entry.EntryType == type))\n results.Add(entry);\n }\n return results;\n}\n</code></pre>\n\n<p>In my test class I store a timestamp:</p>\n\n<pre><code>private DateTime whenLastEventLogEntryWritten;\n</code></pre>\n\n<p>and during test setup I set the timestamp to when the last event log entry was written: </p>\n\n<pre><code>EventLog eventLog = new EventLog(\"Application\");\nwhenLastEventLogEntryWritten = eventLog.Entries.Count &gt; 0 ? \n eventLog.Entries[eventLog.Entries.Count - 1] : DateTime.Now;\n</code></pre>\n\n<p>At the end of my test I check that there were no event log errors: </p>\n\n<pre><code>Assert.IsEmpty(GetEventLogEntriesSince(\"Application\",\n whenLastEventLogEntryWritten, \n EventLogEntryType.Error), \n \"Application Event Log errors occurred during test execution.\");\n</code></pre>\n" }, { "answer_id": 183568, "author": "Tim Farley", "author_id": 4425, "author_profile": "https://Stackoverflow.com/users/4425", "pm_score": 4, "selected": true, "text": "<p>Just to be a good Wiki citizen and strive for completion, there are other ways. I didn't suggest it earlier because it is complete overkill for something that is only going to be run in-house as part of a test suite, and you said right in the title you wanted something easy.</p>\n\n<p>But if you need to see events as they occur in shipping code, read on. Believe it or not there are <em>three</em> different Windows APIs for this thing at this point.</p>\n\n<h2>NotifyChangeEventLog()</h2>\n\n<p>The original API for this sort of thing is called <a href=\"http://msdn.microsoft.com/en-us/library/aa363670(VS.85).aspx\" rel=\"noreferrer\">NotifyChangeEventLog()</a> and it was supported starting in Windows 2000. Essentially you use the <a href=\"http://msdn.microsoft.com/en-us/library/aa363654(VS.85).aspx\" rel=\"noreferrer\">WIN32 event log APIs</a> to open the event log, then you call this API with the handle you were given by the other API and an event handle. Windows will signal your event when there are new event log entries to look at.</p>\n\n<p>I never used this API myself, because most of my interest was in remote event log access and this API explicitly does <em>not</em> support remote logs. However, the rest of the API set this belongs to <em>does</em> let you sequentially read remote logs if you have the right permissions.</p>\n\n<h2>Windows Management Instrumentation</h2>\n\n<p>A second way is to use the <a href=\"http://msdn.microsoft.com/en-us/library/aa394582(VS.85).aspx\" rel=\"noreferrer\">Windows Management Instrumentation API</a>, and this does support both local and remote logs. This is a COM/DCOM based API that has existed for several years in Windows, and the .NET Framework has a nice implementation of it in the <a href=\"http://msdn.microsoft.com/en-us/library/system.management.aspx\" rel=\"noreferrer\">System.Management</a> namespace. Essentially what you do is create an <a href=\"http://msdn.microsoft.com/en-us/library/system.management.eventquery.aspx\" rel=\"noreferrer\">EventQuery</a> that looks for the appearance of new WMI objects of type (meaning within the WMI type system) of <a href=\"http://msdn.microsoft.com/en-us/library/aa394226(VS.85).aspx\" rel=\"noreferrer\">Win32_NTLogEvent</a>. The appearance of these will indicate new event log entries, and they will present pretty much in real time. The attributes on these objects contain all the details of the log entry. There's an <a href=\"http://msdn.microsoft.com/en-us/magazine/cc302051.aspx\" rel=\"noreferrer\">article from MSDN magazine</a> that talks about playing around with this stuff in Visual Studio.</p>\n\n<p>Again, this would be total overkill for a test application, it would require far more code than your existing solution. But years ago I wrote a subsystem for a network management application that used the DCOM flavor of this API to gather the event logs off of all the servers on a network so we could alert on particular ones. It was pretty slick and darn near real time. If you implement this in C++ with DCOM, be prepared to deal with Multithreaded Apartments and a lot of hairy logic to detect if/when your connection to the remote server goes up or down.</p>\n\n<h2>Windows Vista Event Log</h2>\n\n<p>Windows Vista (and Server 2008) have a whole new API suite relating to event logging and tracing. The <a href=\"http://msdn.microsoft.com/en-us/library/aa385780(VS.85).aspx\" rel=\"noreferrer\">new event log is documented here</a>. It looks like there is an API called EvtSubscribe that allows you to <a href=\"http://msdn.microsoft.com/en-us/library/aa385771(VS.85).aspx\" rel=\"noreferrer\">subscribe to events</a>. I have not used this API so I can't comment on its pros and cons.</p>\n" }, { "answer_id": 183768, "author": "Tim Farley", "author_id": 4425, "author_profile": "https://Stackoverflow.com/users/4425", "pm_score": 2, "selected": false, "text": "<p>That having been said, here's an answer that actually should be pretty straightforward even for your test application and is .NET Framework specific.</p>\n\n<p>You need to open the EventLog before you start your test, and subscribe an event handler to the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.entrywritten.aspx\" rel=\"nofollow noreferrer\">EventLog.EntryWritten</a> event. This is the way that .NET exposes the NotifyChangeEventLog() Win32 API.</p>\n\n<p>Move your current logic from <code>GetEventLogEntriesSince()</code> into the event handler, but instead of adding the events to a list for return, store them in a list you can retrieve from somewhere at the end of the run. You can retrieve the contents of the log entry from the EntryWrittenEventArgs argument which is passed, via its <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.entrywritteneventargs.entry.aspx\" rel=\"nofollow noreferrer\">Entry</a> property.</p>\n" }, { "answer_id": 183794, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 0, "selected": false, "text": "<p>I use this Powershell to scan the eventlog for relevant entries within the last 7 days:</p>\n\n<pre><code>$d=Get-Date\n$recent=[System.Management.ManagementDateTimeConverter]::ToDMTFDateTime($d.AddDays(-7))\n\nget-wmiobject -computer HOSTNAME -class Win32_NTLogEvent `\n -filter \"logfile = 'Application' and (sourcename = 'SOURCENAME' or sourcename like 'OTHERSOURCENAME%') and (type = 'error' or type = 'warning') AND (TimeGenerated &gt;='$recent')\" | \nsort-object @{ expression = {$_.TimeWritten} } -descending |\nselect SourceName, Message | \nformat-table @{Expression = { $_.SourceName};Width = 20;Label=\"SourceName\"}, Message\n</code></pre>\n\n<p>If you use C# (tagged, but not mentioned in the question), the magic lies in the get-wmiobject query.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8479/" ]
What is the easiest way to check if events have been logged in the eventlog during a period of time? I want to perform a series of automated test steps and then check if any errors were logged to the Application Event Log, ignoring a few sources that I'm not interested in. I can use System.Diagnostics.EventLog and then look at the Entries collection, but it doesn't seem very useable for this scenario. For instance Entries.Count can get smaller over time if the event log is removing old entries. I'd prefer some way to either query the log or monitor it for changes during a period of time. e.g. ``` DateTime start = DateTime.Now; // do some stuff... foreach(EventLogEntry entry in CleverSolution.EventLogEntriesSince(start, "Application")) { // Now I can do stuff with entry, or ignore if its Source is one // that I don't care about. // ... } ```
Just to be a good Wiki citizen and strive for completion, there are other ways. I didn't suggest it earlier because it is complete overkill for something that is only going to be run in-house as part of a test suite, and you said right in the title you wanted something easy. But if you need to see events as they occur in shipping code, read on. Believe it or not there are *three* different Windows APIs for this thing at this point. NotifyChangeEventLog() ---------------------- The original API for this sort of thing is called [NotifyChangeEventLog()](http://msdn.microsoft.com/en-us/library/aa363670(VS.85).aspx) and it was supported starting in Windows 2000. Essentially you use the [WIN32 event log APIs](http://msdn.microsoft.com/en-us/library/aa363654(VS.85).aspx) to open the event log, then you call this API with the handle you were given by the other API and an event handle. Windows will signal your event when there are new event log entries to look at. I never used this API myself, because most of my interest was in remote event log access and this API explicitly does *not* support remote logs. However, the rest of the API set this belongs to *does* let you sequentially read remote logs if you have the right permissions. Windows Management Instrumentation ---------------------------------- A second way is to use the [Windows Management Instrumentation API](http://msdn.microsoft.com/en-us/library/aa394582(VS.85).aspx), and this does support both local and remote logs. This is a COM/DCOM based API that has existed for several years in Windows, and the .NET Framework has a nice implementation of it in the [System.Management](http://msdn.microsoft.com/en-us/library/system.management.aspx) namespace. Essentially what you do is create an [EventQuery](http://msdn.microsoft.com/en-us/library/system.management.eventquery.aspx) that looks for the appearance of new WMI objects of type (meaning within the WMI type system) of [Win32\_NTLogEvent](http://msdn.microsoft.com/en-us/library/aa394226(VS.85).aspx). The appearance of these will indicate new event log entries, and they will present pretty much in real time. The attributes on these objects contain all the details of the log entry. There's an [article from MSDN magazine](http://msdn.microsoft.com/en-us/magazine/cc302051.aspx) that talks about playing around with this stuff in Visual Studio. Again, this would be total overkill for a test application, it would require far more code than your existing solution. But years ago I wrote a subsystem for a network management application that used the DCOM flavor of this API to gather the event logs off of all the servers on a network so we could alert on particular ones. It was pretty slick and darn near real time. If you implement this in C++ with DCOM, be prepared to deal with Multithreaded Apartments and a lot of hairy logic to detect if/when your connection to the remote server goes up or down. Windows Vista Event Log ----------------------- Windows Vista (and Server 2008) have a whole new API suite relating to event logging and tracing. The [new event log is documented here](http://msdn.microsoft.com/en-us/library/aa385780(VS.85).aspx). It looks like there is an API called EvtSubscribe that allows you to [subscribe to events](http://msdn.microsoft.com/en-us/library/aa385771(VS.85).aspx). I have not used this API so I can't comment on its pros and cons.
182,373
<p>I am currently creating a custom control that needs to handle animation in a C# project. It is basically a listbox that contains a fixed number of elements that are subject to move. An element (another user control with a background image and a couple of generated labels) can move upwards, downwards or be taken out of the list. </p> <p>I would like to create animated movement as the elements get moved around within the container custom control but it seems to me that moving controls around using lines such as</p> <pre><code>myCustomControl.left -= m_iSpeed;</code></pre> <p>triggered within a timer event is flickery and has a terrible rendering, even with double buffering turned on.</p> <p>So here's the question : <strong>What is the best way to achieve a flicker-free animated C# control?</strong> Should I just not create custom controls and handle all of the drawing within a panel's background image that I generate? Is there a super animation method that I have not discovered? :)</p> <p>Thanks!</p>
[ { "answer_id": 182463, "author": "FryHard", "author_id": 231, "author_profile": "https://Stackoverflow.com/users/231", "pm_score": 1, "selected": false, "text": "<p>A similar discussion took place this morning on this question. <a href=\"https://stackoverflow.com/questions/181374/visual-c-form-update-results-in-flickering\">visual c# form update results in flickering.</a> so I will be lazy and give the same answer I gave there:</p>\n\n<p>You could try to call <strong>this.SuspendLayout();</strong> before you start your move and <strong>this.ResumeLayout(false);</strong> when you have finished moving all of the controls. In this way all controls should draw at once and you should have less of a flicker.</p>\n\n<p><em>On a side note I have tried to reproduce this here at work, but seem to be failing. Can you give some more sample code that I can fix maybe?</em></p>\n" }, { "answer_id": 182473, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 0, "selected": false, "text": "<p>The normal way to get flicker-free animation is to implement double-buffering. Take a look at this Code Project article</p>\n\n<p><a href=\"http://www.codeproject.com/KB/GDI-plus/flickerFreeDrawing.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/GDI-plus/flickerFreeDrawing.aspx</a></p>\n\n<p>Minimizing calls to paint until you are ready is also a good idea.</p>\n" }, { "answer_id": 182474, "author": "Mark Heath", "author_id": 7532, "author_profile": "https://Stackoverflow.com/users/7532", "pm_score": 3, "selected": true, "text": "<p>your best bet for flicker-free animation is to do the painting yourself (use the Graphics object in the Paint event handler) and use double-buffering. In your custom control you will need code like this in the constructor:</p>\n\n<pre><code>this.SetStyle(ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | \n ControlStyles.AllPaintingInWmPaint | ControlStyles.SupportsTransparentBackColor,\n true);\n</code></pre>\n" }, { "answer_id": 940153, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/76993/how-to-double-buffer-net-controls-on-a-form/77233#77233\">See How to double buffer .NET controls on a form.</a></p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25152/" ]
I am currently creating a custom control that needs to handle animation in a C# project. It is basically a listbox that contains a fixed number of elements that are subject to move. An element (another user control with a background image and a couple of generated labels) can move upwards, downwards or be taken out of the list. I would like to create animated movement as the elements get moved around within the container custom control but it seems to me that moving controls around using lines such as ``` myCustomControl.left -= m_iSpeed; ``` triggered within a timer event is flickery and has a terrible rendering, even with double buffering turned on. So here's the question : **What is the best way to achieve a flicker-free animated C# control?** Should I just not create custom controls and handle all of the drawing within a panel's background image that I generate? Is there a super animation method that I have not discovered? :) Thanks!
your best bet for flicker-free animation is to do the painting yourself (use the Graphics object in the Paint event handler) and use double-buffering. In your custom control you will need code like this in the constructor: ``` this.SetStyle(ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.SupportsTransparentBackColor, true); ```
182,379
<p>I've got a column in a database table (SQL Server 2005) that contains data like this:</p> <pre><code>TQ7394 SZ910284 T r1534 su8472 </code></pre> <p>I would like to update this column so that the first two characters are uppercase. I would also like to remove any spaces between the first two characters. So <code>T q1234</code> would become <code>TQ1234</code>.</p> <p><strong>The solution should be able to cope with multiple spaces between the first two characters.</strong></p> <p>Is this possible in T-SQL? How about in ANSI-92? I'm always interested in seeing how this is done in other db's too, so feel free to post answers for PostgreSQL, MySQL, et al.</p>
[ { "answer_id": 182438, "author": "Learning", "author_id": 18275, "author_profile": "https://Stackoverflow.com/users/18275", "pm_score": 0, "selected": false, "text": "<pre><code>update Table set Column = case when len(rtrim(substring (Column , 1 , 2))) &lt; 2 \n then UPPER(substring (Column , 1 , 1) + substring (Column , 3 , 1)) + substring(Column , 4, len(Column)\n else UPPER(substring (Column , 1 , 2)) + substring(Column , 3, len(Column) end\n</code></pre>\n\n<p>This works on the fact that if there is a space then the trim of that part of string would yield length less than 2 so we split the string in three and use upper on the 1st and 3rd char. In all other cases we can split the string in 2 parts and use upper to make the first two chars to upper case.</p>\n" }, { "answer_id": 182442, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "<p>If you are doing an UPDATE, I would do it in 2 steps; first get rid of the space (RTRIM on a SUBSTRING), and second do the UPPER on the first 2 chars:</p>\n\n<pre><code>// uses a fixed column length - 20-odd in this case\nUPDATE FOO\nSET bar = RTRIM(SUBSTRING(bar, 1, 2)) + SUBSTRING(bar, 3, 20)\n\nUPDATE FOO\nSET bar = UPPER(SUBSTRING(bar, 1, 2)) + SUBSTRING(bar, 3, 20)\n</code></pre>\n\n<p>If you need it in a SELECT (i.e. inline), then I'd be tempted to write a scalar UDF</p>\n" }, { "answer_id": 182469, "author": "huo73", "author_id": 15657, "author_profile": "https://Stackoverflow.com/users/15657", "pm_score": 2, "selected": false, "text": "<pre><code>UPDATE YourTable \nSET YourColumn = UPPER(\n SUBSTRING(\n REPLACE(YourColumn, ' ', ''), 1, 2\n )\n ) \n + \n SUBSTRING(YourColumn, 3, LEN(YourColumn))\n</code></pre>\n" }, { "answer_id": 182481, "author": "leoinfo", "author_id": 6948, "author_profile": "https://Stackoverflow.com/users/6948", "pm_score": 3, "selected": true, "text": "<p>Here is a solution:</p>\n\n<p><strong>EDIT:</strong> <strong>Updated to support replacement of multiple spaces between the first and the second non-space characters</strong></p>\n\n<pre><code>/* TEST TABLE */\nDECLARE @T AS TABLE(code Varchar(20))\nINSERT INTO @T SELECT 'ab1234x1' UNION SELECT ' ab1234x2' \n UNION SELECT ' ab1234x3' UNION SELECT 'a b1234x4' \n UNION SELECT 'a b1234x5' UNION SELECT 'a b1234x6' \n UNION SELECT 'ab 1234x7' UNION SELECT 'ab 1234x8' \n\nSELECT * FROM @T\n/* INPUT\n code\n --------------------\n ab1234x3\n ab1234x2\n a b1234x6\n a b1234x5\n a b1234x4\n ab 1234x8\n ab 1234x7\n ab1234x1\n*/\n\n/* START PROCESSING SECTION */\nDECLARE @s Varchar(20)\nDECLARE @firstChar INT\nDECLARE @secondChar INT\n\nUPDATE @T SET\n @firstChar = PATINDEX('%[^ ]%',code)\n ,@secondChar = @firstChar + PATINDEX('%[^ ]%', STUFF(code,1, @firstChar,'' ) )\n ,@s = STUFF(\n code,\n 1,\n @secondChar,\n REPLACE(LEFT(code,\n @secondChar\n ),' ','')\n ) \n ,@s = STUFF(\n @s, \n 1,\n 2,\n UPPER(LEFT(@s,2))\n )\n ,code = @s\n/* END PROCESSING SECTION */\n\nSELECT * FROM @T\n/* OUTPUT\n code\n --------------------\n AB1234x3\n AB1234x2\n AB1234x6\n AB1234x5\n AB1234x4\n AB 1234x8\n AB 1234x7\n AB1234x1\n*/\n</code></pre>\n" }, { "answer_id": 182517, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 2, "selected": false, "text": "<p><code>UPPER</code> isn't going to hurt any numbers, so if the examples you gave are completely representative, there's not really any harm in doing:</p>\n\n<pre><code>UPDATE tbl\nSET col = REPLACE(UPPER(col), ' ', '')\n</code></pre>\n" }, { "answer_id": 182608, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 1, "selected": false, "text": "<p>The sample data only has spaces and lowercase letters at the start. If this holds true for the real data then simply:</p>\n\n<pre><code>UPPER(REPLACE(YourColumn, ' ', '')) \n</code></pre>\n\n<p>For a more specific answer I'd politely ask you to expand on your spec, otherwise I'd have to code around all the other possibilities (e.g. values of less than three characters) without knowing if I was overengineering my solution to handle data that wouldn't actually arise in reality :)</p>\n\n<p>As ever, once you've fixed the data, put in a database constraint to ensure the bad data does not reoccur e.g.</p>\n\n<pre><code> ALTER TABLE YourTable ADD\n CONSTRAINT YourColumn__char_pos_1_uppercase_letter\n CHECK (ASCII(SUBSTRING(YourColumn, 1, 1)) BETWEEN ASCII('A') AND ASCII('Z'));\n\n ALTER TABLE YourTable ADD\n CONSTRAINT YourColumn__char_pos_2_uppercase_letter\n CHECK (ASCII(SUBSTRING(YourColumn, 2, 1)) BETWEEN ASCII('A') AND ASCII('Z'));\n</code></pre>\n\n<p>@huo73: yours doesn't work for me on SQL Server 2008: I get 'TRr1534' instead of 'TR1534'.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1944/" ]
I've got a column in a database table (SQL Server 2005) that contains data like this: ``` TQ7394 SZ910284 T r1534 su8472 ``` I would like to update this column so that the first two characters are uppercase. I would also like to remove any spaces between the first two characters. So `T q1234` would become `TQ1234`. **The solution should be able to cope with multiple spaces between the first two characters.** Is this possible in T-SQL? How about in ANSI-92? I'm always interested in seeing how this is done in other db's too, so feel free to post answers for PostgreSQL, MySQL, et al.
Here is a solution: **EDIT:** **Updated to support replacement of multiple spaces between the first and the second non-space characters** ``` /* TEST TABLE */ DECLARE @T AS TABLE(code Varchar(20)) INSERT INTO @T SELECT 'ab1234x1' UNION SELECT ' ab1234x2' UNION SELECT ' ab1234x3' UNION SELECT 'a b1234x4' UNION SELECT 'a b1234x5' UNION SELECT 'a b1234x6' UNION SELECT 'ab 1234x7' UNION SELECT 'ab 1234x8' SELECT * FROM @T /* INPUT code -------------------- ab1234x3 ab1234x2 a b1234x6 a b1234x5 a b1234x4 ab 1234x8 ab 1234x7 ab1234x1 */ /* START PROCESSING SECTION */ DECLARE @s Varchar(20) DECLARE @firstChar INT DECLARE @secondChar INT UPDATE @T SET @firstChar = PATINDEX('%[^ ]%',code) ,@secondChar = @firstChar + PATINDEX('%[^ ]%', STUFF(code,1, @firstChar,'' ) ) ,@s = STUFF( code, 1, @secondChar, REPLACE(LEFT(code, @secondChar ),' ','') ) ,@s = STUFF( @s, 1, 2, UPPER(LEFT(@s,2)) ) ,code = @s /* END PROCESSING SECTION */ SELECT * FROM @T /* OUTPUT code -------------------- AB1234x3 AB1234x2 AB1234x6 AB1234x5 AB1234x4 AB 1234x8 AB 1234x7 AB1234x1 */ ```
182,408
<p>Is there a manual for cross-compiling a C++ application from Linux to Windows?</p> <p>Just that. I would like some information (links, reference, examples...) to guide me to do that.</p> <p>I don't even know if it's possible. </p> <p>My objective is to compile a program in Linux and get a .exe file that I can run under Windows.</p>
[ { "answer_id": 182456, "author": "richq", "author_id": 4596, "author_profile": "https://Stackoverflow.com/users/4596", "pm_score": 7, "selected": true, "text": "<p>The basics are not too difficult:</p>\n\n<pre><code>sudo apt-get install mingw32 \ncat &gt; main.c &lt;&lt;EOF\nint main()\n{\n printf(\"Hello, World!\");\n}\nEOF\ni586-mingw32msvc-cc main.c -o hello.exe\n</code></pre>\n\n<p>Replace <code>apt-get</code> with <code>yum</code>, or whatever your Linux distro uses. That will generate a <code>hello.exe</code> for Windows.</p>\n\n<p>Once you get your head around that, you could use <a href=\"http://sources.redhat.com/autobook/autobook/autobook_268.html#SEC268\" rel=\"noreferrer\">autotools</a>, and set <code>CC=i586-mingw32msvc-cc</code></p>\n\n<pre><code>CC=i586-mingw32msvc-cc ./configure &amp;&amp; make\n</code></pre>\n\n<p>Or use <a href=\"http://www.cmake.org/Wiki/CMake_Cross_Compiling\" rel=\"noreferrer\">CMake and a toolchain file</a> to manage the build. More difficult still is adding native cross libraries. Usually they are stored in <code>/usr/cross/i586-mingw32msvc/{include,lib}</code> and you would need to add those paths in separately in the configure step of the build process.</p>\n" }, { "answer_id": 182470, "author": "Anders Hansson", "author_id": 20364, "author_profile": "https://Stackoverflow.com/users/20364", "pm_score": 3, "selected": false, "text": "<p>It depends on what you mean (I couldn't really say).</p>\n\n<ol>\n<li><p>If you mean that you want to use an existing Linux application on Windows, then you could try compiling it using <a href=\"http://en.wikipedia.org/wiki/Cygwin\" rel=\"nofollow noreferrer\">Cygwin</a> on Windows. This however does not give you a Windows executable free from all dependencies towards Cygwin (your executable still depends on the <code>cygwin.dll</code> file) - and it still may need some porting before it will work. See <a href=\"http://www.cygwin.com\" rel=\"nofollow noreferrer\">http://www.cygwin.com</a>.</p></li>\n<li><p>If you mean that you want to be able to perform the actual compilation of a Windows application on Linux and produce a .exe file that is executable on Windows - thus using your Linux box for development and/or compilation then you should look into <a href=\"http://en.wikipedia.org/wiki/MinGW\" rel=\"nofollow noreferrer\">MinGW</a> for Linux which is a tool for crosscompiling for Windows on Linux. See <a href=\"http://www.mingw.org/wiki/LinuxCrossMinGW\" rel=\"nofollow noreferrer\">http://www.mingw.org/wiki/LinuxCrossMinGW</a>.</p></li>\n</ol>\n\n<p>Best regards!</p>\n" }, { "answer_id": 3570960, "author": "1.01pm", "author_id": 53195, "author_profile": "https://Stackoverflow.com/users/53195", "pm_score": 2, "selected": false, "text": "<p>I suggest you give the following, <a href=\"http://lilypond.org/gub/\" rel=\"nofollow noreferrer\">GUB</a> (Grand Unified Builder) a try as it cross-compiles several packages with their dependencies and assembles them into a single installation package for currently 11 architectures. You can download a prebuilt iso for installation in a VM from <a href=\"http://lilypond.org/doc/v2.13/Documentation/contributor/using-a-virtual-machine-to-compile-lilypond\" rel=\"nofollow noreferrer\">here</a> and follow the source <a href=\"http://github.com/janneke/gub\" rel=\"nofollow noreferrer\">here</a>. It can currently be used to cross-compile GNU LilyPond/ GNU Denemo / Inkscape and OpenOffice.org.</p>\n\n<p>The target architectures are: </p>\n\n<ul>\n<li>darwin-ppc - tar.bz2 file for Darwin 7 (MacOS 10.3)/PowerPC</li>\n<li>darwin-x86 - tar.bz2 file for Darwin 8 (MacOS 10.4)/x86</li>\n<li>mingw - mingw executable for Windows32</li>\n<li>linux-x86 - shar archive for Linux/x86</li>\n<li>linux-64 - shar archive for Linux/x86_64</li>\n<li>linux-ppc - shar archive for Linux/PowerPC</li>\n<li>freebsd-x86 - shar archive for FreeBSD 4/x86</li>\n<li>freebsd-64 - shar archive for FreeBSD 6/x86_64</li>\n<li>cygwin - .tar.bz2 packages for Cygwin/Windows32 </li>\n<li>arm - shar archive for Linux/ARM (largely untested)</li>\n<li>debian - shar archive for Debian (largely untested)</li>\n</ul>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/366094/" ]
Is there a manual for cross-compiling a C++ application from Linux to Windows? Just that. I would like some information (links, reference, examples...) to guide me to do that. I don't even know if it's possible. My objective is to compile a program in Linux and get a .exe file that I can run under Windows.
The basics are not too difficult: ``` sudo apt-get install mingw32 cat > main.c <<EOF int main() { printf("Hello, World!"); } EOF i586-mingw32msvc-cc main.c -o hello.exe ``` Replace `apt-get` with `yum`, or whatever your Linux distro uses. That will generate a `hello.exe` for Windows. Once you get your head around that, you could use [autotools](http://sources.redhat.com/autobook/autobook/autobook_268.html#SEC268), and set `CC=i586-mingw32msvc-cc` ``` CC=i586-mingw32msvc-cc ./configure && make ``` Or use [CMake and a toolchain file](http://www.cmake.org/Wiki/CMake_Cross_Compiling) to manage the build. More difficult still is adding native cross libraries. Usually they are stored in `/usr/cross/i586-mingw32msvc/{include,lib}` and you would need to add those paths in separately in the configure step of the build process.
182,410
<p>I have a JavaScript array that, among others, contains a URL. If I try to simply put the URL in the page (the array is in a project involving the Yahoo! Maps API) it shows the URL as it should be.</p> <p>But if I try to do a redirect or simply do an 'alert' on the link array element I get: </p> <blockquote> <p>function(){return JSON.encode(this);}</p> </blockquote> <p>As far as I see it this is because the browser does an JSON.encode when it renders the page, thus the link is displayed OK. I have tried several methods to make it redirect (that's what I want to do with the link) correctly (including the usage of 'eval') but with no luck.</p> <p>After following some suggestions I've run <code>eval('(' + jsonObject + ')')</code> but it still returns the same output.</p> <p>So how's this done ? </p>
[ { "answer_id": 182445, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 1, "selected": false, "text": "<p>JSON decoding in JavaScript is simply an eval() if you trust the string or the more safe code you can find on <a href=\"http://json.org\" rel=\"nofollow noreferrer\">http://json.org</a> if you don't.</p>\n\n<p>You will then have a JavaScript datastructure that you can traverse for the data you need.</p>\n" }, { "answer_id": 183346, "author": "Joel Anair", "author_id": 7441, "author_profile": "https://Stackoverflow.com/users/7441", "pm_score": 3, "selected": false, "text": "<p>If you get this text in an alert:</p>\n\n<pre><code>function(){return JSON.encode(this);}\n</code></pre>\n\n<p>when you try alert(myArray[i]), then there are a few possibilities:</p>\n\n<ul>\n<li>myArray[i] is a function (most likely)</li>\n<li>myArray[i] is the literal string \"function(){return JSON.encode(this);}\"</li>\n<li>myArray[i] has a .toString() method that returns that function or that string. This is the least likely of the three.</li>\n</ul>\n\n<p>The simplest way to tell would be to check typeof(myArray[i]).</p>\n" }, { "answer_id": 183362, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 2, "selected": false, "text": "<pre><code>eval('(' + jsonObject + ')')\n</code></pre>\n" }, { "answer_id": 189613, "author": "Leonel Martins", "author_id": 26673, "author_profile": "https://Stackoverflow.com/users/26673", "pm_score": 1, "selected": false, "text": "<p>If the object element you get is a function, you can try this:</p>\n\n<pre><code>var url = myArray[i]();\n</code></pre>\n" }, { "answer_id": 5308754, "author": "Floccinaucinihilipilification.", "author_id": 609705, "author_profile": "https://Stackoverflow.com/users/609705", "pm_score": 3, "selected": false, "text": "<p>Suppose you have an array in PHP as $iniData with 5 fields. If using ajax -</p>\n\n<pre><code>echo json_encode($iniData);\n</code></pre>\n\n<p>In Javascript, use the following :</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n $(document).ready(function(){\n $.ajax({\n type: \"GET\",\n url: \"ajaxCalls.php\",\n data: \"dataType=ini\",\n success: function(msg)\n {\n var x = eval('(' + msg + ')');\n $('#allowed').html(x.allowed); // these are the fields which you can now easily access..\n $('#completed').html(x.completed);\n $('#running').html(x.running);\n $('#expired').html(x.expired);\n $('#balance').html(x.balance);\n }\n });\n });\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 6541474, "author": "matija kancijan", "author_id": 655430, "author_profile": "https://Stackoverflow.com/users/655430", "pm_score": 5, "selected": false, "text": "<pre><code>var obj = jQuery.parseJSON('{\"name\":\"John\"}');\nalert( obj.name === \"John\" );\n</code></pre>\n\n<p><a href=\"http://api.jquery.com/jQuery.parseJSON/\" rel=\"noreferrer\">See the jQuery API</a>.</p>\n" }, { "answer_id": 15613878, "author": "pirogtm", "author_id": 2098782, "author_profile": "https://Stackoverflow.com/users/2098782", "pm_score": -1, "selected": false, "text": "<p>I decode JSON this way:</p>\n\n<pre><code>eval( 'var from_json_object = ' + my_json_str + ';' );\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20603/" ]
I have a JavaScript array that, among others, contains a URL. If I try to simply put the URL in the page (the array is in a project involving the Yahoo! Maps API) it shows the URL as it should be. But if I try to do a redirect or simply do an 'alert' on the link array element I get: > > function(){return JSON.encode(this);} > > > As far as I see it this is because the browser does an JSON.encode when it renders the page, thus the link is displayed OK. I have tried several methods to make it redirect (that's what I want to do with the link) correctly (including the usage of 'eval') but with no luck. After following some suggestions I've run `eval('(' + jsonObject + ')')` but it still returns the same output. So how's this done ?
``` var obj = jQuery.parseJSON('{"name":"John"}'); alert( obj.name === "John" ); ``` [See the jQuery API](http://api.jquery.com/jQuery.parseJSON/).
182,436
<p>Are there any tools available for validating a database schema against a set of design rules, naming conventions, etc.</p> <p>I'm not talking about comparing one database to another (as covered by <a href="https://stackoverflow.com/questions/165401/how-to-comparevalidate-sql-schema">this question</a>).</p> <p>I want to be able to say "What in this database doesn't meet this set of rules". </p> <p>Some examples of the type of rules I'm talking about would be like:<br> - Primary key fields should be the first in the table.<br> - Foreign keys should have an index on that field.<br> - Field names ending 'xxx' should be of a certain type.<br> - Fields with a constraint limiting it it certain values it should have a default.</p> <p>I've written a bunch of scripts to do this in the past and was wondering if there was something generic available.</p> <p>Ideally I'd like something for SQL Server, but if you're aware of something for other databases it may be useful to know about them too.</p>
[ { "answer_id": 182445, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 1, "selected": false, "text": "<p>JSON decoding in JavaScript is simply an eval() if you trust the string or the more safe code you can find on <a href=\"http://json.org\" rel=\"nofollow noreferrer\">http://json.org</a> if you don't.</p>\n\n<p>You will then have a JavaScript datastructure that you can traverse for the data you need.</p>\n" }, { "answer_id": 183346, "author": "Joel Anair", "author_id": 7441, "author_profile": "https://Stackoverflow.com/users/7441", "pm_score": 3, "selected": false, "text": "<p>If you get this text in an alert:</p>\n\n<pre><code>function(){return JSON.encode(this);}\n</code></pre>\n\n<p>when you try alert(myArray[i]), then there are a few possibilities:</p>\n\n<ul>\n<li>myArray[i] is a function (most likely)</li>\n<li>myArray[i] is the literal string \"function(){return JSON.encode(this);}\"</li>\n<li>myArray[i] has a .toString() method that returns that function or that string. This is the least likely of the three.</li>\n</ul>\n\n<p>The simplest way to tell would be to check typeof(myArray[i]).</p>\n" }, { "answer_id": 183362, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 2, "selected": false, "text": "<pre><code>eval('(' + jsonObject + ')')\n</code></pre>\n" }, { "answer_id": 189613, "author": "Leonel Martins", "author_id": 26673, "author_profile": "https://Stackoverflow.com/users/26673", "pm_score": 1, "selected": false, "text": "<p>If the object element you get is a function, you can try this:</p>\n\n<pre><code>var url = myArray[i]();\n</code></pre>\n" }, { "answer_id": 5308754, "author": "Floccinaucinihilipilification.", "author_id": 609705, "author_profile": "https://Stackoverflow.com/users/609705", "pm_score": 3, "selected": false, "text": "<p>Suppose you have an array in PHP as $iniData with 5 fields. If using ajax -</p>\n\n<pre><code>echo json_encode($iniData);\n</code></pre>\n\n<p>In Javascript, use the following :</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n $(document).ready(function(){\n $.ajax({\n type: \"GET\",\n url: \"ajaxCalls.php\",\n data: \"dataType=ini\",\n success: function(msg)\n {\n var x = eval('(' + msg + ')');\n $('#allowed').html(x.allowed); // these are the fields which you can now easily access..\n $('#completed').html(x.completed);\n $('#running').html(x.running);\n $('#expired').html(x.expired);\n $('#balance').html(x.balance);\n }\n });\n });\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 6541474, "author": "matija kancijan", "author_id": 655430, "author_profile": "https://Stackoverflow.com/users/655430", "pm_score": 5, "selected": false, "text": "<pre><code>var obj = jQuery.parseJSON('{\"name\":\"John\"}');\nalert( obj.name === \"John\" );\n</code></pre>\n\n<p><a href=\"http://api.jquery.com/jQuery.parseJSON/\" rel=\"noreferrer\">See the jQuery API</a>.</p>\n" }, { "answer_id": 15613878, "author": "pirogtm", "author_id": 2098782, "author_profile": "https://Stackoverflow.com/users/2098782", "pm_score": -1, "selected": false, "text": "<p>I decode JSON this way:</p>\n\n<pre><code>eval( 'var from_json_object = ' + my_json_str + ';' );\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1755/" ]
Are there any tools available for validating a database schema against a set of design rules, naming conventions, etc. I'm not talking about comparing one database to another (as covered by [this question](https://stackoverflow.com/questions/165401/how-to-comparevalidate-sql-schema)). I want to be able to say "What in this database doesn't meet this set of rules". Some examples of the type of rules I'm talking about would be like: - Primary key fields should be the first in the table. - Foreign keys should have an index on that field. - Field names ending 'xxx' should be of a certain type. - Fields with a constraint limiting it it certain values it should have a default. I've written a bunch of scripts to do this in the past and was wondering if there was something generic available. Ideally I'd like something for SQL Server, but if you're aware of something for other databases it may be useful to know about them too.
``` var obj = jQuery.parseJSON('{"name":"John"}'); alert( obj.name === "John" ); ``` [See the jQuery API](http://api.jquery.com/jQuery.parseJSON/).
182,440
<p>This question is a follow-up from <a href="https://stackoverflow.com/questions/161822/how-to-indicate-that-a-method-was-unsuccessful">How to indicate that a method was unsuccessful</a>. The xxx() Tryxxx() pattern is something that can be very useful in many libraries. I am wondering what is the best way to offer both implementations without duplicating my code.</p> <p>What is best:</p> <pre><code>public int DoSomething(string a) { // might throw an exception } public bool TrySomething(string a, out result) { try { result = DoSomething(a) return true; } catch (Exception) { return false; } </code></pre> <p>or</p> <pre><code>public int DoSomething(string a) { int result; if (TrySomething(a, out result)) { return result; } else { throw Exception(); // which exception? } } public bool TrySomething(string a, out result) { //... } </code></pre> <p>I'd instinctively assume that the first example is more correct (you know exactly which exception happened), but couldn't the try/catch be too expensive? Is there a way to catch the exception in the second example?</p>
[ { "answer_id": 182483, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 2, "selected": false, "text": "<p>The first example is correct if you are just going to catch the exception and not do anything but return false with it. </p>\n\n<p>You could change TrySomething to look like below.</p>\n\n<pre><code>public bool TrySomething(string a, out result, bool throwException)\n{\n try\n {\n // Whatever\n }\n catch\n {\n if(throwException)\n {\n throw;\n }\n else\n {\n return false;\n }\n }\n\n}\n\npublic bool TrySomething(string a, out result)\n{\n return TrySomething(a, out result, false);\n}\n</code></pre>\n\n<p>So DoSomething would look like</p>\n\n<pre><code>public int DoSomething(string a)\n{\n int result;\n\n // This will throw the execption or \n // change to false to not, or don't use the overloaded one.\n TrySomething(a, out result, true) \n\n return result; \n}\n</code></pre>\n\n<p>If you did not want TrySomething with throwException exposed to the public you can make it a private member.</p>\n\n<p>Exceptions could get expensive and you could do some RegEx checking on the string to prevent one from being thrown. It depends on what you are trying to do.</p>\n" }, { "answer_id": 182494, "author": "Ben Crouse", "author_id": 6705, "author_profile": "https://Stackoverflow.com/users/6705", "pm_score": 2, "selected": false, "text": "<p>Assuming this is C#, I would say the second example </p>\n\n<pre><code>public bool TrySomething(string a, out result)\n{\n try\n {\n result = DoSomething(a)\n return true;\n }\n catch (Exception)\n {\n return false;\n }\n}\n</code></pre>\n\n<p>It mimics the built in <code>int.TryParse(string s, out int result)</code>, and in my opinion its best to stay consistent with the language/environment.</p>\n" }, { "answer_id": 182507, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I usually use this pattern. Depends on how the Internal method is implemented as to whether or not this makes any sense. If you have to use conditional catch blocks it can get a bit nasty...</p>\n\n<pre><code>public object DoSomething(object input){\n return DoSomethingInternal(input, true);\n}\n\npublic bool TryDoSomething(object input, out object result){\n result = DoSomethingInternal(input, false);\n return result != null;\n}\n\nprivate object DoSomethingInternal(object input, bool throwOnError){\n /* do your work here; only throw if you cannot proceed and throwOnError is true */\n}\n</code></pre>\n" }, { "answer_id": 182515, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "<p>Making TrySomething just catch and swallow the exception is a really bad idea. Half the point of the TryXXX pattern is to avoid the performance hit of exceptions.</p>\n\n<p>If you don't need much information in the exception, you could make the DoSomething method just call TrySomething and throw an exception if it fails. If you need details in the exception, you may need something more elaborate. I haven't timed where the bulk of the performance hit of exceptions is - if it's the throwing rather than the creating, you could write a private method which had a similar signature to TrySomething, but which returned an exception or null:</p>\n\n<pre><code>public int DoSomething(string input)\n{\n int ret;\n Exception exception = DoSomethingImpl(input, out ret);\n if (exception != null)\n {\n // Note that you'll lose stack trace accuracy here\n throw exception;\n }\n return ret;\n}\n\npublic bool TrySomething(string input, out int ret)\n{\n Exception exception = DoSomethingImpl(input, out ret);\n return exception == null;\n}\n\nprivate Exception DoSomethingImpl(string input, out int ret)\n{\n ret = 0;\n if (input != \"bad\")\n {\n ret = 5;\n return null;\n }\n else\n {\n return new ArgumentException(\"Some details\");\n }\n}\n</code></pre>\n\n<p>Time this before you commit to it though!</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5789/" ]
This question is a follow-up from [How to indicate that a method was unsuccessful](https://stackoverflow.com/questions/161822/how-to-indicate-that-a-method-was-unsuccessful). The xxx() Tryxxx() pattern is something that can be very useful in many libraries. I am wondering what is the best way to offer both implementations without duplicating my code. What is best: ``` public int DoSomething(string a) { // might throw an exception } public bool TrySomething(string a, out result) { try { result = DoSomething(a) return true; } catch (Exception) { return false; } ``` or ``` public int DoSomething(string a) { int result; if (TrySomething(a, out result)) { return result; } else { throw Exception(); // which exception? } } public bool TrySomething(string a, out result) { //... } ``` I'd instinctively assume that the first example is more correct (you know exactly which exception happened), but couldn't the try/catch be too expensive? Is there a way to catch the exception in the second example?
Making TrySomething just catch and swallow the exception is a really bad idea. Half the point of the TryXXX pattern is to avoid the performance hit of exceptions. If you don't need much information in the exception, you could make the DoSomething method just call TrySomething and throw an exception if it fails. If you need details in the exception, you may need something more elaborate. I haven't timed where the bulk of the performance hit of exceptions is - if it's the throwing rather than the creating, you could write a private method which had a similar signature to TrySomething, but which returned an exception or null: ``` public int DoSomething(string input) { int ret; Exception exception = DoSomethingImpl(input, out ret); if (exception != null) { // Note that you'll lose stack trace accuracy here throw exception; } return ret; } public bool TrySomething(string input, out int ret) { Exception exception = DoSomethingImpl(input, out ret); return exception == null; } private Exception DoSomethingImpl(string input, out int ret) { ret = 0; if (input != "bad") { ret = 5; return null; } else { return new ArgumentException("Some details"); } } ``` Time this before you commit to it though!
182,455
<p>How do I remove a trailing comma from a string in ColdFusion?</p>
[ { "answer_id": 182464, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 3, "selected": false, "text": "<p>Check the rightmost char - if it's a comma, set the string to a substring of the original, with length -1.</p>\n\n<p>Trimming the string ensures that spaces after the trailing comma don't interfere with this method.</p>\n\n<pre><code>&lt;cfset myStr = \"hello, goodbye,\"&gt;\n&lt;cfset myStr = trim(myStr)&gt;\n\n&lt;cfif right(myStr, 1) is \",\"&gt;\n &lt;cfset myStr = left(myStr, len(myStr)-1)&gt;\n&lt;/cfif&gt;\n</code></pre>\n" }, { "answer_id": 182466, "author": "Patrick McElhaney", "author_id": 437, "author_profile": "https://Stackoverflow.com/users/437", "pm_score": 6, "selected": true, "text": "<p>To remove a trailing comma (if it exists):</p>\n\n<pre><code>REReplace(list, \",$\", \"\")\n</code></pre>\n\n<p>To strip one or more trailing commas:</p>\n\n<pre><code>REReplace(list, \",+$\", \"\")\n</code></pre>\n" }, { "answer_id": 182511, "author": "Jason", "author_id": 3242, "author_profile": "https://Stackoverflow.com/users/3242", "pm_score": 2, "selected": false, "text": "<p>To add onto Patrick's answer. To replace one or more commas at the end use the following:\nreReplace(myString, \",+$\", \"\", \"all\")</p>\n\n<p>Example Below</p>\n\n<pre><code>&lt;cfset myString = \"This is the string, with training commas,,,\"&gt;\n&lt;cfset onlyTheLastTrailingComma = reReplace(myString, \",$\", \"\", \"all\")&gt;\n&lt;cfset allTrailingCommas = reReplace(myString, \",+$\", \"\", \"all\")&gt;\n&lt;cfoutput&gt;#onlyTheLastTrailingComma#&lt;br /&gt;#allTrailingCommas#&lt;/cfoutput&gt;\n</code></pre>\n" }, { "answer_id": 197995, "author": "Phydiux", "author_id": 27465, "author_profile": "https://Stackoverflow.com/users/27465", "pm_score": 2, "selected": false, "text": "<p>This is probably more of a performance hit than Regex'ing a list, but sometimes when I end up filtering/fixing dirty data, I convert it to an array and then convert it back into a list.</p>\n\n<pre><code>\n&lt;cfset someVariable = arrayToList(listToArray(someVariable, \",\"), \",\")&gt;\n</code></pre>\n\n<p>It's cheating, but it works ;-)</p>\n" }, { "answer_id": 217758, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": false, "text": "<p>Also easy: </p>\n\n<pre><code>&lt;cfset CleanList = ListChangeDelims(DirtyList, \",\", \",\")&gt;\n</code></pre>\n\n<p>Explanation: This takes advantage of the fact that CF list functions ignore empty elements. <code>ListChangeDelims()</code> consequently strips off that last \"element\".</p>\n" }, { "answer_id": 2291045, "author": "richard", "author_id": 276352, "author_profile": "https://Stackoverflow.com/users/276352", "pm_score": 1, "selected": false, "text": "<p>Remove \",\" from Both Sides, Just the Right Side, or Just the Left Side</p>\n\n<pre><code>&lt;cfset theFunnyList = \",!@2ed32,a,b,c,d,%442,d,a\"&gt;\n</code></pre>\n\n<p>Replace Funny Characters and Separate with Comma</p>\n\n<pre><code>&lt;cfset theList = rereplace(theFunnyList, \"[^A-Za-z0-9]+\", \",\", \"all\")&gt;\n&lt;cfset theList = trim(theList)&gt;\n&lt;cfif left(theList, 1) is \",\" and right(theList, 1) is \",\"&gt;\n &lt;cfset theList = right(theList, len(theList)-1)&gt;\n &lt;cfset theList = left(theList, len(theList)-1)&gt;\n&lt;cfelseif right(theList, 1) is \",\"&gt;\n &lt;cfset theList = left(theList, len(theList)-1)&gt;\n&lt;cfelseif left(theList, 1) is \",\"&gt;\n &lt;cfset theList = right(theList, len(theList)-1)&gt;\n&lt;/cfif&gt;\n</code></pre>\n\n<p>Sort List (Numeric to A-Z) ASCending</p>\n\n<pre><code>&lt;cfoutput&gt; #ListSort(\"#theList#\", \"text\", \"ASC\", \",;\")# &lt;/cfoutput&gt;\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26121/" ]
How do I remove a trailing comma from a string in ColdFusion?
To remove a trailing comma (if it exists): ``` REReplace(list, ",$", "") ``` To strip one or more trailing commas: ``` REReplace(list, ",+$", "") ```
182,475
<p>AFAIK, Currency type in Delphi Win32 depends on the processor floating point precision. Because of this I'm having rounding problems when comparing two Currency values, returning different results depending on the machine.</p> <p>For now I'm using the SameValue function passing a Epsilon parameter = 0.009, because I only need 2 decimal digits precision.</p> <p>Is there any better way to avoid this problem?</p>
[ { "answer_id": 182509, "author": "Matt Lacey", "author_id": 1755, "author_profile": "https://Stackoverflow.com/users/1755", "pm_score": -1, "selected": false, "text": "<p>To avoid possible issues with currency rounding in Delphi use 4 decimal places.</p>\n\n<p>This will ensure that you never having rounding issues when doing calcualtions with very small amounts.</p>\n\n<p><code>\"Been there. Done That. Written the unit tests.\"</code></p>\n" }, { "answer_id": 182777, "author": "Craig Stuntz", "author_id": 7714, "author_profile": "https://Stackoverflow.com/users/7714", "pm_score": 4, "selected": false, "text": "<p>No, Currency is not a floating point type. It is a fixed-precision decimal, implemented with integer storage. It can be compared exactly, and does not have the rounding issues of, say, Double. Therefore, if you are seeing inexact values in your Currency variables, the problem is not the Currency type itself, but what you are putting into it. Most likely, you have a floating-point calculation somewhere else in your code. Since you do not show that code, it's hard to be of more help on this question. But the solution, generally speaking, will be to round your floating point numbers to the correct precision before storing in the Currency variable, rather than doing an inexact comparison on the Currency variables.</p>\n" }, { "answer_id": 182822, "author": "Barry Kelly", "author_id": 3712, "author_profile": "https://Stackoverflow.com/users/3712", "pm_score": 5, "selected": true, "text": "<p>The Currency type in Delphi is a 64-bit integer scaled by 1/10,000; in other words, its smallest increment is equivalent to 0.0001. It is not susceptible to precision issues in the same way that floating point code is.</p>\n\n<p>However, if you are multiplying your Currency numbers by floating-point types, or dividing your Currency values, the rounding does need to be worked out one way or the other. The FPU controls this mechanism (it's called the \"control word\"). The Math unit contains some procedures which control this mechanism: SetRoundMode in particular. You can see the effects in this program:</p>\n\n<pre><code>{$APPTYPE CONSOLE}\n\nuses Math;\n\nvar\n x: Currency;\n y: Currency;\nbegin\n SetRoundMode(rmTruncate);\n x := 1;\n x := x / 6;\n SetRoundMode(rmNearest);\n y := 1;\n y := y / 6;\n Writeln(x = y); // false\n Writeln(x - y); // 0.0001; i.e. 0.1666 vs 0.1667\nend.\n</code></pre>\n\n<p>It is possible that a third-party library you are using is setting the control word to a different value. You may want to set the control word (i.e. rounding mode) explicitly at the starting point of your important calculations.</p>\n\n<p>Also, if your calculations ever transfer into plain floating point and then back into Currency, all bets are off - too hard to audit. Make sure all your calculations are in Currency.</p>\n" }, { "answer_id": 183280, "author": "jrodenhi", "author_id": 25315, "author_profile": "https://Stackoverflow.com/users/25315", "pm_score": 0, "selected": false, "text": "<p>If your situation is like mine, you might find this approach helpful. I work mostly in payroll. If a business has say 3 departments and wants to charge the cost of an employee evenly among those three departments, there are a lot of times when there will be rounding issues. </p>\n\n<p>What I have been doing is loop through the departments charging each one a third of the total cost and adding the cost charged to a subtotal (currency) variable. But when the loop variable equals the limit, rather than multiplying by the fraction, I subtract the subtotal variable from the total cost and put that in the last department. Since the journal entries that result from this process always have to balance, I believe that it has always worked.</p>\n" }, { "answer_id": 830280, "author": "mjn", "author_id": 80901, "author_profile": "https://Stackoverflow.com/users/80901", "pm_score": 0, "selected": false, "text": "<p>See thread:</p>\n\n<p>D7 / DUnit: all CheckEquals(Currency, Currency) tests suddenly fail ... </p>\n\n<p><a href=\"https://forums.codegear.com/thread.jspa?threadID=16288\" rel=\"nofollow noreferrer\">https://forums.codegear.com/thread.jspa?threadID=16288</a></p>\n\n<p>It looks like a change on our development workstations caused Currency comparision to fail. We have not found the root cause, but on two computers running Windows 2000 SP4, and independent of the version of gds32.dll (InterBase 7.5.1 or 2007) and Delphi (7 and 2009), this line</p>\n\n<pre><code>TIBDataBase.Create(nil);\n</code></pre>\n\n<p>changes the value of to 8087 control word from $1372 to $1272 now.</p>\n\n<p>And all Currency comparisions in unit tests will fail with funny messages like</p>\n\n<pre><code>Expected: &lt;12.34&gt; - Found: &lt;12.34&gt;\n</code></pre>\n\n<p>The gds32.dll has not been modified, so I guess that there is a dependency in this library to a third party dll which modifies the control word.</p>\n" }, { "answer_id": 8061486, "author": "Arnaud Bouchez", "author_id": 458259, "author_profile": "https://Stackoverflow.com/users/458259", "pm_score": 2, "selected": false, "text": "<p>Faster and safer way of comparing two <code>currency</code> values is certainly to map the variables to their internal <code>Int64</code> representation:</p>\n\n<pre><code>function CompCurrency(var A,B: currency): Int64;\nvar A64: Int64 absolute A;\n B64: Int64 absolute B;\nbegin\n result := A64-B64;\nend;\n</code></pre>\n\n<p>This will avoid any rounding error during comparison (working with *10000 integer values), and will be faster than the default FPU-based implementation (especially under 64 bit XE2 compiler).</p>\n\n<p>See <a href=\"http://blog.synopse.info/post/2011/11/08/Currency-is-your-friend\" rel=\"nofollow\">this article</a> for additional information.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2089/" ]
AFAIK, Currency type in Delphi Win32 depends on the processor floating point precision. Because of this I'm having rounding problems when comparing two Currency values, returning different results depending on the machine. For now I'm using the SameValue function passing a Epsilon parameter = 0.009, because I only need 2 decimal digits precision. Is there any better way to avoid this problem?
The Currency type in Delphi is a 64-bit integer scaled by 1/10,000; in other words, its smallest increment is equivalent to 0.0001. It is not susceptible to precision issues in the same way that floating point code is. However, if you are multiplying your Currency numbers by floating-point types, or dividing your Currency values, the rounding does need to be worked out one way or the other. The FPU controls this mechanism (it's called the "control word"). The Math unit contains some procedures which control this mechanism: SetRoundMode in particular. You can see the effects in this program: ``` {$APPTYPE CONSOLE} uses Math; var x: Currency; y: Currency; begin SetRoundMode(rmTruncate); x := 1; x := x / 6; SetRoundMode(rmNearest); y := 1; y := y / 6; Writeln(x = y); // false Writeln(x - y); // 0.0001; i.e. 0.1666 vs 0.1667 end. ``` It is possible that a third-party library you are using is setting the control word to a different value. You may want to set the control word (i.e. rounding mode) explicitly at the starting point of your important calculations. Also, if your calculations ever transfer into plain floating point and then back into Currency, all bets are off - too hard to audit. Make sure all your calculations are in Currency.
182,492
<p>I would like TortoiseSVN (1.5.3) to ignore certain folders, their contents and certain other files wherever they might appear in my directory hierarchy but I cannot get the global ignore string right.</p> <p>Whatever I do, it either adds to much or ignores too much</p> <p>What is the correct 'Global ignore pattern' to ignore....</p> <pre><code>Folders : bin obj release compile Files : *.bak *.user *.suo </code></pre> <p>Update: To help clarify... yes I am using this on windows. </p>
[ { "answer_id": 182508, "author": "PersistenceOfVision", "author_id": 6721, "author_profile": "https://Stackoverflow.com/users/6721", "pm_score": 7, "selected": true, "text": "<p>Currently I have the following in my Global Ignore Pattern:<br></p>\n\n<pre><code>bin obj CVS .cvsignore *.user *.suo Debug Release *.pdb test.* Thumbs.db\n</code></pre>\n\n<p>Works really well to ignore several hidden or temp files/folders....</p>\n\n<p>So for your specific requirements:</p>\n\n<ul>\n<li>Folders: <code>bin obj release compile</code></li>\n<li>Files: <code>*.bak *.user *.suo</code></li>\n</ul>\n\n<p>I would use:</p>\n\n<pre><code>bin obj release compile *.bak *.user *.suo\n</code></pre>\n" }, { "answer_id": 182513, "author": "RS Conley", "author_id": 7890, "author_profile": "https://Stackoverflow.com/users/7890", "pm_score": 2, "selected": false, "text": "<p>This is one I use for .NET. Note that I use VB6 as well as other packages so there are extra entries. Also it is case sensitive. </p>\n\n<p>*.chm *.dat *.dll *.ini *.err *.exe *.DLL *.INI *.ERR *.EXE *.backup *.zip *.ZIP *.vbw *.scc *.vbg *.log *.exp *.lib <em>.vrs</em>.SCC *.PRF *.prf *.NIP *.NOP *.nip *.nop *.out *.bjob *.job *.prt *.tmp *.txt *.EX_ *.ex_ *.MDP *.bak *.BAK *.CFG *.cfg *.TXT *.vrs *.VRS *.scc *.SCC *.vsc *.VSC *.mdb *.MDB *.cur *.oca *.setup *.png *.suo *.user Debug Release bin *.pdb *.trx TestResults *.WS~ *.ocx</p>\n\n<p>These three proved critical in greatly reducing the number of files wildcards I had to track down.</p>\n\n<p>Debug Release bin</p>\n" }, { "answer_id": 182548, "author": "Ian Hopkinson", "author_id": 19172, "author_profile": "https://Stackoverflow.com/users/19172", "pm_score": 2, "selected": false, "text": "<p>If you're using Windows don't you need to use an ignore pattern like this:</p>\n\n<p>*/bin */obj</p>\n\n<p>for directories? And maybe even:</p>\n\n<pre>\n*/bin/* */obj/*\n</pre>\n\n<p>I must admit I only realised this after I had committed the wrong things, so I haven't tried this out 'live'. Notice the use of the forward slashes in the directory pattern.</p>\n\n<p>(See this link for the source:\n<a href=\"http://svn.haxx.se/tsvnusers/archive-2007-03/0281.shtml\" rel=\"nofollow noreferrer\">http://svn.haxx.se/tsvnusers/archive-2007-03/0281.shtml</a>\n)</p>\n" }, { "answer_id": 12636786, "author": "Shiraz", "author_id": 422663, "author_profile": "https://Stackoverflow.com/users/422663", "pm_score": 2, "selected": false, "text": "<p>Please be aware that using the subversion 1.7+ does not expect paths in the Global Ignore List (the global-ignores line in the %appdata%\\subversion\\config file). See <a href=\"http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-ignore.html\" rel=\"nofollow\">http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-ignore.html</a></p>\n\n<p>So, to ignore bin and obj directories in <em>all</em> projects:\nglobal-ignores = bin obj</p>\n" }, { "answer_id": 32848430, "author": "Andreas Reiff", "author_id": 586754, "author_profile": "https://Stackoverflow.com/users/586754", "pm_score": 3, "selected": false, "text": "<p>(Adding to an old question..)<br>\nIt depends mainly on your language. So there are some versions here already for VB6 and others.</p>\n\n<p>This is for <strong>Visual Studio &amp; C#</strong>:</p>\n\n<pre><code>global-ignores = *.suo *.user *.userosscache *.sln.docstates *.userprefs debug release Debug Release bin x64 x86 obj Obj *_i.c *_p.c *_i.h *.ilk *.meta *.obj *.pch *.pdb *.pgc *.pgd *.rsp *.sbr *.tlb *.tli *.tlh *.tmp *.tmp_proj *.log *.psess *.vsp *.vspx *.sap Thumbs.db _UpgradeReport_Files *.dbmdl\n</code></pre>\n\n<p>and goes into your</p>\n\n<pre><code>%APPDATA%/Subversion/config\n</code></pre>\n\n<p>file. If you have a fresh <em>config</em> file, like me, you will only find <em>global-ignore</em> entries that are commented out, so you can append the line.</p>\n\n<p>It is take mainly from the gitignore at <a href=\"https://github.com/github/gitignore/blob/master/VisualStudio.gitignore\" rel=\"noreferrer\">https://github.com/github/gitignore/blob/master/VisualStudio.gitignore</a> .</p>\n\n<p><strong>General case for any language</strong><br>\nBasically, googling (or binging, if you so desire) for \"gitignore (language or tool)\" you will find sample gitignore files, the syntax is similar to the <em>global-ignore</em> of SVN, you just need to do some editing (all entries in one line for SVN, each entry in new line for GIT).</p>\n\n<p>A good text editor like <a href=\"http://www.sublimetext.com/\" rel=\"noreferrer\">Sublime</a> or <a href=\"https://notepad-plus-plus.org/\" rel=\"noreferrer\">Notepad++</a> helps a lot when converting.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11356/" ]
I would like TortoiseSVN (1.5.3) to ignore certain folders, their contents and certain other files wherever they might appear in my directory hierarchy but I cannot get the global ignore string right. Whatever I do, it either adds to much or ignores too much What is the correct 'Global ignore pattern' to ignore.... ``` Folders : bin obj release compile Files : *.bak *.user *.suo ``` Update: To help clarify... yes I am using this on windows.
Currently I have the following in my Global Ignore Pattern: ``` bin obj CVS .cvsignore *.user *.suo Debug Release *.pdb test.* Thumbs.db ``` Works really well to ignore several hidden or temp files/folders.... So for your specific requirements: * Folders: `bin obj release compile` * Files: `*.bak *.user *.suo` I would use: ``` bin obj release compile *.bak *.user *.suo ```
182,497
<p>Please give me the direction of the best guidance on the Entity Framework.</p>
[ { "answer_id": 182508, "author": "PersistenceOfVision", "author_id": 6721, "author_profile": "https://Stackoverflow.com/users/6721", "pm_score": 7, "selected": true, "text": "<p>Currently I have the following in my Global Ignore Pattern:<br></p>\n\n<pre><code>bin obj CVS .cvsignore *.user *.suo Debug Release *.pdb test.* Thumbs.db\n</code></pre>\n\n<p>Works really well to ignore several hidden or temp files/folders....</p>\n\n<p>So for your specific requirements:</p>\n\n<ul>\n<li>Folders: <code>bin obj release compile</code></li>\n<li>Files: <code>*.bak *.user *.suo</code></li>\n</ul>\n\n<p>I would use:</p>\n\n<pre><code>bin obj release compile *.bak *.user *.suo\n</code></pre>\n" }, { "answer_id": 182513, "author": "RS Conley", "author_id": 7890, "author_profile": "https://Stackoverflow.com/users/7890", "pm_score": 2, "selected": false, "text": "<p>This is one I use for .NET. Note that I use VB6 as well as other packages so there are extra entries. Also it is case sensitive. </p>\n\n<p>*.chm *.dat *.dll *.ini *.err *.exe *.DLL *.INI *.ERR *.EXE *.backup *.zip *.ZIP *.vbw *.scc *.vbg *.log *.exp *.lib <em>.vrs</em>.SCC *.PRF *.prf *.NIP *.NOP *.nip *.nop *.out *.bjob *.job *.prt *.tmp *.txt *.EX_ *.ex_ *.MDP *.bak *.BAK *.CFG *.cfg *.TXT *.vrs *.VRS *.scc *.SCC *.vsc *.VSC *.mdb *.MDB *.cur *.oca *.setup *.png *.suo *.user Debug Release bin *.pdb *.trx TestResults *.WS~ *.ocx</p>\n\n<p>These three proved critical in greatly reducing the number of files wildcards I had to track down.</p>\n\n<p>Debug Release bin</p>\n" }, { "answer_id": 182548, "author": "Ian Hopkinson", "author_id": 19172, "author_profile": "https://Stackoverflow.com/users/19172", "pm_score": 2, "selected": false, "text": "<p>If you're using Windows don't you need to use an ignore pattern like this:</p>\n\n<p>*/bin */obj</p>\n\n<p>for directories? And maybe even:</p>\n\n<pre>\n*/bin/* */obj/*\n</pre>\n\n<p>I must admit I only realised this after I had committed the wrong things, so I haven't tried this out 'live'. Notice the use of the forward slashes in the directory pattern.</p>\n\n<p>(See this link for the source:\n<a href=\"http://svn.haxx.se/tsvnusers/archive-2007-03/0281.shtml\" rel=\"nofollow noreferrer\">http://svn.haxx.se/tsvnusers/archive-2007-03/0281.shtml</a>\n)</p>\n" }, { "answer_id": 12636786, "author": "Shiraz", "author_id": 422663, "author_profile": "https://Stackoverflow.com/users/422663", "pm_score": 2, "selected": false, "text": "<p>Please be aware that using the subversion 1.7+ does not expect paths in the Global Ignore List (the global-ignores line in the %appdata%\\subversion\\config file). See <a href=\"http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-ignore.html\" rel=\"nofollow\">http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-ignore.html</a></p>\n\n<p>So, to ignore bin and obj directories in <em>all</em> projects:\nglobal-ignores = bin obj</p>\n" }, { "answer_id": 32848430, "author": "Andreas Reiff", "author_id": 586754, "author_profile": "https://Stackoverflow.com/users/586754", "pm_score": 3, "selected": false, "text": "<p>(Adding to an old question..)<br>\nIt depends mainly on your language. So there are some versions here already for VB6 and others.</p>\n\n<p>This is for <strong>Visual Studio &amp; C#</strong>:</p>\n\n<pre><code>global-ignores = *.suo *.user *.userosscache *.sln.docstates *.userprefs debug release Debug Release bin x64 x86 obj Obj *_i.c *_p.c *_i.h *.ilk *.meta *.obj *.pch *.pdb *.pgc *.pgd *.rsp *.sbr *.tlb *.tli *.tlh *.tmp *.tmp_proj *.log *.psess *.vsp *.vspx *.sap Thumbs.db _UpgradeReport_Files *.dbmdl\n</code></pre>\n\n<p>and goes into your</p>\n\n<pre><code>%APPDATA%/Subversion/config\n</code></pre>\n\n<p>file. If you have a fresh <em>config</em> file, like me, you will only find <em>global-ignore</em> entries that are commented out, so you can append the line.</p>\n\n<p>It is take mainly from the gitignore at <a href=\"https://github.com/github/gitignore/blob/master/VisualStudio.gitignore\" rel=\"noreferrer\">https://github.com/github/gitignore/blob/master/VisualStudio.gitignore</a> .</p>\n\n<p><strong>General case for any language</strong><br>\nBasically, googling (or binging, if you so desire) for \"gitignore (language or tool)\" you will find sample gitignore files, the syntax is similar to the <em>global-ignore</em> of SVN, you just need to do some editing (all entries in one line for SVN, each entry in new line for GIT).</p>\n\n<p>A good text editor like <a href=\"http://www.sublimetext.com/\" rel=\"noreferrer\">Sublime</a> or <a href=\"https://notepad-plus-plus.org/\" rel=\"noreferrer\">Notepad++</a> helps a lot when converting.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11135/" ]
Please give me the direction of the best guidance on the Entity Framework.
Currently I have the following in my Global Ignore Pattern: ``` bin obj CVS .cvsignore *.user *.suo Debug Release *.pdb test.* Thumbs.db ``` Works really well to ignore several hidden or temp files/folders.... So for your specific requirements: * Folders: `bin obj release compile` * Files: `*.bak *.user *.suo` I would use: ``` bin obj release compile *.bak *.user *.suo ```
182,519
<p>Ok I give up, I've been trying to write a regexp in ant to replace the version number from something that I have in a properties file. I have the following:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;feature id="some.feature.id" label="Some test feature" version="1.0.0" provider-name="Provider"&gt; &lt;plugin id="test.plugin" download-size="0" install-size="0" version="0.0.0" unpack="false"/&gt; ..... many plugins later.... &lt;/feature&gt; </code></pre> <p>What I want to achieve is substitute the version number of the feature tag only, without changing the version of the xml or the version of the miriad of plugins in the file.</p> <p>The problem I have is that I either match too much or too little. Definitively matching "version" is not enough, because everything would be changed</p> <p>Is there any easy way to match then only the version inside the tag, taking into consideration that the '0.0.0' could be any number?</p>
[ { "answer_id": 182537, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 0, "selected": false, "text": "<p>A Perl substitution regex would look something like this...</p>\n\n<pre><code>s/&lt;feature(.*?)version=\".*?\"/&lt;feature$1version=\"1.2.3.4\"/s\n</code></pre>\n" }, { "answer_id": 182570, "author": "Tomas Sedovic", "author_id": 2239, "author_profile": "https://Stackoverflow.com/users/2239", "pm_score": 0, "selected": false, "text": "<p>How about:</p>\n\n<pre><code>&lt;feature[^&lt;&gt;]+version\\s*=\\s*\"(\\d+\\.\\d+\\.\\d+)\"[^&lt;&gt;]*&gt;\n</code></pre>\n\n<p>In the parentheses is the group that matches the version number. Move the parentheses around to get the exact match you require.</p>\n" }, { "answer_id": 182577, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The following regex may do what you want...</p>\n\n<pre><code>(?&lt;=&lt;feature[^&gt;]{*,1000}version=\")[^\"]*(?=\")\n</code></pre>\n\n<p>Which, in human speak, roughly means</p>\n\n<blockquote>\n <p>I want to match text that immediately\n follows the string \"&lt;feature\", followed by up to a thousand\n characters not the greater-than bracket, and\n \"version=\"\"; the text to match is immediately followed\n by a double quote, and contains no\n double quotes.</p>\n</blockquote>\n\n<p><code>**</code><em>Thanks to Alan M for the heads up about java lookbehinds</em> ಠ_ಠ</p>\n\n<p>If you use this regex with a Replace operation, it will switch out whatever is inside the version=\"\" attribute with whatever you set as the replacement value. Its up to you to provide the correctly formatted version number.</p>\n\n<p>Now, since you're doing this with XML, the obvious question is, \"Why aren't you using XPath?\"</p>\n" }, { "answer_id": 182601, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 3, "selected": true, "text": "<p>Assuming you're using the <code>replaceregexp</code> task:</p>\n\n<pre><code>&lt;replaceregexp file=\"whatever\"\n match=\"(&lt;feature\\b[^&lt;&gt;]+?version=\\\")[^\\\"]+\"\n replace=\"\\1${feature.version}\" /&gt;\n</code></pre>\n\n<p>I'm also assuming there's only the one <code>&lt;feature&gt;</code> element.</p>\n" }, { "answer_id": 182629, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 0, "selected": false, "text": "<p>Vim ti the rescue:</p>\n\n<pre><code>:s/\\(label=\".+\"\\_.\\s*version=\"\\).+\"/\\1NEWVERSIONNUMBER\"/\n</code></pre>\n" }, { "answer_id": 182954, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 1, "selected": false, "text": "<p>Just for fun: a one-liner, <em>using xpath</em>(!), with <strong>ruby</strong></p>\n\n<p>(I know: it is not a regexp, but it is meant to illustrate the suggestion of Will, who is saying</p>\n\n<blockquote>\n <p>Now, since you're doing this with XML, the obvious question is, \"Why aren't you using XPath?</p>\n</blockquote>\n\n<p>)</p>\n\n<p>type 'irb', then:<br>\n<strong>require \"rexml/document\";include REXML;file = File.new(\"a.xml\"); doc = Document.new(file);puts doc; doc.elements.each(\"/feature\") {|e| e.attributes[\"version\"]=\"1.2.3\" }; puts doc</strong></p>\n\n<p>It replaces all 'version' attributes of all 'feature' elements with \"1.2.3\"</p>\n\n<pre><code>irb(main):001:0* require \"rexml/document\";include REXML;file = File.new(\"a.xml\"); doc = Document.new(file);puts doc; doc.elements.each(\"/feature\") {|e| e.attributes[\"version\"]=\"1.2.3\" }; puts doc\n\n&lt;?xml version='1.0' encoding='UTF-8'?&gt;\n&lt;feature id='some.feature.id' version='1.0.0' provider-name='Provider' label='Some test feature'&gt;\n &lt;plugin unpack='false' id='test.plugin' download-size='0' version='0.0.0' install-size='0'/&gt;\n&lt;/feature&gt;\n\n\n&lt;?xml version='1.0' encoding='UTF-8'?&gt;\n&lt;feature id='some.feature.id' version='1.2.3' provider-name='Provider' label='Some test feature'&gt;\n &lt;plugin unpack='false' id='test.plugin' download-size='0' version='0.0.0' install-size='0'/&gt;\n&lt;/feature&gt;\n</code></pre>\n" }, { "answer_id": 183252, "author": "Adam Crume", "author_id": 25498, "author_profile": "https://Stackoverflow.com/users/25498", "pm_score": 1, "selected": false, "text": "<p>It might be a little heavyweight, but since you're dealing with XML, I would recommend using an XSLT like this:</p>\n\n<pre><code>&lt;xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\"&gt;\n &lt;xsl:template match=\"@*|*\"&gt;\n &lt;xsl:copy&gt;\n &lt;xsl:apply-templates select=\"node()|@*|*\"/&gt;\n &lt;/xsl:copy&gt;\n &lt;/xsl:template&gt;\n\n\n &lt;xsl:template match=\"/feature/@version\"&gt;\n &lt;xsl:attribute name=\"version\"&gt;\n &lt;xsl:text&gt;1.0.1&lt;/xsl:text&gt;\n &lt;/xsl:attribute&gt;\n &lt;/xsl:template&gt;\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2309/" ]
Ok I give up, I've been trying to write a regexp in ant to replace the version number from something that I have in a properties file. I have the following: ``` <?xml version="1.0" encoding="UTF-8"?> <feature id="some.feature.id" label="Some test feature" version="1.0.0" provider-name="Provider"> <plugin id="test.plugin" download-size="0" install-size="0" version="0.0.0" unpack="false"/> ..... many plugins later.... </feature> ``` What I want to achieve is substitute the version number of the feature tag only, without changing the version of the xml or the version of the miriad of plugins in the file. The problem I have is that I either match too much or too little. Definitively matching "version" is not enough, because everything would be changed Is there any easy way to match then only the version inside the tag, taking into consideration that the '0.0.0' could be any number?
Assuming you're using the `replaceregexp` task: ``` <replaceregexp file="whatever" match="(<feature\b[^<>]+?version=\")[^\"]+" replace="\1${feature.version}" /> ``` I'm also assuming there's only the one `<feature>` element.
182,528
<p>Leaving aside the question of whether you should serve single or multiple stylesheets, assuming you're sending just one, what do you think of this as a basic structure?</p> <p>/* Structure */</p> <p>Any template layout stuff should be put into here, so header, footer, body etc.</p> <p>/* Structure End */</p> <p>/* Common Components*/</p> <p>Repeated elements, such as signup forms, lists, etc.</p> <p>/* Common Components End*/</p> <p>/* Specific Page 1 */</p> <p>Some pages might have specific styles, that would go here.</p> <p>/* Specific Page 1 End */</p> <p>/* Specific Page 2 */</p> <p>As above</p> <p>/* Specific Page 2 End */</p> <p>/* Specific Page etc */</p> <p>And so on.</p> <p>/* Specific Page etc End */</p>
[ { "answer_id": 182565, "author": "Rimas Kudelis", "author_id": 25804, "author_profile": "https://Stackoverflow.com/users/25804", "pm_score": 0, "selected": false, "text": "<p>The structure you presented is exactly what I use. However, it seems to me that it still got too complex with new rules showing up and overriding each other... Perhaps I should try to stick to the solution suggested in the topic linked to by Adam instead.</p>\n" }, { "answer_id": 183327, "author": "Matt", "author_id": 17020, "author_profile": "https://Stackoverflow.com/users/17020", "pm_score": 4, "selected": true, "text": "<p>That's similar to how I structure mine, however, I find that using sub-headings is the best way to do it, so I use this structure:</p>\n\n<p>/*************************\n * GLOBAL *\n *************************/</p>\n\n<p>/* All of the common stuff goes here under the appropriate sub headings */</p>\n\n<p>/* Heading formatting */</p>\n\n<p>/* Text formatting */</p>\n\n<p>/* Form formatting */</p>\n\n<p>/* Table formatting */</p>\n\n<p>/* etc */</p>\n\n<p>/*************************\n * LAYOUT *\n *************************/</p>\n\n<p>/* All the layout things go here under sub-headings */</p>\n\n<p>/* Header */</p>\n\n<p>/* Left Sidebar */</p>\n\n<p>/* Right Sidebar */</p>\n\n<p>/* Footer */</p>\n\n<p>/*************************\n * NAVIGATION *\n *************************/</p>\n\n<p>/* I put navigation separate to the layout as there can be a number of navigation points under their sub-headings */</p>\n\n<p>/* Main (horizontal) Navigation */</p>\n\n<p>/* Left Navigation */</p>\n\n<p>/* Right Navigation */</p>\n\n<p>/* Breadcrumb Navigation */</p>\n\n<p>/*************************\n * FORMS *\n *************************/</p>\n\n<p>/* Any form formatting that varies from the common formatting, if there are multiple differently formatted forms, then use sub-headings */</p>\n\n<p>/*************************\n * TABLES *\n *************************/</p>\n\n<p>/* Same deal as forms */</p>\n\n<p>/*************************\n * LISTS *\n *************************/</p>\n\n<p>/* Same deal as forms and tables */</p>\n\n<p>/*************************\n * CONTENT *\n *************************/</p>\n\n<p>/* Any specific formatting for particular pages, grouped by sub-headings for the page the same way as forms, tables and lists */</p>\n\n<p>/*************************\n * CSS SUPPORT *\n *************************/</p>\n\n<p>/* This is for any special formatting that can be applied to any element on any page and have it override the regular formatting for that item. For example, this might have things like: */</p>\n\n<pre><code>.float-right { float: right; }\n.float-left { float: left; }\n.float-center { margin-left: auto; margin-right: auto; }\n.clear { clear: both }\n.clear-block { display: block }\n.text-left { text-align: left }\n.text-right { text-align: right }\n.text-center { text-align: center }\n.text-justify { text-align: justify }\n.bold { font-weight: bold }\n.italic { font-style: italic }\n.underline { border-bottom: 1px solid }\n.nopadding { padding: 0 }\n.nobullet { list-style: none; list-style-image: none }\n</code></pre>\n\n<p>/* etc */</p>\n\n<p>Hope that helps.</p>\n\n<p>I generally don't recommend writing on a single line like that though, or like suggested in the link Adam posted, they get very difficult to skim over if they get long. For the examples above, it was just quicker to type them that way so I didn't have to indent every line.</p>\n\n<p>For formatting I would recommend this structure:</p>\n\n<pre><code>.class {\n width: 200px;\n height: 200px;\n border: 1px solid #000000;\n}\n</code></pre>\n\n<p>And so on, I put the structure of the class or ID at the top, then any other formatting, like the font etc below that. Makes it very quick and clear to skim over.</p>\n" }, { "answer_id": 183395, "author": "Ryan Rodemoyer", "author_id": 1444511, "author_profile": "https://Stackoverflow.com/users/1444511", "pm_score": 0, "selected": false, "text": "<p>It seems like every time I create a new css file, I find a new way to organize it. And they are ALL better than the previous.</p>\n" }, { "answer_id": 184158, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 1, "selected": false, "text": "<p>Whatever makes sense to you is good enough. Frankly, when someone else comes looking for something in your stylesheet - or when you come looking for something, for that matter - they're not going to try to figure out what your organizing structure was. They're just going to search for whatever class or element they need to see. So as long as you generally keep stuff that's related together, and section things off with comments like @Matt suggests, you're fine. </p>\n\n<p>The fact of the matter is that even with a very well-thought-out organizational structure - just like with a well-thought-out filing system - it's not always obvious what goes where; so you're better off just being somewhat sensible, not devoting a lot of time to keeping things organized, and relying on search tools to find what you need. </p>\n" }, { "answer_id": 186404, "author": "allesklar", "author_id": 19893, "author_profile": "https://Stackoverflow.com/users/19893", "pm_score": 1, "selected": false, "text": "<p>I organize my CSS in a similar way as yours but I do start with a reset section. The main idea is to go from general to specific. So here it goes:</p>\n\n<ul>\n<li>reset <br /></li>\n<li>structure <br /></li>\n<li>html_tags <br /></li>\n<li>navigation <br /></li>\n<li>specific sections <br /></li>\n<li>Error messages - that's my last section</li>\n</ul>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2977/" ]
Leaving aside the question of whether you should serve single or multiple stylesheets, assuming you're sending just one, what do you think of this as a basic structure? /\* Structure \*/ Any template layout stuff should be put into here, so header, footer, body etc. /\* Structure End \*/ /\* Common Components\*/ Repeated elements, such as signup forms, lists, etc. /\* Common Components End\*/ /\* Specific Page 1 \*/ Some pages might have specific styles, that would go here. /\* Specific Page 1 End \*/ /\* Specific Page 2 \*/ As above /\* Specific Page 2 End \*/ /\* Specific Page etc \*/ And so on. /\* Specific Page etc End \*/
That's similar to how I structure mine, however, I find that using sub-headings is the best way to do it, so I use this structure: /\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \* GLOBAL \* \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*/ /\* All of the common stuff goes here under the appropriate sub headings \*/ /\* Heading formatting \*/ /\* Text formatting \*/ /\* Form formatting \*/ /\* Table formatting \*/ /\* etc \*/ /\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \* LAYOUT \* \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*/ /\* All the layout things go here under sub-headings \*/ /\* Header \*/ /\* Left Sidebar \*/ /\* Right Sidebar \*/ /\* Footer \*/ /\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \* NAVIGATION \* \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*/ /\* I put navigation separate to the layout as there can be a number of navigation points under their sub-headings \*/ /\* Main (horizontal) Navigation \*/ /\* Left Navigation \*/ /\* Right Navigation \*/ /\* Breadcrumb Navigation \*/ /\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \* FORMS \* \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*/ /\* Any form formatting that varies from the common formatting, if there are multiple differently formatted forms, then use sub-headings \*/ /\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \* TABLES \* \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*/ /\* Same deal as forms \*/ /\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \* LISTS \* \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*/ /\* Same deal as forms and tables \*/ /\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \* CONTENT \* \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*/ /\* Any specific formatting for particular pages, grouped by sub-headings for the page the same way as forms, tables and lists \*/ /\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \* CSS SUPPORT \* \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*/ /\* This is for any special formatting that can be applied to any element on any page and have it override the regular formatting for that item. For example, this might have things like: \*/ ``` .float-right { float: right; } .float-left { float: left; } .float-center { margin-left: auto; margin-right: auto; } .clear { clear: both } .clear-block { display: block } .text-left { text-align: left } .text-right { text-align: right } .text-center { text-align: center } .text-justify { text-align: justify } .bold { font-weight: bold } .italic { font-style: italic } .underline { border-bottom: 1px solid } .nopadding { padding: 0 } .nobullet { list-style: none; list-style-image: none } ``` /\* etc \*/ Hope that helps. I generally don't recommend writing on a single line like that though, or like suggested in the link Adam posted, they get very difficult to skim over if they get long. For the examples above, it was just quicker to type them that way so I didn't have to indent every line. For formatting I would recommend this structure: ``` .class { width: 200px; height: 200px; border: 1px solid #000000; } ``` And so on, I put the structure of the class or ID at the top, then any other formatting, like the font etc below that. Makes it very quick and clear to skim over.
182,529
<p>I have have some code which adds new cells to a table and fills them with text boxes. </p> <p>The way I've coded it so far works fine:</p> <pre><code> TableCell tCell1 = new TableCell(); TableCell tCell2 = new TableCell(); TableCell tCell3 = new TableCell(); TableCell tCell4 = new TableCell(); TableCell tCell5 = new TableCell(); TableCell tCell6 = new TableCell(); TableCell tCell7 = new TableCell(); TextBox txt1 = new TextBox(); TextBox txt2 = new TextBox(); TextBox txt3 = new TextBox(); TextBox txt4 = new TextBox(); TextBox txt5 = new TextBox(); TextBox txt6 = new TextBox(); TextBox txt7 = new TextBox(); tCell1.Controls.Add(txt1); tCell2.Controls.Add(txt2); tCell3.Controls.Add(txt3); tCell4.Controls.Add(txt4); tCell5.Controls.Add(txt5); tCell6.Controls.Add(txt6); tCell7.Controls.Add(txt7); tRow.Cells.Add(tCell1); tRow.Cells.Add(tCell2); tRow.Cells.Add(tCell3); tRow.Cells.Add(tCell4); tRow.Cells.Add(tCell5); tRow.Cells.Add(tCell6); tRow.Cells.Add(tCell7); </code></pre> <p>As you can see there's basically 4 instructions getting repeated 7 times. I'm sure there has to be a way to accomplish this with just 4 lines of code within a FOR loop and having all the names dynamically assigned but I just can't seem to find anything that would point me in the direction of how to do it.</p> <p>Something like the following is what I'm after:</p> <pre><code> for (int i = 0; i &lt; 6; i++) { TableCell tCell[i] = new TableCell(); TextBox txt[i] = new TextBox(); tCell[i].Controls.Add(txt[i]); tRow.Cells.Add(tCell[i]); } </code></pre> <p>Any help would be much appreciated.</p>
[ { "answer_id": 182551, "author": "Lars Mæhlum", "author_id": 960, "author_profile": "https://Stackoverflow.com/users/960", "pm_score": 0, "selected": false, "text": "<p>This should work fine?</p>\n\n<pre><code>for (int i = 0; i &lt; 6; i++)\n{\n TableCell tCell = new TableCell();\n TextBox txt = new TextBox();\n tCell.Controls.Add(txt);\n tRow.Cells.Add(tCell);\n}\n</code></pre>\n\n<p>I don't really get what you need the names for though.<br>\nDo you plan on using the \"txt5\" name as a reference to that specific textbox?<br>\nWhy not just use <code>tRow.Cells[4].Controls[0] As TextBox</code> ?</p>\n" }, { "answer_id": 182557, "author": "Eugene Katz", "author_id": 1533, "author_profile": "https://Stackoverflow.com/users/1533", "pm_score": 3, "selected": true, "text": "<p>I think this should do it: </p>\n\n<pre><code> for (int i = 0; i &lt; 7; i++)\n {\n\n TableCell tCell = new TableCell();\n TextBox txt = new TextBox();\n tCell.Controls.Add(txt);\n tRow.Cells.Add(tCell);\n\n }\n</code></pre>\n\n<p>Make sure that 6 is changed to a 7.</p>\n" }, { "answer_id": 182563, "author": "Ian Jacobs", "author_id": 22818, "author_profile": "https://Stackoverflow.com/users/22818", "pm_score": 0, "selected": false, "text": "<p>What you wrote actually looks pretty close to me. There a re a few points to keep in mind though.</p>\n\n<p>I don't believe you need the array index. As long as tRow is initialized outside the loop it will add the new elements each time. You also may want to set the ID property of each textbox so you can access any specific on you may be looking for down the road.</p>\n" }, { "answer_id": 182604, "author": "Jay Wilde", "author_id": 26126, "author_profile": "https://Stackoverflow.com/users/26126", "pm_score": 0, "selected": false, "text": "<p>Thanks for all the helpful answers. To those asking questions about what I was doing with the arrays, I wasn't! That was just an example of what I was trying to achieve. </p>\n\n<p>Ian and Lars got the right idea in the fact that I will need to refer to these textboxes later so I just need to use Eugene and Lubos' solution and make sure I'm adding a line that will give them sequential ID's (txt1, txt2 etc) so that I can do this.</p>\n\n<p>Thanks again for all the wonderful (and quick!) input, I'm now in love with this site!</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26126/" ]
I have have some code which adds new cells to a table and fills them with text boxes. The way I've coded it so far works fine: ``` TableCell tCell1 = new TableCell(); TableCell tCell2 = new TableCell(); TableCell tCell3 = new TableCell(); TableCell tCell4 = new TableCell(); TableCell tCell5 = new TableCell(); TableCell tCell6 = new TableCell(); TableCell tCell7 = new TableCell(); TextBox txt1 = new TextBox(); TextBox txt2 = new TextBox(); TextBox txt3 = new TextBox(); TextBox txt4 = new TextBox(); TextBox txt5 = new TextBox(); TextBox txt6 = new TextBox(); TextBox txt7 = new TextBox(); tCell1.Controls.Add(txt1); tCell2.Controls.Add(txt2); tCell3.Controls.Add(txt3); tCell4.Controls.Add(txt4); tCell5.Controls.Add(txt5); tCell6.Controls.Add(txt6); tCell7.Controls.Add(txt7); tRow.Cells.Add(tCell1); tRow.Cells.Add(tCell2); tRow.Cells.Add(tCell3); tRow.Cells.Add(tCell4); tRow.Cells.Add(tCell5); tRow.Cells.Add(tCell6); tRow.Cells.Add(tCell7); ``` As you can see there's basically 4 instructions getting repeated 7 times. I'm sure there has to be a way to accomplish this with just 4 lines of code within a FOR loop and having all the names dynamically assigned but I just can't seem to find anything that would point me in the direction of how to do it. Something like the following is what I'm after: ``` for (int i = 0; i < 6; i++) { TableCell tCell[i] = new TableCell(); TextBox txt[i] = new TextBox(); tCell[i].Controls.Add(txt[i]); tRow.Cells.Add(tCell[i]); } ``` Any help would be much appreciated.
I think this should do it: ``` for (int i = 0; i < 7; i++) { TableCell tCell = new TableCell(); TextBox txt = new TextBox(); tCell.Controls.Add(txt); tRow.Cells.Add(tCell); } ``` Make sure that 6 is changed to a 7.
182,542
<p>What do you use to validate an email address on a ASP.NET form. I want to make sure that it contains no XSS exploits.</p> <p>This is ASP.NET 1.1</p>
[ { "answer_id": 182579, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 2, "selected": false, "text": "<p>Preventing XSS is a different issue from validating input.</p>\n\n<p>Regarding XSS: You should not try to check <em>input</em> for XSS or related exploits. You should prevent XSS exploits, SQL injection and so on by escaping correctly when inserting strings into a different language where some characters are \"magic\", eg, when inserting strings in HTML or SQL. For example a name like O'Reilly is perfectly valid input, but could cause a crash or worse if inserted unescaped into SQL. You cannot prevent that kind of problems by validating input.</p>\n\n<p>Validation of user input makes sense to prevent missing or malformed data, eg. a user writing \"asdf\" in the zip-code field and so on. Wrt. e-mail adresses, the syntax is so complex though, that it doesnt provide much benefit to validate it using a regex. Just check that it contains a \"@\".</p>\n" }, { "answer_id": 182580, "author": "Martin Brown", "author_id": 20553, "author_profile": "https://Stackoverflow.com/users/20553", "pm_score": 3, "selected": false, "text": "<p>You can use a RegularExpression validator. The ValidationExpression property has a button you can press in Visual Studio's property's panel that gets lists a lot of useful expressions. The one they use for email addresses is: </p>\n\n<pre><code>\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*\n</code></pre>\n" }, { "answer_id": 182582, "author": "WebDude", "author_id": 15360, "author_profile": "https://Stackoverflow.com/users/15360", "pm_score": 8, "selected": true, "text": "<p>Any script tags posted on an ASP.NET web form will cause your site to throw and unhandled exception.</p>\n\n<p>You can use a asp regex validator to confirm input, just ensure you wrap your code behind method with a if(IsValid) clause in case your javascript is bypassed.\nIf your client javascript is bypassed and script tags are posted to your asp.net form, asp.net will throw a unhandled exception.</p>\n\n<p>You can use something like:</p>\n\n<pre><code>&lt;asp:RegularExpressionValidator ID=\"regexEmailValid\" runat=\"server\" ValidationExpression=\"\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*\" ControlToValidate=\"tbEmail\" ErrorMessage=\"Invalid Email Format\"&gt;&lt;/asp:RegularExpressionValidator&gt;\n</code></pre>\n" }, { "answer_id": 182585, "author": "RB.", "author_id": 15393, "author_profile": "https://Stackoverflow.com/users/15393", "pm_score": 3, "selected": false, "text": "<p>Validating that it is a real email address is much harder.</p>\n\n<p>The regex to confirm the syntax is correct can be very long (see <a href=\"http://www.regular-expressions.info/email.html\" rel=\"noreferrer\">http://www.regular-expressions.info/email.html</a> for example). The best way to confirm an email address is to email the user, and get the user to reply by clicking on a link to validate that they have recieved the email (the way most sign-up systems work).</p>\n" }, { "answer_id": 182599, "author": "Simon Johnson", "author_id": 854, "author_profile": "https://Stackoverflow.com/users/854", "pm_score": 3, "selected": false, "text": "<p>In our code we have a specific validator inherited from the BaseValidator class.</p>\n\n<p>This class does the following:</p>\n\n<ol>\n<li>Validates the e-mail address against a regular expression.</li>\n<li>Does a lookup on the MX record for the domain to make sure there is at least a server to deliver to.</li>\n</ol>\n\n<p>This is the closest you can get to validation without actually sending the person an e-mail confirmation link.</p>\n" }, { "answer_id": 271946, "author": "John_", "author_id": 26081, "author_profile": "https://Stackoverflow.com/users/26081", "pm_score": 4, "selected": false, "text": "<p>Here is a basic email validator I just created based on Simon Johnson's idea. It just needs the extra functionality of DNS lookup being added if it is required.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Web.UI.WebControls;\nusing System.Text.RegularExpressions;\nusing System.Web.UI;\n\nnamespace CompanyName.Library.Web.Controls\n{\n [ToolboxData(\"&lt;{0}:EmailValidator runat=server&gt;&lt;/{0}:EmailValidator&gt;\")]\n public class EmailValidator : BaseValidator\n {\n\n protected override bool EvaluateIsValid()\n {\n string val = this.GetControlValidationValue(this.ControlToValidate);\n string pattern = @\"^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)?@[a-z][a-z|0-9|]*\\.([a-z][a-z|0-9]*(\\.[a-z][a-z|0-9]*)?)$\";\n Match match = Regex.Match(val.Trim(), pattern, RegexOptions.IgnoreCase);\n\n if (match.Success)\n return true;\n else\n return false;\n }\n\n }\n}\n</code></pre>\n\n<p>Update: Please don't use the original Regex. Seek out a newer more complete sample.</p>\n" }, { "answer_id": 43138457, "author": "VDWWD", "author_id": 5836671, "author_profile": "https://Stackoverflow.com/users/5836671", "pm_score": 3, "selected": false, "text": "<p>You should always do server side validaton as well.</p>\n\n<pre><code>public bool IsValidEmailAddress(string email)\n{\n try\n {\n var emailChecked = new System.Net.Mail.MailAddress(email);\n return true;\n }\n catch\n {\n return false;\n }\n}\n</code></pre>\n\n<p>UPDATE</p>\n\n<p>You can also use the <code>EmailAddressAttribute</code> in <code>System.ComponentModel.DataAnnotations</code>. Then there is no need for a try-catch to it's a cleaner solution.</p>\n\n<pre><code>public bool IsValidEmailAddress(string email)\n{\n if (!string.IsNullOrEmpty(email) &amp;&amp; new EmailAddressAttribute().IsValid(email))\n return true;\n else\n return false;\n}\n</code></pre>\n\n<p>Note that the <code>IsNullOrEmpty</code> check is also needed otherwise a <code>null</code> value will return true.</p>\n" }, { "answer_id": 51764513, "author": "Naveen", "author_id": 5718260, "author_profile": "https://Stackoverflow.com/users/5718260", "pm_score": 1, "selected": false, "text": "<p>Quick and Simple Code </p>\n\n<pre><code>public static bool IsValidEmail(this string email)\n{\n const string pattern = @\"^(?!\\.)(\"\"([^\"\"\\r\\\\]|\\\\[\"\"\\r\\\\])*\"\"|\" + @\"([-a-z0-9!#$%&amp;'*+/=?^_`{|}~]|(?&lt;!\\.)\\.)*)(?&lt;!\\.)\" + @\"@[a-z0-9][\\w\\.-]*[a-z0-9]\\.[a-z][a-z\\.]*[a-z]$\"; \n var regex = new Regex(pattern, RegexOptions.IgnoreCase); \n return regex.IsMatch(email);\n}\n</code></pre>\n" }, { "answer_id": 66397618, "author": "Code", "author_id": 9787173, "author_profile": "https://Stackoverflow.com/users/9787173", "pm_score": 0, "selected": false, "text": "<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Globalization;\nusing System.Text.RegularExpressions;\n\n/// &lt;summary&gt;\n/// Summary description for RegexUtilities\n/// &lt;/summary&gt;\npublic class RegexUtilities\n{\n bool InValid = false;\n\n public bool IsValidEmail(string strIn)\n {\n InValid = false;\n if (String.IsNullOrEmpty(strIn))\n return false;\n\n // Use IdnMapping class to convert Unicode domain names.\n strIn = Regex.Replace(strIn, @&quot;(@)(.+)$&quot;, this.DomainMapper);\n if (InValid)\n return false;\n\n // Return true if strIn is in valid e-mail format. \n return Regex.IsMatch(strIn, @&quot;^(?(&quot;&quot;)(&quot;&quot;[^&quot;&quot;]+?&quot;&quot;@)|(([0-9a-z]((\\.(?!\\.))|[-!#\\$%&amp;'\\*\\+/=\\?\\^`\\{\\}\\|~\\w])*)(?&lt;=[0-9a-z])@))&quot; + @&quot;(?(\\[)(\\[(\\d{1,3}\\.){3}\\d{1,3}\\])|(([0-9a-z][-\\w]*[0-9a-z]*\\.)+[a-z0-9]{2,17}))$&quot;,\n RegexOptions.IgnoreCase);\n }\n\n private string DomainMapper(Match match)\n {\n // IdnMapping class with default property values.\n IdnMapping idn = new IdnMapping();\n\n string domainName = match.Groups[2].Value;\n try\n {\n domainName = idn.GetAscii(domainName);\n }\n catch (ArgumentException)\n {\n InValid = true;\n }\n return match.Groups[1].Value + domainName;\n }\n\n}\n\n\n\n\n\nRegexUtilities EmailRegex = new RegexUtilities();\n\n if (txtEmail.Value != &quot;&quot;)\n {\n string[] SplitClients_Email = txtEmail.Value.Split(',');\n string Send_Email, Hold_Email;\n Send_Email = Hold_Email = &quot;&quot;;\n \n int CountEmail;/**Region For Count Total Email**/\n CountEmail = 0;/**First Time Email Counts Zero**/\n bool EmaiValid = false;\n Hold_Email = SplitClients_Email[0].ToString().Trim().TrimEnd().TrimStart().ToString();\n if (SplitClients_Email[0].ToString() != &quot;&quot;)\n {\n if (EmailRegex.IsValidEmail(Hold_Email))\n {\n Send_Email = Hold_Email;\n CountEmail = 1;\n EmaiValid = true;\n }\n else\n {\n EmaiValid = false;\n }\n }\n \n if (EmaiValid == false)\n {\n divStatusMsg.Style.Add(&quot;display&quot;, &quot;&quot;);\n divStatusMsg.Attributes.Add(&quot;class&quot;, &quot;alert alert-danger alert-dismissable&quot;);\n divStatusMsg.InnerText = &quot;ERROR !!...Please Enter A Valid Email ID.&quot;;\n txtEmail.Focus();\n txtEmail.Value = null;\n ScriptManager.RegisterStartupScript(Page, this.GetType(), &quot;SmoothScroll&quot;, &quot;SmoothScroll();&quot;, true);\n divStatusMsg.Visible = true;\n ClientScript.RegisterStartupScript(this.GetType(), &quot;alert&quot;, &quot;HideLabel();&quot;, true);\n return false;\n }\n }\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
What do you use to validate an email address on a ASP.NET form. I want to make sure that it contains no XSS exploits. This is ASP.NET 1.1
Any script tags posted on an ASP.NET web form will cause your site to throw and unhandled exception. You can use a asp regex validator to confirm input, just ensure you wrap your code behind method with a if(IsValid) clause in case your javascript is bypassed. If your client javascript is bypassed and script tags are posted to your asp.net form, asp.net will throw a unhandled exception. You can use something like: ``` <asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="tbEmail" ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator> ```
182,544
<p>SQL to find duplicate entries (within a group)</p> <p>I have a small problem and I'm not sure what would be the best way to fix it, as I only have limited access to the database (Oracle) itself. In our Table "EVENT" we have about 160k entries, each EVENT has a GROUPID and a normal entry has exactly 5 rows with the same GROUPID. Due to a bug we currently get a couple of duplicate entries (duplicate, so 10 rows instead of 5, just a different EVENTID. This may change, so it's just &lt;> 5). We need to filter all the entries of these groups.</p> <p>Due to limited access to the database we can not use a temporary table, nor can we add an index to the GROUPID column to make it faster.</p> <p>We can get the GROUPIDs with this query, but we would need a second query to get the needed data</p> <pre><code>select A."GROUPID" from "EVENT" A group by A."GROUPID" having count(A."GROUPID") &lt;&gt; 5 </code></pre> <p>One solution would be a subselect:</p> <pre><code>select * from "EVENT" A where A."GROUPID" IN ( select B."GROUPID" from "EVENT" B group by B."GROUPID" having count(B."GROUPID") &lt;&gt; 5 ) </code></pre> <p>Without an index on GROUPID and 160k entries, this takes much too long. Tried thinking about a join that can handle this, but can't find a good solution so far.</p> <p>Anybody can find a good solution for this maybe?</p> <p>Small edit: We don't have 100% duplicates here, as each entry still has a unique ID and the GROUPID is not unique either (that's why we need to use "group by") - or maybe I just miss an easy solution for it :)</p> <p>Small example about the data (I don't want to delete it, just find it)</p> <p><code> EVENTID | GROUPID | TYPEID<br> 123456&nbsp;&nbsp;&nbsp;&nbsp;123&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;12<br> 123457&nbsp;&nbsp;&nbsp;&nbsp;123&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;145<br> 123458&nbsp;&nbsp;&nbsp;&nbsp;123&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2612<br> 123459&nbsp;&nbsp;&nbsp;&nbsp;123&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;41<br> 123460&nbsp;&nbsp;&nbsp;&nbsp;123&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;238<br> <br> 234567&nbsp;&nbsp;&nbsp;&nbsp;123&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;12<br> 234568&nbsp;&nbsp;&nbsp;&nbsp;123&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;145<br> 234569&nbsp;&nbsp;&nbsp;&nbsp;123&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2612<br> 234570&nbsp;&nbsp;&nbsp;&nbsp;123&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;41<br> 234571&nbsp;&nbsp;&nbsp;&nbsp;123&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;238<br> </code><br> It has some more columns, like timestamp etc, but as you can see already, everything is identical, besides the EVENTID.</p> <p>We will run it more often for testing, to find the bug and check if it happens again.</p>
[ { "answer_id": 182575, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "<p>If your DBAs won't add an index to make this faster, ask them what they suggest you do (that's what they're paid for, after all). Presumably you have a business case why you need this information in which case your immediate management should be on your side.</p>\n\n<p>Perhaps you could ask your DBAs to duplicate the data into a database where you <strong>could</strong> add an index.</p>\n" }, { "answer_id": 182612, "author": "Michael OShea", "author_id": 13178, "author_profile": "https://Stackoverflow.com/users/13178", "pm_score": 2, "selected": false, "text": "<p>From a SQL perspective I think you've already answered your own question. The approach you've described (ie using the sub-select) is fine, and I'd be surprised if any other way of writing the query differed vastly in performance.</p>\n\n<p>160K records doesn't seem like a lot to me. I could understand if you were unhappy with the performance of that query if it was going into a piece of application code, but from the sounds of it you're just using it as part of some data cleansing excercise. (and so would expect you to be a little more tolerant in performance terms).</p>\n\n<p>Even without any supporting index, its still just two full table table scans on 160K rows, which frankly, I'd expect to perform in some sort of vaguely reasonable time.</p>\n\n<p>Talk to your db administrators. They've helped create the problem, so let them be part of the solution.</p>\n\n<p>/EDIT/ In the meantime, run the query you have. Find out how long it takes, rather than guessing. Even better would be to run it, with set autotrace on, and post the results here, then we might be able to help you refine it somewhat.</p>\n" }, { "answer_id": 182669, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 2, "selected": false, "text": "<p>How long does that SQL actually take? You are only going to run it once I presume, having fixed the bug that caused the corruption in the first place? I just set up a test case like this:</p>\n\n<pre><code>SQL&gt; create table my_objects as \n 2 select object_name, ceil(rownum/5) groupid, rpad('x',500,'x') filler\n 3 from all_objects;\n\nTable created.\n\nSQL&gt; select count(*) from my_objects;\n\n COUNT(*)\n----------\n 83782\n\nSQL&gt; select * from my_objects where groupid in (\n 2 select groupid from my_objects\n 3 group by groupid\n 4 having count(*) &lt;&gt; 5\n 5 );\n\nOBJECT_NAME GROUPID FILLER\n------------------------------ ---------- --------------------------------\nXYZ 16757 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nYYYY 16757 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\nElapsed: 00:00:01.67\n</code></pre>\n\n<p>Less than 2 seconds. OK, my table has half as many rows as yours, but 160K isn't huge. I added the filler column to make the table take up some disk space. The AUTOTRACE execution plan was:</p>\n\n<pre><code>-------------------------------------------------------------------------\n| Id | Operation | Name | Rows | Bytes | Cost (%CPU)|\n-------------------------------------------------------------------------\n| 0 | SELECT STATEMENT | | 389 | 112K| 14029 (2)|\n|* 1 | HASH JOIN | | 389 | 112K| 14029 (2)|\n| 2 | VIEW | VW_NSO_1 | 94424 | 1198K| 6570 (2)|\n|* 3 | FILTER | | | | |\n| 4 | HASH GROUP BY | | 1 | 1198K| 6570 (2)|\n| 5 | TABLE ACCESS FULL| MY_OBJECTS | 94424 | 1198K| 6504 (1)|\n| 6 | TABLE ACCESS FULL | MY_OBJECTS | 94424 | 25M| 6506 (1)|\n-------------------------------------------------------------------------\n</code></pre>\n" }, { "answer_id": 182694, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 4, "selected": true, "text": "<p>You can get the answer with a join instead of a subquery</p>\n\n<pre><code>select\n a.*\nfrom\n event as a\ninner join\n (select groupid\n from event\n group by groupid\n having count(*) &lt;&gt; 5) as b\n on a.groupid = b.groupid\n</code></pre>\n\n<p>This is a fairly common way of obtaining the all the information out of the rows in a group. </p>\n\n<p>Like your suggested answer and the other responses, this will run a lot faster with an index on groupid. It's up to the DBA to balance the benefit of making your query run a lot faster against the cost of maintaining yet another index. </p>\n\n<p>If the DBA decides against the index, make sure the appropriate people understand that its the index strategy and not the way you wrote the query that is slowing things down.</p>\n" }, { "answer_id": 182713, "author": "ilitirit", "author_id": 9825, "author_profile": "https://Stackoverflow.com/users/9825", "pm_score": 0, "selected": false, "text": "<p>Does this work do what you want, and does it offer better performance? (I just thought I'd throw it in as a suggestion).</p>\n\n<pre><code>select * \nfrom group g\nwhere (select count(*) from event e where g.groupid = e.groupid) &lt;&gt; 5\n</code></pre>\n" }, { "answer_id": 182734, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 0, "selected": false, "text": "<p>How about an analytic:</p>\n\n<pre><code>SELECT * FROM (\nSELECT eventid, groupid, typeid, COUNT(groupid) OVER (PARTITION BY groupid) group_count\n FROM event\n)\n WHERE group_count &lt;&gt; 5\n</code></pre>\n" }, { "answer_id": 182747, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 3, "selected": false, "text": "<p>A classic problem for analytic queries to solve:</p>\n\n<pre><code>select eventid,\n groupid,\n typeid\nfrom (\n Select eventid,\n groupid,\n typeid,\n count(*) over (partition by group_id) count_by_group_id\n from EVENT\n )\nwhere count_by_group_id &lt;&gt; 5\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3134/" ]
SQL to find duplicate entries (within a group) I have a small problem and I'm not sure what would be the best way to fix it, as I only have limited access to the database (Oracle) itself. In our Table "EVENT" we have about 160k entries, each EVENT has a GROUPID and a normal entry has exactly 5 rows with the same GROUPID. Due to a bug we currently get a couple of duplicate entries (duplicate, so 10 rows instead of 5, just a different EVENTID. This may change, so it's just <> 5). We need to filter all the entries of these groups. Due to limited access to the database we can not use a temporary table, nor can we add an index to the GROUPID column to make it faster. We can get the GROUPIDs with this query, but we would need a second query to get the needed data ``` select A."GROUPID" from "EVENT" A group by A."GROUPID" having count(A."GROUPID") <> 5 ``` One solution would be a subselect: ``` select * from "EVENT" A where A."GROUPID" IN ( select B."GROUPID" from "EVENT" B group by B."GROUPID" having count(B."GROUPID") <> 5 ) ``` Without an index on GROUPID and 160k entries, this takes much too long. Tried thinking about a join that can handle this, but can't find a good solution so far. Anybody can find a good solution for this maybe? Small edit: We don't have 100% duplicates here, as each entry still has a unique ID and the GROUPID is not unique either (that's why we need to use "group by") - or maybe I just miss an easy solution for it :) Small example about the data (I don't want to delete it, just find it) `EVENTID | GROUPID | TYPEID 123456    123       12 123457    123       145 123458    123       2612 123459    123       41 123460    123       238 234567    123       12 234568    123       145 234569    123       2612 234570    123       41 234571    123       238` It has some more columns, like timestamp etc, but as you can see already, everything is identical, besides the EVENTID. We will run it more often for testing, to find the bug and check if it happens again.
You can get the answer with a join instead of a subquery ``` select a.* from event as a inner join (select groupid from event group by groupid having count(*) <> 5) as b on a.groupid = b.groupid ``` This is a fairly common way of obtaining the all the information out of the rows in a group. Like your suggested answer and the other responses, this will run a lot faster with an index on groupid. It's up to the DBA to balance the benefit of making your query run a lot faster against the cost of maintaining yet another index. If the DBA decides against the index, make sure the appropriate people understand that its the index strategy and not the way you wrote the query that is slowing things down.
182,569
<p>Sybase db tables do not have a concept of self updating row numbers. However , for one of the modules , I require the presence of rownumber corresponding to each row in the database such that max(Column) would always tell me the number of rows in the table.</p> <p>I thought I'll introduce an int column and keep updating this column to keep track of the row number. However I'm having problems in updating this column in case of deletes. What sql should I use in delete trigger to update this column? </p>
[ { "answer_id": 182744, "author": "AdamH", "author_id": 21081, "author_profile": "https://Stackoverflow.com/users/21081", "pm_score": 2, "selected": false, "text": "<p>You can easily assign a unique number to each row by using an identity column. The identity can be a numeric or an integer (in ASE12+).</p>\n\n<p>This will <em>almost</em> do what you require. There are certain circumstances in which you will get a gap in the identity sequence. (These are called \"identity gaps\", the best discussion on them is <a href=\"http://www.sypron.nl/idgaps.html\" rel=\"nofollow noreferrer\">here</a>). Also deletes will cause gaps in the sequence as you've identified.</p>\n\n<p>Why do you need to use max(col) to get the number of rows in the table, when you could just use count(*)? If you're trying to get the last row from the table, then you can do</p>\n\n<pre><code>select * from table where column = (select max(column) from table).\n</code></pre>\n\n<p>Regarding the delete trigger to update a manually managed column, I think this would be a potential source of deadlocks, and many performance issues. Imagine you have 1 million rows in your table, and you delete row 1, that's 999999 rows you now have to update to subtract 1 from the id.</p>\n" }, { "answer_id": 183510, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I'm not sure why you would want to do this. You could experiment with using temporary tables and <a href=\"http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.help.ase_12.5.sqlug/html/sqlug/sqlug345.htm\" rel=\"nofollow noreferrer\">\"select into\" with an Identity column</a> like below.</p>\n\n<pre><code>create table test\n ( \n col1 int,\n col2 varchar(3)\n )\n\n insert into test values (100, \"abc\")\n insert into test values (111, \"def\")\n insert into test values (222, \"ghi\")\n insert into test values (300, \"jkl\")\n insert into test values (400, \"mno\")\n\nselect rank = identity(10), col1 into #t1 from Test\nselect * from #t1\n\ndelete from test where col2=\"ghi\"\n\nselect rank = identity(10), col1 into #t2 from Test\nselect * from #t2\n\ndrop table test\ndrop table #t1\ndrop table #t2\n</code></pre>\n\n<p>This would give you a dynamic id (of sorts)</p>\n" }, { "answer_id": 187083, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 1, "selected": true, "text": "<h2>Delete trigger</h2>\n\n<pre><code>CREATE TRIGGER tigger ON myTable FOR DELETE\nAS \nupdate myTable \nset id = id - (select count(*) from deleted d where d.id &lt; t.id) \nfrom myTable t\n</code></pre>\n\n<h2>To avoid locking problems</h2>\n\n<p>You could add an extra table (which joins to your primary table) like this: </p>\n\n<pre><code>CREATE TABLE rowCounter \n(id int, -- foreign key to main table\n rownum int) \n</code></pre>\n\n<p>... and use the rownum field from this table.<br>\nIf you put the delete trigger on this table then you would hugely reduce the potential for locking problems. </p>\n\n<h2>Approximate solution?</h2>\n\n<p>Does the table need to keep its rownumbers up to date all the time?<br>\nIf not, you could have a job which runs every minute or so, which checks for gaps in the rownum, and does an update. </p>\n\n<p>Question: do the rownumbers have to reflect the order in which rows were inserted?<br>\nIf not, you could do far fewer updates, but only updating the most recent rows, \"moving\" them into gaps. </p>\n\n<p>Leave a comment if you would like me to post any SQL for these ideas. </p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18275/" ]
Sybase db tables do not have a concept of self updating row numbers. However , for one of the modules , I require the presence of rownumber corresponding to each row in the database such that max(Column) would always tell me the number of rows in the table. I thought I'll introduce an int column and keep updating this column to keep track of the row number. However I'm having problems in updating this column in case of deletes. What sql should I use in delete trigger to update this column?
Delete trigger -------------- ``` CREATE TRIGGER tigger ON myTable FOR DELETE AS update myTable set id = id - (select count(*) from deleted d where d.id < t.id) from myTable t ``` To avoid locking problems ------------------------- You could add an extra table (which joins to your primary table) like this: ``` CREATE TABLE rowCounter (id int, -- foreign key to main table rownum int) ``` ... and use the rownum field from this table. If you put the delete trigger on this table then you would hugely reduce the potential for locking problems. Approximate solution? --------------------- Does the table need to keep its rownumbers up to date all the time? If not, you could have a job which runs every minute or so, which checks for gaps in the rownum, and does an update. Question: do the rownumbers have to reflect the order in which rows were inserted? If not, you could do far fewer updates, but only updating the most recent rows, "moving" them into gaps. Leave a comment if you would like me to post any SQL for these ideas.
182,573
<p>PowerShell v1.0 is obviously a console based administrative shell. It doesn't really require a GUI interface. If one is required, like the Exchange 2007 management GUI, it is built on top of PowerShell. You can create your own GUI using Windows Forms in a PowerShell script. My question is, "What sort of PowerShell scripts or management tasks do you think would be best served with the addition of even a simple graphical interface? What have you created winforms to accomplish?"</p>
[ { "answer_id": 183053, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Isnt this mainly used by powershell guys who want to make there scripts pretty before handing to users or people who know nothing about a console and like pretty pictures ?!</p>\n" }, { "answer_id": 183110, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 0, "selected": false, "text": "<p>I would head over to the PowerGUI site which I'm sure you are already aware of Jeff. The sort of things that users are doing there are what I would consider exemplars of the fusion of powershell and a GUI. The ability to generate a list of objects then drill down into the hierarchical structure of the objects, or run scripts on an object. This sort of thing is where I would see a GUI interface shine. </p>\n" }, { "answer_id": 185629, "author": "slipsec", "author_id": 1635, "author_profile": "https://Stackoverflow.com/users/1635", "pm_score": 0, "selected": false, "text": "<p>I'm hopeful for some examples here because I'm sure there's loads of tasks I would be able to delegate down if they had a pretty UI on them and were usable with a mouse.</p>\n\n<p>But as far as adding a user interface, I'm having trouble of thinking of a spot where there's not one. Most of the examples I can think of are either just dumbing down or exposing a selected section of an existing UI. They are typically just a different view to the existing data that's not there, or hard to see in the provided management console. Or they extend some functionality with looping or pipelining (you can still use the mouse to change the names of 200 files if you want). Almost everything I've done that's still in use is either one-shot scripts, or sitting as a scheduled task somewhere.</p>\n\n<p>I'm waiting for ideas :)</p>\n" }, { "answer_id": 185822, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 1, "selected": false, "text": "<p>My favorite old gui tool for a command line shell was a select directory tool that when exectued from the command line would open a gui directory selection dialog. Very help full when you have to cd to some other directory with a long path name.</p>\n\n<p>I couldn't find the old exe tool I used to use unfortunalty. (It was pre-powershell anyway)\nAlso, I'm not familiar enough with powershell to figure out how to call the dialog from powershell directly and make this a cmd-let or whatever, but here's what I'm talking about with some python mixed in.</p>\n\n<p>Here it is:</p>\n\n<pre><code>PS D:\\&gt; $dir = &amp; \"C:\\python25\\python.exe\" \"C:\\python25\\selectdir.pyw\"; cd $dir;\n# Directory selection dialog opens here, user selects the directory to goto.\nPS D:\\NewDirectory&gt;\n</code></pre>\n\n<p>And the python code:</p>\n\n<pre><code>import Tkinter\nimport tkFileDialog\n\nroot = Tkinter.Tk()\nroot.withdraw()\ndirname = tkFileDialog.askdirectory(parent=root)\n\nprint dirname\n</code></pre>\n\n<p>I'd like to have this tool again, if anyone knows how to clean this up so I can just call a command like, \"cdir\" or something please comment.</p>\n" }, { "answer_id": 186261, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Actually, thinking more about this, In the examples I have seen that use a GUI they seem to be multiple input front ends, something that is done alot easier than a command line with several switches which may be quite long and harder to visualise.</p>\n" }, { "answer_id": 216936, "author": "Emperor XLII", "author_id": 2495, "author_profile": "https://Stackoverflow.com/users/2495", "pm_score": 2, "selected": false, "text": "<p>In answer to <a href=\"https://stackoverflow.com/questions/182573/powershell-cli-or-gui-which-do-you-need-or-prefer#185822\">monkut's suggestion</a>, here's a simple function to get file paths using the WindowsForms <code>OpenFileDialog</code>:</p>\n\n<pre><code>[void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' )\n\nfunction Select-File( [string]$initialDirectory=$pwd, [switch]$multiselect ) {\n $dialog = New-Object Windows.Forms.OpenFileDialog\n $dialog.ShowHelp = $true # http://tinyurl.com/6cnmrr\n $dialog.InitialDirectory = $initialDirectory\n $dialog.Multiselect = $multiselect\n\n if( $dialog.ShowDialog( ) -eq 'OK' ) { $dialog.FileNames }\n $dialog.Dispose( )\n}\n</code></pre>\n\n<p>I also tried creating a similar <code>Select-Directory</code> function, but <a href=\"https://stackoverflow.com/questions/216817/call-folderbrowserdialog-from-powershell\"><code>FolderBrowserDialog</code>'s STA thread requirement</a> is rather difficult to achieve in PowerShell v1.</p>\n\n<hr>\n\n<p><strong>Edit:</strong> Thanks to <a href=\"https://stackoverflow.com/questions/216817/call-folderbrowserdialog-from-powershell#217527\">Gordon</a>, here's a workaround to show the <code>FolderBrowserDialog</code> using COM:</p>\n\n<pre><code>function Select-Directory( ) {\n $app = New-Object -COM Shell.Application\n $directory = $app.BrowseForFolder( 0, \"Select Directory\", 0 )\n $path = $directory.Self.Path\n if( $path ) { return $path }\n}\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25508/" ]
PowerShell v1.0 is obviously a console based administrative shell. It doesn't really require a GUI interface. If one is required, like the Exchange 2007 management GUI, it is built on top of PowerShell. You can create your own GUI using Windows Forms in a PowerShell script. My question is, "What sort of PowerShell scripts or management tasks do you think would be best served with the addition of even a simple graphical interface? What have you created winforms to accomplish?"
In answer to [monkut's suggestion](https://stackoverflow.com/questions/182573/powershell-cli-or-gui-which-do-you-need-or-prefer#185822), here's a simple function to get file paths using the WindowsForms `OpenFileDialog`: ``` [void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' ) function Select-File( [string]$initialDirectory=$pwd, [switch]$multiselect ) { $dialog = New-Object Windows.Forms.OpenFileDialog $dialog.ShowHelp = $true # http://tinyurl.com/6cnmrr $dialog.InitialDirectory = $initialDirectory $dialog.Multiselect = $multiselect if( $dialog.ShowDialog( ) -eq 'OK' ) { $dialog.FileNames } $dialog.Dispose( ) } ``` I also tried creating a similar `Select-Directory` function, but [`FolderBrowserDialog`'s STA thread requirement](https://stackoverflow.com/questions/216817/call-folderbrowserdialog-from-powershell) is rather difficult to achieve in PowerShell v1. --- **Edit:** Thanks to [Gordon](https://stackoverflow.com/questions/216817/call-folderbrowserdialog-from-powershell#217527), here's a workaround to show the `FolderBrowserDialog` using COM: ``` function Select-Directory( ) { $app = New-Object -COM Shell.Application $directory = $app.BrowseForFolder( 0, "Select Directory", 0 ) $path = $directory.Self.Path if( $path ) { return $path } } ```
182,587
<p>Is there a best practice when it comes to setting client side "onclick" events when using ASP.Net controls? Simply adding the onclick attribute results in a Visual Studio warning that onclick is not a valid attribute of that control. Adding it during the Page_Load event through codebehind works, but is less clear than I'd like.</p> <p>Are these the only two choices? Is there a right way to do this that I'm missing?</p> <p>Thanks! Eric Sipple</p>
[ { "answer_id": 182642, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "<p>Setting the value for <code>WebControl.Attributes[\"onclick\"]</code> is okay. If ASP.NET needs a client-side <code>click</code> handler, it will concatenate the values, delimited by semi-colon.</p>\n" }, { "answer_id": 182649, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p><code>**</code><em>just a pre-note on the answer: HTML validation in VS is often BS. It complains about stuff that works IRL, even if that stuff is bad practice. But sometimes you gotta bend the rules to get stuff done.</em></p>\n\n<p>Every ASP.NET page (2.0 and greater) comes with a <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.aspx\" rel=\"nofollow noreferrer\">ClientScriptManager</a>. You use this to register javascript from server side code. You can pass in javascript that registers events on controls after the page has loaded, when the HTML controls on the page are all present in the DOM.</p>\n\n<p>It presents a single, unified place on pages to dynamically add javascript, which isn't a bad thing. It is, however, awfully ugly. </p>\n\n<p>In this time of the death of the ASP.NET server control model, you might want to set events the way they will be in the future of ASP.NET MVC. Grab a copy of <a href=\"http://jquery.com\" rel=\"nofollow noreferrer\">jQuery</a> and add it to your website. You can then easily register your events thusly:</p>\n\n<pre><code> &lt;html&gt;\n &lt;head&gt;\n &lt;script type=\"text/javascript\" src=\"jquery.js\"&gt;&lt;/script&gt;\n &lt;script type=\"text/javascript\"&gt;\n $(document).ready(function(){\n $(\"controlId\").bind(\"click\", function(e) { /* do your best here! */ });\n });\n &lt;/script&gt;\n &lt;/head&gt;\n &lt;!-- etc --&gt;\n &lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 182688, "author": "Alex Gyoshev", "author_id": 25427, "author_profile": "https://Stackoverflow.com/users/25427", "pm_score": 2, "selected": false, "text": "<p>You can add the events through Javascript to the HTML elements that you want. This is the cleanest way, since it doesn't mix the server&amp;client technologies. Furthermore, this way many handlers can be registered to the same event (in contrast to the onclick attribute).</p>\n\n<p>Basically, the code would be</p>\n\n<pre><code>document.getElementById('myLovelyButtonId').attachEvent('onclick',doSomething)\n</code></pre>\n\n<p>for Internet Explorer and</p>\n\n<pre><code>document.getElementById('myLovelyButtonId').addEventListener('click',doSomething,false)\n</code></pre>\n\n<p>for other browsers. (doSomething is an event handler - JavaScript function). These calls should be made in the <em>window load</em> event handler</p>\n\n<p>Consider reading the <a href=\"http://quirksmode.org/js/events_advanced.html\" rel=\"nofollow noreferrer\">advanced event registration article on Quirksmode</a> for further info.</p>\n\n<p>Also, consider using a library like <a href=\"http://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a>. This way, the statement will become</p>\n\n<pre><code>$('#myLovelyButtonId').click(\n function doSomething () {\n alert('my lovely code here');\n });\n</code></pre>\n" }, { "answer_id": 1017511, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Fix grammatical or spelling errors.</p>\n\n<p>Clarify meaning without changing it.</p>\n\n<p>Correct minor mistakes.</p>\n\n<p>Add related resources or links.</p>\n\n<p>Always respect the original author.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111/" ]
Is there a best practice when it comes to setting client side "onclick" events when using ASP.Net controls? Simply adding the onclick attribute results in a Visual Studio warning that onclick is not a valid attribute of that control. Adding it during the Page\_Load event through codebehind works, but is less clear than I'd like. Are these the only two choices? Is there a right way to do this that I'm missing? Thanks! Eric Sipple
`**`*just a pre-note on the answer: HTML validation in VS is often BS. It complains about stuff that works IRL, even if that stuff is bad practice. But sometimes you gotta bend the rules to get stuff done.* Every ASP.NET page (2.0 and greater) comes with a [ClientScriptManager](http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.aspx). You use this to register javascript from server side code. You can pass in javascript that registers events on controls after the page has loaded, when the HTML controls on the page are all present in the DOM. It presents a single, unified place on pages to dynamically add javascript, which isn't a bad thing. It is, however, awfully ugly. In this time of the death of the ASP.NET server control model, you might want to set events the way they will be in the future of ASP.NET MVC. Grab a copy of [jQuery](http://jquery.com) and add it to your website. You can then easily register your events thusly: ``` <html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("controlId").bind("click", function(e) { /* do your best here! */ }); }); </script> </head> <!-- etc --> </html> ```
182,592
<p>I have a webapp that segfaults when the database in restarted and it tries to use the old connections. Running it under <code>gdb --args apache -X</code> leads to the following output:</p> <pre><code>Program received signal SIGSEGV, Segmentation fault. [Switching to Thread -1212868928 (LWP 16098)] 0xb7471c20 in mysql_send_query () from /usr/lib/libmysqlclient.so.15 </code></pre> <p>I've checked that the drivers and database are all up to date (<a href="http://search.cpan.org/dist/DBD-mysql/" rel="nofollow noreferrer" title="DBD::mysql">DBD::mysql</a> 4.0008, MySQL 5.0.32-Debian_7etch6-log).</p> <p>Annoyingly I can't reproduce this with a trivial script:</p> <pre><code>use DBI; use Test::More tests =&gt; 2; my $dbh = DBI-&gt;connect( "dbi:mysql:test", 'root' ); sub test_db { my ($number) = $dbh-&gt;selectrow_array("select 1 "); return $number; } is test_db, 1, "connected to db"; warn "restart db now"; getc; is test_db, 1, "connected to db"; </code></pre> <p>Which gives the following:</p> <pre><code>ok 1 - connected to db restart db now at dbd-mysql-test.pl line 23. DBD::mysql::db selectrow_array failed: MySQL server has gone away at dbd-mysql-test.pl line 17. not ok 2 - connected to db # Failed test 'connected to db' # at dbd-mysql-test.pl line 26. # got: undef # expected: '1' </code></pre> <p>This behaves correctly, telling me why the request failed.</p> <p>What stumps me is that it is segfaulting, which it shouldn't do. As it only appears to happen when the whole app is running (which uses <a href="http://search.cpan.org/dist/DBIx-Class" rel="nofollow noreferrer" title="DBIx::Class">DBIx::Class</a>) it is hard to reduce it to a test case.</p> <p>Where should I start to look to debug this? Has anyone else seen this?</p> <p><strong>UPDATE</strong>: further prodding showed that it being under mod_perl was a red herring. Having reduced it to a simple test script I've now posted to the <a href="http://www.mail-archive.com/[email protected]/msg31416.html" rel="nofollow noreferrer">DBI mailing list</a>. Thanks for your answers.</p>
[ { "answer_id": 182757, "author": "mpeters", "author_id": 12094, "author_profile": "https://Stackoverflow.com/users/12094", "pm_score": 2, "selected": false, "text": "<p>What this probably means is that there's a difference between your mod_perl environment and the one you were testing via your script. Some things to check:</p>\n\n<ul>\n<li><p>Was your mod_perl compiled with the same version of Perl</p></li>\n<li><p>Are the @INC's the same for both</p></li>\n<li><p>Are you using threads in your mod_perl setup? I don't believe DBD::mysql is completely thread-safe.</p></li>\n</ul>\n" }, { "answer_id": 185176, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": 2, "selected": false, "text": "<p>I've seen this problem, but I'm not sure it had the same cause as yours. Are you by chance using a certain module for sending mails (forgot the name, sorry) from your application? When we had the problem in a project, after days of debugging we found that this mail module was doing strange things with open file descriptors, then forked off another process which called the console tool sendmail, which again did strange things with file descriptors. I guess one of the file descriptors it messed around with was the connection to the database, but I'm still not sure about that. The problem disappeared when we switched to another module for sending mails. Maybe it's worth a look for you too.</p>\n" }, { "answer_id": 186228, "author": "Ovid", "author_id": 8003, "author_profile": "https://Stackoverflow.com/users/8003", "pm_score": 2, "selected": false, "text": "<p>If you're getting a segfault, do you have a core file greated? If not, check ulimit -c. If that returns 0, your system won't create core files and you'll have to change that. If you do have a core file, you can use gdb or similar tools to debug it. It's not particularly <em>fun</em>, but it's possible. The start of the command will look something like:</p>\n\n<pre><code>gbd /usr/bin/httpd core\n</code></pre>\n\n<p>There are plenty of tutorials for <a href=\"http://www.google.com/search?hl=en&amp;q=debugging+core+files&amp;btnG=Search\" rel=\"nofollow noreferrer\">debugging core files</a> scattered about the Web.</p>\n\n<p>Update: Just found a reference for <a href=\"http://modperlbook.org/html/21-6-3-Dumping-the-core-File.html\" rel=\"nofollow noreferrer\">ensuring you get core dumps from mod_perl</a>. That should help.</p>\n" }, { "answer_id": 3489623, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 2, "selected": true, "text": "<p>This is a known problem in old DBD::mysql. Upgrade it (4.008 is <em>not</em> up to date).</p>\n\n<p>There's a simple test script attached to <a href=\"https://rt.cpan.org/Public/Bug/Display.html?id=37027\" rel=\"nofollow noreferrer\">https://rt.cpan.org/Public/Bug/Display.html?id=37027</a>\nthat will trigger this bug.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5349/" ]
I have a webapp that segfaults when the database in restarted and it tries to use the old connections. Running it under `gdb --args apache -X` leads to the following output: ``` Program received signal SIGSEGV, Segmentation fault. [Switching to Thread -1212868928 (LWP 16098)] 0xb7471c20 in mysql_send_query () from /usr/lib/libmysqlclient.so.15 ``` I've checked that the drivers and database are all up to date ([DBD::mysql](http://search.cpan.org/dist/DBD-mysql/ "DBD::mysql") 4.0008, MySQL 5.0.32-Debian\_7etch6-log). Annoyingly I can't reproduce this with a trivial script: ``` use DBI; use Test::More tests => 2; my $dbh = DBI->connect( "dbi:mysql:test", 'root' ); sub test_db { my ($number) = $dbh->selectrow_array("select 1 "); return $number; } is test_db, 1, "connected to db"; warn "restart db now"; getc; is test_db, 1, "connected to db"; ``` Which gives the following: ``` ok 1 - connected to db restart db now at dbd-mysql-test.pl line 23. DBD::mysql::db selectrow_array failed: MySQL server has gone away at dbd-mysql-test.pl line 17. not ok 2 - connected to db # Failed test 'connected to db' # at dbd-mysql-test.pl line 26. # got: undef # expected: '1' ``` This behaves correctly, telling me why the request failed. What stumps me is that it is segfaulting, which it shouldn't do. As it only appears to happen when the whole app is running (which uses [DBIx::Class](http://search.cpan.org/dist/DBIx-Class "DBIx::Class")) it is hard to reduce it to a test case. Where should I start to look to debug this? Has anyone else seen this? **UPDATE**: further prodding showed that it being under mod\_perl was a red herring. Having reduced it to a simple test script I've now posted to the [DBI mailing list](http://www.mail-archive.com/[email protected]/msg31416.html). Thanks for your answers.
This is a known problem in old DBD::mysql. Upgrade it (4.008 is *not* up to date). There's a simple test script attached to <https://rt.cpan.org/Public/Bug/Display.html?id=37027> that will trigger this bug.
182,600
<p>If you had to iterate through a loop 7 times, would you use:</p> <pre><code>for (int i = 0; i &lt; 7; i++) </code></pre> <p>or:</p> <pre><code>for (int i = 0; i &lt;= 6; i++) </code></pre> <p>There are two considerations:</p> <ul> <li>performance</li> <li>readability </li> </ul> <p>For performance I'm assuming Java or C#. Does it matter if "less than" or "less than or equal to" is used? If you have insight for a different language, please indicate which.</p> <p>For readability I'm assuming 0-based arrays.</p> <p><strong>UPD:</strong> My mention of 0-based arrays may have confused things. I'm not talking about iterating through array elements. Just a general loop. </p> <p>There is a good point below about using a constant to which would explain what this magic number is. So if I had "<code>int NUMBER_OF_THINGS = 7</code>" then "<code>i &lt;= NUMBER_OF_THINGS - 1</code>" would look weird, wouldn't it. </p>
[ { "answer_id": 182606, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 3, "selected": false, "text": "<p>It makes no effective difference when it comes to performance. Therefore I would use whichever is easier to understand in the context of the problem you are solving.</p>\n" }, { "answer_id": 182610, "author": "Steve Losh", "author_id": 13498, "author_profile": "https://Stackoverflow.com/users/13498", "pm_score": 6, "selected": false, "text": "<p>Both of those loops iterate 7 times. I'd say the one with a 7 in it is more readable/clearer, unless you have a really good reason for the other.</p>\n" }, { "answer_id": 182613, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 2, "selected": false, "text": "<p>In Java 1.5 you can just do</p>\n\n<pre><code>for (int i: myArray) {\n ...\n}\n</code></pre>\n\n<p>so for the array case you don't need to worry.</p>\n" }, { "answer_id": 182614, "author": "Omar Kooheji", "author_id": 20400, "author_profile": "https://Stackoverflow.com/users/20400", "pm_score": 5, "selected": false, "text": "<p>I always use &lt; array.length because it's easier to read than &lt;= array.length-1.</p>\n\n<p>also having &lt; 7 and given that you know it's starting with a 0 index it should be intuitive that the number is the number of iterations.</p>\n" }, { "answer_id": 182616, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 2, "selected": false, "text": "<p>I don't think there is a performance difference. The second form is definitely more readable though, you don't have to mentally subtract one to find the last iteration number.</p>\n\n<p><strong>EDIT:</strong> I see others disagree. For me personally, I like to see the actual index numbers in the loop structure. Maybe it's because it's more reminiscent of Perl's <code>0..6</code> syntax, which I know is equivalent to <code>(0,1,2,3,4,5,6)</code>. If I see a 7, I have to check the operator next to it to see that, in fact, index 7 is never reached.</p>\n" }, { "answer_id": 182617, "author": "Dominic Rodger", "author_id": 20972, "author_profile": "https://Stackoverflow.com/users/20972", "pm_score": 3, "selected": false, "text": "<p>I prefer:</p>\n\n<pre><code>for (int i = 0; i &lt; 7; i++)\n</code></pre>\n\n<p>I think that translates more readily to \"iterating through a loop 7 times\".</p>\n\n<p>I'm not sure about the performance implications - I suspect any differences would get compiled away.</p>\n" }, { "answer_id": 182620, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 9, "selected": true, "text": "<p>The first is more <a href=\"http://en.wiktionary.org/wiki/idiomatic\" rel=\"noreferrer\">idiomatic</a>. In particular, it indicates (in a 0-based sense) the number of iterations. When using something 1-based (e.g. JDBC, IIRC) I might be tempted to use &lt;=. So:</p>\n\n<pre><code>for (int i=0; i &lt; count; i++) // For 0-based APIs\n\nfor (int i=1; i &lt;= count; i++) // For 1-based APIs\n</code></pre>\n\n<p>I would expect the performance difference to be insignificantly small in real-world code.</p>\n" }, { "answer_id": 182623, "author": "seanyboy", "author_id": 1726, "author_profile": "https://Stackoverflow.com/users/1726", "pm_score": 0, "selected": false, "text": "<p>I think either are OK, but when you've chosen, stick to one or the other. If you're used to using &lt;=, then try not to use &lt; and vice versa. </p>\n\n<p>I prefer &lt;=, but in situations where you're working with indexes which start at zero, I'd probably try and use &lt;. It's all personal preference though. </p>\n" }, { "answer_id": 182624, "author": "erlando", "author_id": 4192, "author_profile": "https://Stackoverflow.com/users/4192", "pm_score": 4, "selected": false, "text": "<p>Seen from an optimizing viewpoint it doesn't matter.</p>\n\n<p>Seen from a code style viewpoint I prefer &lt; . Reason:</p>\n\n<pre><code>for ( int i = 0; i &lt; array.size(); i++ )\n</code></pre>\n\n<p>is so much more readable than</p>\n\n<pre><code>for ( int i = 0; i &lt;= array.size() -1; i++ )\n</code></pre>\n\n<p>also &lt; gives you the number of iterations straight away.</p>\n\n<p>Another vote for &lt; is that you might prevent a lot of accidental off-by-one mistakes.</p>\n" }, { "answer_id": 182625, "author": "tloach", "author_id": 14092, "author_profile": "https://Stackoverflow.com/users/14092", "pm_score": 2, "selected": false, "text": "<p>I agree with the crowd saying that the 7 makes sense in this case, but I would add that in the case where the 6 is important, say you want to make clear you're only acting on objects up to the 6th index, then the &lt;= is better since it makes the 6 easier to see.</p>\n" }, { "answer_id": 182628, "author": "casademora", "author_id": 5619, "author_profile": "https://Stackoverflow.com/users/5619", "pm_score": 2, "selected": false, "text": "<p>Way back in college, I remember something about these two operations being similar in compute time on the CPU. Of course, we're talking down at the assembly level.</p>\n\n<p>However, if you're talking C# or Java, I really don't think one is going to be a speed boost over the other, The few nanoseconds you gain are most likely not worth any confusion you introduce.</p>\n\n<p>Personally, I would author the code that makes sense from a business implementation standpoint, and make sure it's easy to read.</p>\n" }, { "answer_id": 182647, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 2, "selected": false, "text": "<p>I'd say use the \"&lt; 7\" version because that's what the majority of people will read - so if people are skim reading your code, they might interpret it wrongly.</p>\n\n<p>I wouldn't worry about whether \"&lt;\" is quicker than \"&lt;=\", just go for readability.</p>\n\n<p>If you do want to go for a speed increase, consider the following:</p>\n\n<pre><code>for (int i = 0; i &lt; this-&gt;GetCount(); i++)\n{\n // Do something\n}\n</code></pre>\n\n<p>To increase performance you can slightly rearrange it to:</p>\n\n<pre><code>const int count = this-&gt;GetCount();\nfor (int i = 0; i &lt; count; ++i)\n{\n // Do something\n}\n</code></pre>\n\n<p>Notice the removal of GetCount() from the loop (because that will be queried in every loop) and the change of \"i++\" to \"++i\".</p>\n" }, { "answer_id": 182661, "author": "Henry B", "author_id": 6414, "author_profile": "https://Stackoverflow.com/users/6414", "pm_score": 0, "selected": false, "text": "<p>Strictly from a logical point of view, you have to think that <code>&lt; count</code> would be more efficient than <code>&lt;= count</code> for the exact reason that <code>&lt;=</code> will be testing for equality as well.</p>\n" }, { "answer_id": 182684, "author": "Rob Allen", "author_id": 149, "author_profile": "https://Stackoverflow.com/users/149", "pm_score": 2, "selected": false, "text": "<p>As a slight aside, when looping through an array or other collection in .Net, I find</p>\n\n<pre><code>foreach (string item in myarray)\n{\n System.Console.WriteLine(item);\n}\n</code></pre>\n\n<p>to be more readable than the numeric for loop. This of course assumes that the actual counter Int itself isn't used in the loop code. I do not know if there is a performance change.</p>\n" }, { "answer_id": 182700, "author": "DJClayworth", "author_id": 19276, "author_profile": "https://Stackoverflow.com/users/19276", "pm_score": 1, "selected": false, "text": "<p>There are many good reasons for writing i&lt;7. Having the number 7 in a loop that iterates 7 times is good. The performance is effectively identical. Almost everybody writes i&lt;7. If you're writing for readability, use the form that everyone will recognise instantly.</p>\n" }, { "answer_id": 182754, "author": "Martin Brown", "author_id": 20553, "author_profile": "https://Stackoverflow.com/users/20553", "pm_score": 6, "selected": false, "text": "<p>I remember from my days when we did 8086 Assembly at college it was more performant to do:</p>\n\n<pre><code>for (int i = 6; i &gt; -1; i--)\n</code></pre>\n\n<p>as there was a <a href=\"http://tic01.tic.ec-lyon.fr/~muller/trotek/cours/8086/JNS.html.en\" rel=\"noreferrer\">JNS</a> operation that means Jump if No Sign. Using this meant that there was no memory lookup after each cycle to get the comparison value and no compare either. These days most compilers optimize register usage so the memory thing is no longer important, but you still get an un-required compare.</p>\n\n<p>By the way putting 7 or 6 in your loop is introducing a \"<a href=\"http://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"noreferrer\">magic number</a>\". For better readability you should use a constant with an Intent Revealing Name. Like this:</p>\n\n<pre><code>const int NUMBER_OF_CARS = 7;\nfor (int i = 0; i &lt; NUMBER_OF_CARS; i++)\n</code></pre>\n\n<p>EDIT: People aren’t getting the assembly thing so a fuller example is obviously required:</p>\n\n<p>If we do for (i = 0; i &lt;= 10; i++) you need to do this:</p>\n\n<pre><code> mov esi, 0\nloopStartLabel:\n ; Do some stuff\n inc esi\n ; Note cmp command on next line\n cmp esi, 10\n jle exitLoopLabel\n jmp loopStartLabel\nexitLoopLabel:\n</code></pre>\n\n<p>If we do for (int i = 10; i > -1; i--) then you can get away with this:</p>\n\n<pre><code> mov esi, 10\nloopStartLabel:\n ; Do some stuff\n dec esi\n ; Note no cmp command on next line\n jns exitLoopLabel\n jmp loopStartLabel\nexitLoopLabel:\n</code></pre>\n\n<p>I just checked and Microsoft's C++ compiler does not do this optimization, but it does if you do:</p>\n\n<pre><code>for (int i = 10; i &gt;= 0; i--) \n</code></pre>\n\n<p>So the moral is if you are using Microsoft C++†, and ascending or descending makes no difference, to get a quick loop you should use:</p>\n\n<pre><code>for (int i = 10; i &gt;= 0; i--)\n</code></pre>\n\n<p>rather than either of these:</p>\n\n<pre><code>for (int i = 10; i &gt; -1; i--)\nfor (int i = 0; i &lt;= 10; i++)\n</code></pre>\n\n<p>But frankly getting the readability of \"for (int i = 0; i &lt;= 10; i++)\" is normally far more important than missing one processor command.</p>\n\n<p>† Other compilers may do different things.</p>\n" }, { "answer_id": 182782, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 1, "selected": false, "text": "<p>I have always preferred:</p>\n\n<pre><code>for ( int count = 7 ; count &gt; 0 ; -- count )\n</code></pre>\n" }, { "answer_id": 182800, "author": "akalenuk", "author_id": 25459, "author_profile": "https://Stackoverflow.com/users/25459", "pm_score": 0, "selected": false, "text": "<p>It should not be difference in perfomance at least with the x86 compilers. JL and JLE works the same time, as soon as I know. And as for redability, using \"&lt;7\" for an array of seven elements makes sense.</p>\n" }, { "answer_id": 182844, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": 0, "selected": false, "text": "<p>I follow the first method as that idiom is repeated frequently.</p>\n\n<p>for (int index = 0; index &lt; array.length; i++)</p>\n\n<p>String s = oldString.substring(0, numChars);</p>\n\n<p>etc. </p>\n\n<p>I'm used to the upper bound being excluded, and would prefer to keep it that way unless there is good reason to change it. (example -- 1 based indexing)</p>\n" }, { "answer_id": 182857, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 0, "selected": false, "text": "<p>Go for readability first, optimize later (although, quite honestly, I can't imagine any difference that would be noticeable).</p>\n\n<p>Be aware that the 0 -> K form is a C idiom carried over into C# by having arrays be 0 based. Follow the idiom and don't violate the principal of least astonishment.</p>\n" }, { "answer_id": 182881, "author": "Brian", "author_id": 18192, "author_profile": "https://Stackoverflow.com/users/18192", "pm_score": 1, "selected": false, "text": "<p>You could also use <code>!=</code> instead. That way, you'll get an infinite loop if you make an error in initialization, causing the error to be noticed earlier and any problems it causes to be limitted to getting stuck in the loop (rather than having a problem much later and not finding it).</p>\n" }, { "answer_id": 182972, "author": "Carra", "author_id": 21679, "author_profile": "https://Stackoverflow.com/users/21679", "pm_score": 2, "selected": false, "text": "<p>First, don't use 6 or 7.</p>\n\n<p>Better to use:</p>\n\n<pre><code>int numberOfDays = 7;\nfor (int day = 0; day &lt; numberOfDays ; day++){\n\n}\n</code></pre>\n\n<p>In this case it's better than using</p>\n\n<pre><code>for (int day = 0; day &lt;= numberOfDays - 1; day++){\n\n}\n</code></pre>\n\n<p>Even better (Java / C#):</p>\n\n<pre><code>for(int day = 0; day &lt; dayArray.Length; i++){\n\n}\n</code></pre>\n\n<p>And even better (C#)</p>\n\n<pre><code>foreach (int day in days){// day : days in Java\n\n}\n</code></pre>\n\n<p>The reverse loop is indeed faster but since it's harder to read (if not by you by other programmers), it's better to avoid in. Especially in C#, Java...</p>\n" }, { "answer_id": 183089, "author": "JohnMcG", "author_id": 1674, "author_profile": "https://Stackoverflow.com/users/1674", "pm_score": 1, "selected": false, "text": "<p>Making a habit of using &lt; will make it consistent for both you and the reader when you are iterating through an array. It will be simpler for everyone to have a standard convention. And if you're using a language with 0-based arrays, then &lt; is the convention.</p>\n\n<p>This almost certainly matters more than any performance difference between &lt; and &lt;=. Aim for functionality and readability first, then optimize.</p>\n\n<p>Another note is that it would be better to be in the habit of doing ++i rather than i++, since fetch and increment requires a temporary and increment and fetch does not. For integers, your compiler will probably optimize the temporary away, but if your iterating type is more complex, it might not be able to.</p>\n" }, { "answer_id": 183184, "author": "Krakkos", "author_id": 15533, "author_profile": "https://Stackoverflow.com/users/15533", "pm_score": 1, "selected": false, "text": "<p>Don't use magic numbers.</p>\n\n<p>Why is it 7? ( or 6 for that matter).</p>\n\n<p>use the correct symbol for the number you want to use...</p>\n\n<p>In which case I think it is better to use</p>\n\n<pre><code>for ( int i = 0; i &lt; array.size(); i++ )\n</code></pre>\n" }, { "answer_id": 183216, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>In C++, I prefer using <code>!=</code>, which is usable with all STL containers. Not all STL container iterators are less-than comparable.</p>\n" }, { "answer_id": 183266, "author": "Jeff B", "author_id": 25879, "author_profile": "https://Stackoverflow.com/users/25879", "pm_score": 1, "selected": false, "text": "<p>The '&lt;' and '&lt;=' operators are exactly the same performance cost.</p>\n\n<p>The '&lt;' operator is a standard and easier to read in a zero-based loop.</p>\n\n<p>Using ++i instead of i++ improves performance in C++, but not in C# - I don't know about Java.</p>\n" }, { "answer_id": 183373, "author": "Ryan Rodemoyer", "author_id": 1444511, "author_profile": "https://Stackoverflow.com/users/1444511", "pm_score": 0, "selected": false, "text": "<p>I prefer this:</p>\n\n<pre><code>for (int i = 0; i &lt; 7; i++)\n</code></pre>\n\n<p>However (this is merely a thought), the readability of it might have to do whether or not arrays are 0-based (C#, Java) or 1-based (VB .NET). I say this because when you work with 0-based arrays, you get in a mindset that 0-6 would run 7 times. I think 0-6 is more intuitive than 1-7. Then again, I come from a C++, Java, C# background.</p>\n" }, { "answer_id": 183384, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 0, "selected": false, "text": "<p>For some languages/technologies like .NET using .Size or .Length or size()/length() is a bad idea is it accesses that property each time it iterates, so assigned it to a variable has a slightly less performance hit.</p>\n" }, { "answer_id": 183467, "author": "David Wees", "author_id": 22479, "author_profile": "https://Stackoverflow.com/users/22479", "pm_score": 1, "selected": false, "text": "<p>As people have observed, there is no difference in either of the two alternatives you mentioned. Just to confirm this, I did some simple benchmarking in JavaScript.</p>\n\n<p>You can see the results <a href=\"http://unitorganizer.com/javascript/loops/\" rel=\"nofollow noreferrer\">here</a>. What is not clear from this is that if I swap the position of the 1st and 2nd tests, the results for those 2 tests swap, this is clearly a memory issue. However the 3rd test, one where I reverse the order of the iteration is clearly faster.</p>\n" }, { "answer_id": 183539, "author": "Jeff Mc", "author_id": 25521, "author_profile": "https://Stackoverflow.com/users/25521", "pm_score": 3, "selected": false, "text": "<p>@Chris, Your statement about .Length being costly in .NET is actually untrue and in the case of simple types the exact opposite.</p>\n\n<pre><code>int len = somearray.Length;\nfor(i = 0; i &lt; len; i++)\n{\n somearray[i].something();\n}\n</code></pre>\n\n<p>is actually slower than</p>\n\n<pre><code>for(i = 0; i &lt; somearray.Length; i++)\n{\n somearray[i].something();\n}\n</code></pre>\n\n<p>The later is a case that is optimized by the runtime. Since the runtime can guarantee i is a valid index into the array no bounds checks are done. In the former, the runtime can't guarantee that i wasn't modified prior to the loop and forces bounds checks on the array for every index lookup.</p>\n" }, { "answer_id": 183726, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 1, "selected": false, "text": "<p>As everybody says, it is customary to use 0-indexed iterators even for things outside of arrays. If everything begins at <code>0</code> and ends at <code>n-1</code>, and lower-bounds are always <code>&lt;=</code> and upper-bounds are always <code>&lt;</code>, there's that much less thinking that you have to do when reviewing the code.</p>\n" }, { "answer_id": 184166, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The results doesn't make sense.</p>\n\n<p>From a hardware point of view, &lt;= with a loopNuumber-1 will introduce one extra calculation to do loopNumber-1 per iteration. So I assume that &lt; will take less time, if not same amount of time than &lt;=</p>\n" }, { "answer_id": 184201, "author": "Ryan Delucchi", "author_id": 9931, "author_profile": "https://Stackoverflow.com/users/9931", "pm_score": 2, "selected": false, "text": "<p>This falls directly under the category of <a href=\"http://www.joelonsoftware.com/articles/Wrong.html\" rel=\"nofollow noreferrer\">\"Making Wrong Code Look Wrong\"</a>. </p>\n\n<p>In zero-based indexing languages, such as Java or C# people are accustomed to variations on the <code>index &lt; count</code> condition. Thus, leveraging this defacto convention would make off-by-one errors more obvious.</p>\n\n<p>Regarding performance: any good compiler worth its memory footprint should render such as a non-issue.</p>\n" }, { "answer_id": 184974, "author": "Martijn", "author_id": 17439, "author_profile": "https://Stackoverflow.com/users/17439", "pm_score": 2, "selected": false, "text": "<p>Edsger Dijkstra <a href=\"http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html\" rel=\"nofollow noreferrer\">wrote an article</a> on this back in 1982 where he argues for lower &lt;= i &lt; upper:</p>\n\n<blockquote>\n <p>There is a smallest natural number. Exclusion of the lower bound —as in b) and d)— forces for a subsequence starting at the smallest natural number the lower bound as mentioned into the realm of the unnatural numbers. That is ugly, so for the lower bound we prefer the ≤ as in a) and c). Consider now the subsequences starting at the smallest natural number: inclusion of the upper bound would then force the latter to be unnatural by the time the sequence has shrunk to the empty one. That is ugly, so for the upper bound we prefer &lt; as in a) and d). We conclude that convention a) is to be preferred.</p>\n</blockquote>\n" }, { "answer_id": 241310, "author": "cciotti", "author_id": 16834, "author_profile": "https://Stackoverflow.com/users/16834", "pm_score": 0, "selected": false, "text": "<p>Premature optimization is the root of all evil. Go with readability unless there is a really good reason to worry about <code>&lt;</code> over <code>&lt;=</code>.</p>\n" }, { "answer_id": 263686, "author": "Mike Dunlavey", "author_id": 23771, "author_profile": "https://Stackoverflow.com/users/23771", "pm_score": 0, "selected": false, "text": "<p>No speed difference, but &lt; is more likely to be correct in a language with 0-based arrays. Also, if you want to iterate down instead of up, you can say:</p>\n\n<pre><code>for (i = 7; --i &gt;= 0; ) ...\n</code></pre>\n" }, { "answer_id": 859177, "author": "Cam Wolff", "author_id": 98487, "author_profile": "https://Stackoverflow.com/users/98487", "pm_score": 0, "selected": false, "text": "<p>I would argue it should be &lt;. </p>\n\n<p>Why use many words when a few will do. One test is easier to understand then two. Consquently, it is easier to unit test and modify going forward. </p>\n\n<p>Is the difference small? Yes. But why add any complexity when it is not warranted. </p>\n\n<p>Finally, you are not reliant on any optimizer or implementation of an interpreter when the code is optimized to begin with. To quote Einstein, \"keep it as simple as possible but no simpler\".</p>\n" }, { "answer_id": 2041240, "author": "Pavel Radzivilovsky", "author_id": 73656, "author_profile": "https://Stackoverflow.com/users/73656", "pm_score": 1, "selected": false, "text": "<p>Great question. My answer: use type A ('&lt;')</p>\n\n<ul>\n<li>You clearly see how many iterations you have (7). </li>\n<li>The difference between two endpoints is the width of the range</li>\n<li>Less characters makes it more readable</li>\n<li>You more often have the total number of elements <code>i &lt; strlen(s)</code> rather than the <em>index of the last element</em> so uniformity is important.</li>\n</ul>\n\n<p>Another problem is with this whole construct. <code>i</code> appears <strong>3 times</strong> in it, so it can be mistyped. The for-loop construct says <strong>how to do</strong> instead of <strong>what to do</strong>. I suggest adopting this:</p>\n\n<p><code>BOOST_FOREACH(i, IntegerInterval(0,7))</code></p>\n\n<p>This is more clear, compiles to exaclty the same asm instructions, etc. Ask me for the code of IntegerInterval if you like. </p>\n" }, { "answer_id": 3765406, "author": "Nick Westgate", "author_id": 313445, "author_profile": "https://Stackoverflow.com/users/313445", "pm_score": 1, "selected": false, "text": "<p>So many answers ... but I believe I have something to add.</p>\n\n<p>My preference is for the literal numbers to clearly show <strong>what values \"i\" will take in the loop</strong>. So in the case of iterating though a zero-based array:</p>\n\n<p><code>for (int i = 0; i &lt;= array.Length - 1; ++i)</code></p>\n\n<p>And if you're just looping, not iterating through an array, counting from 1 to 7 is pretty intuitive:</p>\n\n<p><code>for (int i = 1; i &lt;= 7; ++i)</code></p>\n\n<p>Readability trumps performance until you profile it, as you probably don't know what the compiler or runtime is going to do with your code until then.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1533/" ]
If you had to iterate through a loop 7 times, would you use: ``` for (int i = 0; i < 7; i++) ``` or: ``` for (int i = 0; i <= 6; i++) ``` There are two considerations: * performance * readability For performance I'm assuming Java or C#. Does it matter if "less than" or "less than or equal to" is used? If you have insight for a different language, please indicate which. For readability I'm assuming 0-based arrays. **UPD:** My mention of 0-based arrays may have confused things. I'm not talking about iterating through array elements. Just a general loop. There is a good point below about using a constant to which would explain what this magic number is. So if I had "`int NUMBER_OF_THINGS = 7`" then "`i <= NUMBER_OF_THINGS - 1`" would look weird, wouldn't it.
The first is more [idiomatic](http://en.wiktionary.org/wiki/idiomatic). In particular, it indicates (in a 0-based sense) the number of iterations. When using something 1-based (e.g. JDBC, IIRC) I might be tempted to use <=. So: ``` for (int i=0; i < count; i++) // For 0-based APIs for (int i=1; i <= count; i++) // For 1-based APIs ``` I would expect the performance difference to be insignificantly small in real-world code.
182,602
<p>I have a BulletedList in asp.net that is set to DisplayMode="LinkButton". I would like to trigger the first "bullet" from a javascript, can this be done? And if so, how?</p>
[ { "answer_id": 183374, "author": "Alex Gyoshev", "author_id": 25427, "author_profile": "https://Stackoverflow.com/users/25427", "pm_score": 3, "selected": true, "text": "<p>Say you have the BulletedList as</p>\n\n<pre><code>&lt;asp:BulletedList runat=\"server\" ID=\"MyLovelyBulletedList\" DisplayMode=\"LinkButton\"&gt;\n &lt;asp:ListItem Text=\"My Lovely Text 1\" /&gt;\n &lt;asp:ListItem Text=\"My Lovely Text 2\" /&gt;\n&lt;/asp:BulletedList&gt;\n</code></pre>\n\n<p>... then you can fire the \"onclick\" event like this (cross-browser):</p>\n\n<pre><code>var links = document.getElementById('&lt;%= MyLovelyBulletedList.ClientID %&gt;').getElementsByTagName('a');\n\nvar targetLink = links[0];\n\nif (targetLink.fireEvent)\n{\n // IE\n targetLink.fireEvent(\"onclick\");\n}\nelse if (targetLink.dispatchEvent)\n{\n // W3C\n var evt = document.createEvent(\"MouseEvents\");\n\n evt.initMouseEvent(\"click\", true, true, window,\n 0, 0, 0, 0, 0, false, false, false, false, 0, null);\n\n targetLink.dispatchEvent(evt);\n}\n</code></pre>\n" }, { "answer_id": 185751, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>Similar to what Alexander indicated except that you could use jQuery to fire the event and depend on their cross-browser support rather than maintain it on your own.</p>\n\n<pre><code>$('#&lt;%= MyLovelyBulletedList.ClientID %&gt;')\n .contents()\n .find('a:first')\n .trigger('click');\n</code></pre>\n" }, { "answer_id": 515836, "author": "Cros", "author_id": 1523, "author_profile": "https://Stackoverflow.com/users/1523", "pm_score": 1, "selected": false, "text": "<p>After a lot of testing it seems the only dependent way to do this is by manually firing the __doPostBack-script like so:</p>\n\n<pre><code>__doPostBack('MyLovelyBulletedList', '0');\n</code></pre>\n\n<p>as suggested by <a href=\"https://stackoverflow.com/users/25427/alexander-gyoshev\">Alexander Gyoshev</a></p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1523/" ]
I have a BulletedList in asp.net that is set to DisplayMode="LinkButton". I would like to trigger the first "bullet" from a javascript, can this be done? And if so, how?
Say you have the BulletedList as ``` <asp:BulletedList runat="server" ID="MyLovelyBulletedList" DisplayMode="LinkButton"> <asp:ListItem Text="My Lovely Text 1" /> <asp:ListItem Text="My Lovely Text 2" /> </asp:BulletedList> ``` ... then you can fire the "onclick" event like this (cross-browser): ``` var links = document.getElementById('<%= MyLovelyBulletedList.ClientID %>').getElementsByTagName('a'); var targetLink = links[0]; if (targetLink.fireEvent) { // IE targetLink.fireEvent("onclick"); } else if (targetLink.dispatchEvent) { // W3C var evt = document.createEvent("MouseEvents"); evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); targetLink.dispatchEvent(evt); } ```
182,615
<p>When reading my RSS feed with the Thunderbird feed reader, some entries are duplicated. <a href="https://en.wikipedia.org/wiki/Google_Reader" rel="nofollow noreferrer">Google Reader</a> does not have the same problem.</p> <p>Here is the faulty feed: <a href="http://plcoder.net/rss.php?rss=Blog" rel="nofollow noreferrer">http://plcoder.net/rss.php?rss=Blog</a></p> <p>There is a problem, but where?</p> <p>I added a <a href="https://en.wikipedia.org/wiki/Globally_unique_identifier" rel="nofollow noreferrer">GUID</a>, but the problem remains. Other feeds do not duplicate like mine, so I will do rework on this module and replace this old good code.</p> <p>Conclusion: I completely reworked the RSS generator code, and it's OK. I think I was using a very old version of <a href="https://en.wikipedia.org/wiki/Resource_Description_Framework" rel="nofollow noreferrer">RDF</a>.</p>
[ { "answer_id": 182646, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 4, "selected": true, "text": "<p>Try adding a <code>&lt;guid&gt;</code> tag to each item, giving it a permalink. i.e.:</p>\n\n<pre><code>&lt;item rdf:about=\"http://plcoder.net/?doc=2134&amp;amp;amp;titre=mon-pc-se-la-pete\"&gt;\n &lt;link&gt;http://plcoder.net/?doc=2134&amp;amp;amp;titre=mon-pc-se-la-pete&lt;/link&gt;\n &lt;guid&gt;http://plcoder.net/?doc=2134&amp;amp;amp;titre=mon-pc-se-la-pete&lt;/guid&gt;\n ...\n&lt;/item&gt;\n</code></pre>\n\n<p>Without a GUID, if any of the content in the post changes, your RSS aggregator might think that it is a new post. With the GUID, even if the content of that item changes, your RSS aggregator <em>should</em> just update the post, instead of treating it as a new item.</p>\n" }, { "answer_id": 182768, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 1, "selected": false, "text": "<p>I have experienced these issues with some of my own feeds. I started off with a list of entries like this:</p>\n<pre><code>Item A\nItem B\nItem C\n</code></pre>\n<p>The client downloads them and everything is fine. Then I add a new item, so the feed reads as:</p>\n<pre><code>Item D\nItem A\nItem B\n</code></pre>\n<p>D shows up in the reader.</p>\n<p>But then I decide I don't want that item, so the list reverts to:</p>\n<pre><code>Item A\nItem B\nItem C\n</code></pre>\n<p>When Thunderbird reads this, it'll count C as a new item. I <em><strong>am</strong></em> using a GUID element, so I doubt that's the problem. I think it's got more to do with Thunderbird's parser not taking older elements into consideration.</p>\n<p>The long-winded workaround is to &quot;remember&quot; what items you've already published and have since been pushed off the end of the list by new items. You'll basically need to keep a current list of items in the feed and when you delete items from it, cut it short until there are new items to replace it.</p>\n" }, { "answer_id": 755325, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>At least with Thunderbird 2.0.0.21, the problem is that Thunderbird doesn't seem to respect GUID tags, but it <em>does</em> respect the <em>channel's</em> pubDate-tag. Thus if pubDate is more recent than with the last reading, Thunderbird will read <em>all</em> entries (it seems).</p>\n<p>I don't know what would happen if the channel's pubDate-tag is missing though...</p>\n" }, { "answer_id": 48707313, "author": "user598527", "author_id": 6404709, "author_profile": "https://Stackoverflow.com/users/6404709", "pm_score": 1, "selected": false, "text": "<p>This is explained in <a href=\"https://support.mozilla.org/en-US/kb/how-subscribe-news-feeds-and-blogs\" rel=\"nofollow noreferrer\">Thunderbird's documentation</a> (under &quot;Troubleshooting FAQ&quot;):</p>\n<blockquote>\n<p><strong>Q: Why are feed messages sometimes duplicated?</strong></p>\n<p>A: Feed messages with identical content, but different unique ids, are\nnot detected as duplicates. See <a href=\"http://forums.mozillazine.org/viewtopic.php?p=13360829#p13360829\" rel=\"nofollow noreferrer\">this post</a> for many more details.</p>\n</blockquote>\n<p>The linked post for reference:</p>\n<blockquote>\n<ol>\n<li><a href=\"https://en.wikipedia.org/wiki/Atom_(Web_standard)\" rel=\"nofollow noreferrer\">Atom</a> feeds (mandatory) have a unique ID; RSS feeds (not mandatory) usually have a unique GUID. For RSS feeds without a GUID, an attempt\nis made to create a unique ID from mandatory parts of the feed item.</li>\n<li>All downloaded feed messages have a record with this ID stored in feeditems.rdf and exist there as long as they exist in the publisher's\nfile, with that ID. If the publisher removes a message with the ID\nfrom their file, after 24 hours the feeditems.rdf cache is also purged\n(on get messages biff).</li>\n<li>If a publisher reuses an ID after it has been purged, you will get a duplicate (if the content is identical). This is an abuse of the intent\nbehind unique IDs and is the publisher's error.</li>\n<li>If a publisher reuses an ID before it is purged, and the content is different, you will not see the new content, as it will be treated as\na duplicate. Thunderbird does not use the &lt;updated&gt; tag currently and\nits misuse by publishers may make it difficult to implement.</li>\n<li>If you view the source (<kbd>Ctrl</kbd> + <kbd>U</kbd>) of two apparent duplicates, you will note the Message-Id header. If two apparent duplicates have different\nMessage-Id values, then they are not duplicates regardless of potential\nidentical content. Thunderbird does not distinguish duplicate content.</li>\n</ol>\n<p>If you want extreme debugging, change the Feeds.logging.console preference setting\nto debug or trace and restart, to see what happens during feed\nprocessing.</p>\n<p>If you unsubscribe a feed URL, this will clear the <em>feeditems.rdf</em> cache\nfor that feed. If you subsequently resubscribe you will get duplicates of\nall current items in the publisher's file that also exist in your feed\nfolder.</p>\n<p>Compaction has no effect on feed processing; it just removes marked\nfor deletion items from the file. If you delete a folder/move it to\ntrash, it is unsubscribed. Starting with Thunderbird 29, if you drag/drop a\nfolder from one feed account to another feed account, the subscription\nis retained (but not feeditems). For very old profiles/feed accounts\n(pre Thunderbird 17), it can be a good idea to create a new feed account and\ndrag folders there (Thunderbird 29 and up), as a fresh <em>feeds.rdf</em> database is\ncreated; the penalty is a one-time duplicate possibility.</p>\n</blockquote>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8404/" ]
When reading my RSS feed with the Thunderbird feed reader, some entries are duplicated. [Google Reader](https://en.wikipedia.org/wiki/Google_Reader) does not have the same problem. Here is the faulty feed: <http://plcoder.net/rss.php?rss=Blog> There is a problem, but where? I added a [GUID](https://en.wikipedia.org/wiki/Globally_unique_identifier), but the problem remains. Other feeds do not duplicate like mine, so I will do rework on this module and replace this old good code. Conclusion: I completely reworked the RSS generator code, and it's OK. I think I was using a very old version of [RDF](https://en.wikipedia.org/wiki/Resource_Description_Framework).
Try adding a `<guid>` tag to each item, giving it a permalink. i.e.: ``` <item rdf:about="http://plcoder.net/?doc=2134&amp;amp;titre=mon-pc-se-la-pete"> <link>http://plcoder.net/?doc=2134&amp;amp;titre=mon-pc-se-la-pete</link> <guid>http://plcoder.net/?doc=2134&amp;amp;titre=mon-pc-se-la-pete</guid> ... </item> ``` Without a GUID, if any of the content in the post changes, your RSS aggregator might think that it is a new post. With the GUID, even if the content of that item changes, your RSS aggregator *should* just update the post, instead of treating it as a new item.