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
265,750
<p>I have a xml build of</p> <pre><code>&lt;elig&gt; &lt;subscriber code="1234"/&gt; &lt;date to="12/30/2004" from="12/31/2004"/&gt; &lt;person name="bob" ID="654321"/&gt; &lt;dog type="labrador" color="white"/&gt; &lt;location name="hawaii" islandCode="01"/&gt; &lt;/subscriber&gt; &lt;/elig&gt; </code></pre> <p>In XSL I have:</p> <pre><code>&lt;xsl:template match="subscriber"&gt; &lt;xsl:for-each select="date"&gt; &lt;xsl:apply-templates match="person" /&gt; &lt;xsl:apply-templates match="location" /&gt; &lt;xsl:apply-templates match="dog" /&gt; &lt;/xsl:for-each&gt; &lt;/xsl:template&gt; </code></pre> <p>The problem I have is that I need the location block in between the person and the dog block. I have tried ../ and it does not work. I simplified this majorly but the point comes across. I can't seem to remember what I need to place in front of location to get it to work. Thanks.</p>
[ { "answer_id": 265828, "author": "mkoeller", "author_id": 33433, "author_profile": "https://Stackoverflow.com/users/33433", "pm_score": 1, "selected": false, "text": "<p>I modified one typo in your example XML:</p>\n\n<pre><code>&lt;elig&gt;\n &lt;subscriber code=\"1234\"&gt;\n &lt;date to=\"12/30/2004\" from=\"12/31/2004\"/&gt;\n &lt;person name=\"bob\" ID=\"654321\"/&gt;\n &lt;dog type=\"labrador\" color=\"white\"/&gt;\n &lt;location name=\"hawaii\" islandCode=\"01\"/&gt;\n &lt;/subscriber&gt;\n&lt;/elig&gt;\n</code></pre>\n\n<p>And using this stylesheet everything works just fine:</p>\n\n<pre><code>&lt;xsl:template match=\"subscriber\"&gt;\n &lt;xsl:for-each select=\"date\"&gt;\n &lt;xsl:apply-templates select=\"../person\" /&gt;\n &lt;xsl:apply-templates select=\"../location\" /&gt;\n &lt;xsl:apply-templates select=\"../dog\" /&gt;\n &lt;/xsl:for-each&gt;\n&lt;/xsl:template&gt;\n\n&lt;xsl:template match=\"person\"&gt;person&lt;/xsl:template&gt;\n&lt;xsl:template match=\"location\"&gt;location&lt;/xsl:template&gt;\n&lt;xsl:template match=\"dog\"&gt;dog&lt;/xsl:template&gt;\n</code></pre>\n\n<p>Output is:</p>\n\n<pre><code>personlocationdog\n</code></pre>\n" }, { "answer_id": 266090, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 2, "selected": true, "text": "<p>First of all your XML is still not well-formed and I actually cannot catch why you're looping over the <code>&lt;date/&gt;</code> tags - there is only one <code>&lt;date/&gt;</code> tag inside <code>&lt;subscriber/&gt;</code> (assuming that the first <code>&lt;subscriber/&gt;</code> should not be self-closed).</p>\n\n<p>When using XPath you alway have to think about the context in which the XPatch is called. The following should do it (when my assumption about your data structure is correct):</p>\n\n<pre><code>&lt;xsl:template match=\"subscriber\"&gt;\n &lt;xsl:for-each select=\"date\"&gt; \n &lt;!-- from here on we're in the context of the date-tag --&gt;\n &lt;xsl:apply-templates match=\"../person\" /&gt;\n &lt;xsl:apply-templates match=\"../location\" /&gt;\n &lt;xsl:apply-templates match=\"../dog\" /&gt;\n &lt;/xsl:for-each&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n" }, { "answer_id": 1254057, "author": "Alderath", "author_id": 151344, "author_profile": "https://Stackoverflow.com/users/151344", "pm_score": 0, "selected": false, "text": "<p>In this case, isn't it more logical to move the apply-template calls outside the for-each loop? Since the person, location and dog elements are children of the subscriber, they should be processed within the scope of the subscriber, instead of in the scope of the date.</p>\n\n<p>I.e.:</p>\n\n<pre><code>&lt;xsl:template match=\"subscriber\"&gt;\n &lt;xsl:for-each select=\"date\"&gt;\n &lt;!-- Perform the processing of the date tags here--&gt;\n &lt;/xsl:for-each&gt;\n\n &lt;xsl:apply-templates match=\"person\" /&gt;\n &lt;xsl:apply-templates match=\"location\" /&gt;\n &lt;xsl:apply-templates match=\"dog\" /&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n" }, { "answer_id": 1442150, "author": "Laxmikanth Samudrala", "author_id": 144414, "author_profile": "https://Stackoverflow.com/users/144414", "pm_score": 1, "selected": false, "text": "<pre><code>&lt;xsl:template match=\"subscriber\"&gt;\n &lt;xsl:apply-templates match=\"date\" /&gt;\n&lt;/xsl:template&gt;\n\n&lt;xsl:template match=\"date\"&gt;\n &lt;xsl:apply-templates match=\"../person\" /&gt;\n &lt;xsl:apply-templates match=\"../location\" /&gt;\n &lt;xsl:apply-templates match=\"../dog\" /&gt;\n&lt;/xsl:template&gt;\n\n instead of xsl:for-each on date better practice is having a template match for date.\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16354/" ]
I have a xml build of ``` <elig> <subscriber code="1234"/> <date to="12/30/2004" from="12/31/2004"/> <person name="bob" ID="654321"/> <dog type="labrador" color="white"/> <location name="hawaii" islandCode="01"/> </subscriber> </elig> ``` In XSL I have: ``` <xsl:template match="subscriber"> <xsl:for-each select="date"> <xsl:apply-templates match="person" /> <xsl:apply-templates match="location" /> <xsl:apply-templates match="dog" /> </xsl:for-each> </xsl:template> ``` The problem I have is that I need the location block in between the person and the dog block. I have tried ../ and it does not work. I simplified this majorly but the point comes across. I can't seem to remember what I need to place in front of location to get it to work. Thanks.
First of all your XML is still not well-formed and I actually cannot catch why you're looping over the `<date/>` tags - there is only one `<date/>` tag inside `<subscriber/>` (assuming that the first `<subscriber/>` should not be self-closed). When using XPath you alway have to think about the context in which the XPatch is called. The following should do it (when my assumption about your data structure is correct): ``` <xsl:template match="subscriber"> <xsl:for-each select="date"> <!-- from here on we're in the context of the date-tag --> <xsl:apply-templates match="../person" /> <xsl:apply-templates match="../location" /> <xsl:apply-templates match="../dog" /> </xsl:for-each> </xsl:template> ```
265,761
<p>In the iPhone 2.x firmware, can you make the iPhone vibrate for durations other than the system-defined:</p> <pre><code>AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); </code></pre> <p>In jailbroken phones, you used to be able to use the MeCCA.framework to do this:</p> <p><a href="http://pastie.org/94481" rel="nofollow noreferrer">http://pastie.org/94481</a></p> <pre><code>MeCCA_Vibrator *v = new MeCCA_Vibrator; v-&gt;activate(1); sleep(5); v-&gt;deactivate(); </code></pre> <p>But MeCCA.framework doesn't exist on my 2.x iPhone.</p>
[ { "answer_id": 266995, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 2, "selected": false, "text": "<p>There's no way to do this using the SDK, sorry.</p>\n" }, { "answer_id": 267015, "author": "Can Berk Güder", "author_id": 2119, "author_profile": "https://Stackoverflow.com/users/2119", "pm_score": 2, "selected": false, "text": "<p>Not only is this impossible to do using the SDK, but it's also the first item in the <a href=\"http://10base-t.com/unofficial-appstore-rejection-criteria/\" rel=\"nofollow noreferrer\">Unofficial App Store Rejection Criteria</a>.</p>\n" }, { "answer_id": 281614, "author": "KevinButler", "author_id": 34463, "author_profile": "https://Stackoverflow.com/users/34463", "pm_score": 5, "selected": true, "text": "<p>Yes, this is something that has caused AppStore rejections in the past, and probably will again...which means it is still possible to do it.</p>\n\n<p>Answering my own question, here's how to do it:</p>\n\n<p>Add framework CoreTelephony in Build Phases. </p>\n\n<p>declare:</p>\n\n<pre><code>extern void * _CTServerConnectionCreate(CFAllocatorRef, int (*)(void *, CFStringRef, CFDictionaryRef, void *), int *);\nextern int _CTServerConnectionSetVibratorState(int *, void *, int, int, float, float, float);\n\nstatic void* connection = nil;\nstatic int x = 0;\n</code></pre>\n\n<p>initialize:</p>\n\n<pre><code>connection = _CTServerConnectionCreate(kCFAllocatorDefault, &amp;vibratecallback, &amp;x);\n</code></pre>\n\n<p>start vibration: </p>\n\n<pre><code>_CTServerConnectionSetVibratorState(&amp;x, connection, 3, intensity, 0, 0, 0);\n</code></pre>\n\n<p>stop vibration:</p>\n\n<pre><code>_CTServerConnectionSetVibratorState(&amp;x, connection, 0, 0, 0, 0, 0);\n</code></pre>\n\n<p>This code is from <a href=\"http://code.google.com/p/zataangstuff/source/browse/trunk/HapticKeyboard/Classes/HapticKeyboard.m?r=93\" rel=\"nofollow noreferrer\">HapticKeyboard</a>, a downloadable application that buzzes the phone as you type. It is available for jailbroken phones on Cydia. See also <a href=\"http://soi.kd6.us/2008/09/25/so-i-got-a-new-phone/\" rel=\"nofollow noreferrer\">my jailbreaking experience</a>)</p>\n\n<p>Any other good references?</p>\n" }, { "answer_id": 8936609, "author": "Nikolay Frick", "author_id": 434448, "author_profile": "https://Stackoverflow.com/users/434448", "pm_score": 0, "selected": false, "text": "<p>iOS 5 has implemented Custom Vibrations mode. So in some cases variable vibration is acceptable. The only thing is unknown what library deals with that (pretty sure not CoreTelephony) and if it is open for developers.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34463/" ]
In the iPhone 2.x firmware, can you make the iPhone vibrate for durations other than the system-defined: ``` AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); ``` In jailbroken phones, you used to be able to use the MeCCA.framework to do this: <http://pastie.org/94481> ``` MeCCA_Vibrator *v = new MeCCA_Vibrator; v->activate(1); sleep(5); v->deactivate(); ``` But MeCCA.framework doesn't exist on my 2.x iPhone.
Yes, this is something that has caused AppStore rejections in the past, and probably will again...which means it is still possible to do it. Answering my own question, here's how to do it: Add framework CoreTelephony in Build Phases. declare: ``` extern void * _CTServerConnectionCreate(CFAllocatorRef, int (*)(void *, CFStringRef, CFDictionaryRef, void *), int *); extern int _CTServerConnectionSetVibratorState(int *, void *, int, int, float, float, float); static void* connection = nil; static int x = 0; ``` initialize: ``` connection = _CTServerConnectionCreate(kCFAllocatorDefault, &vibratecallback, &x); ``` start vibration: ``` _CTServerConnectionSetVibratorState(&x, connection, 3, intensity, 0, 0, 0); ``` stop vibration: ``` _CTServerConnectionSetVibratorState(&x, connection, 0, 0, 0, 0, 0); ``` This code is from [HapticKeyboard](http://code.google.com/p/zataangstuff/source/browse/trunk/HapticKeyboard/Classes/HapticKeyboard.m?r=93), a downloadable application that buzzes the phone as you type. It is available for jailbroken phones on Cydia. See also [my jailbreaking experience](http://soi.kd6.us/2008/09/25/so-i-got-a-new-phone/)) Any other good references?
265,774
<p>Consider the following code:</p> <pre><code>&lt;a href="#label2"&gt;GoTo Label2&lt;/a&gt; ... [content here] ... &lt;a name="label0"&gt;&lt;/a&gt;More content &lt;a name="label1"&gt;&lt;/a&gt;More content &lt;a name="label2"&gt;&lt;/a&gt;More content &lt;a name="label3"&gt;&lt;/a&gt;More content &lt;a name="label4"&gt;&lt;/a&gt;More content </code></pre> <p>Is there a way to emulate clicking on the "GoTo Label2" link to scroll to the appropriate region on the page through code?</p> <p><strong>EDIT</strong>: An acceptable alternative would be to scroll to an element with a unique-id, which already exists on my page. I would be adding the anchor tags if this is a viable solution.</p>
[ { "answer_id": 265789, "author": "mkoeller", "author_id": 33433, "author_profile": "https://Stackoverflow.com/users/33433", "pm_score": 2, "selected": false, "text": "<p>I suppose this will work:</p>\n\n<pre><code>window.location=\"&lt;yourCurrentUri&gt;#label2\";\n</code></pre>\n" }, { "answer_id": 265805, "author": "Ken Pespisa", "author_id": 30812, "author_profile": "https://Stackoverflow.com/users/30812", "pm_score": -1, "selected": false, "text": "<p>you can just open the new URL with the name appended, for instance <code>http://www.example.com/mypage.htm#label2</code></p>\n\n<p>In JavaScript,</p>\n\n<pre><code>location.href = location.href + '#label2';\n</code></pre>\n" }, { "answer_id": 265806, "author": "CubanX", "author_id": 27555, "author_profile": "https://Stackoverflow.com/users/27555", "pm_score": 4, "selected": false, "text": "<p>Using javascript:</p>\n\n<pre><code>window.location.href = '#label2';\n</code></pre>\n\n<p>If you need to do it from the server/code behind, you can just emit this Javascript and register it as a startup script for that page.</p>\n" }, { "answer_id": 265880, "author": "MikeeMike", "author_id": 6447, "author_profile": "https://Stackoverflow.com/users/6447", "pm_score": 7, "selected": true, "text": "<p>This JS has generally worked well for me if you also put an ID on the element:</p>\n\n<pre><code>document.getElementById('MyID').scrollIntoView(true);\n</code></pre>\n\n<p>This is good as it will also position scrollable divs etc so that the content is visible.</p>\n" }, { "answer_id": 265937, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "<p>If the element is an anchor tag, you should be able to do:</p>\n\n<pre><code>document.getElementsByName('label2')[0].focus();\n</code></pre>\n" }, { "answer_id": 315324, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>no \"#\" when you use window.location.hash</p>\n" }, { "answer_id": 4211333, "author": "sebarmeli", "author_id": 506570, "author_profile": "https://Stackoverflow.com/users/506570", "pm_score": 1, "selected": false, "text": "<p>The solution </p>\n\n<pre><code>document.getElementById('MyID').scrollIntoView(true);\n</code></pre>\n\n<p>works well in almost all browsers, whereas I've noticed that in some browsers or in some mobile (such as some Blackberry versions) \"scrollIntoView\" function is not recognized, so I would consider this solution (a bit uglier than the previous one):</p>\n\n<pre><code>window.location.href = window.location.protocol + \"//\" + window.location.host + \n window.location.pathname + window.location.search + \n \"#MyAnchor\";\n</code></pre>\n" }, { "answer_id": 24017343, "author": "Gareth Williams", "author_id": 1029827, "author_profile": "https://Stackoverflow.com/users/1029827", "pm_score": 2, "selected": false, "text": "<p>Moving to a anchor from server side, example is c#.</p>\n\n<pre><code>ClientScript.RegisterStartupScript(this.GetType(), \"hash\", \"location.hash = '#form';\", true);\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
Consider the following code: ``` <a href="#label2">GoTo Label2</a> ... [content here] ... <a name="label0"></a>More content <a name="label1"></a>More content <a name="label2"></a>More content <a name="label3"></a>More content <a name="label4"></a>More content ``` Is there a way to emulate clicking on the "GoTo Label2" link to scroll to the appropriate region on the page through code? **EDIT**: An acceptable alternative would be to scroll to an element with a unique-id, which already exists on my page. I would be adding the anchor tags if this is a viable solution.
This JS has generally worked well for me if you also put an ID on the element: ``` document.getElementById('MyID').scrollIntoView(true); ``` This is good as it will also position scrollable divs etc so that the content is visible.
265,809
<p>I'm scouring the internet for a definition of the term &quot;Internal Node.&quot; I cannot find a succinct definition. Every source I'm looking at uses the term without defining it, and the usage doesn't yield a proper definition of what an internal node actually is.</p> <p>Here are the two places I've been mainly looking: <a href="https://planetmath.org/ExternalNode" rel="nofollow noreferrer">Link</a> assumes that internal nodes are nodes that have two subtrees that aren't null, but doesn't say what nodes in the original tree are internal vs. external. <br /></p> <p><a href="http://www.math.bas.bg/%7Enkirov/2008/NETB201/slides/ch06/ch06-2.html" rel="nofollow noreferrer">http://www.math.bas.bg/~nkirov/2008/NETB201/slides/ch06/ch06-2.html</a> seems to insinuate that internal nodes only exist in proper binary trees and doesn't yield much useful information about them.</p> <p>What actually <em>is</em> an internal node!?</p>
[ { "answer_id": 265815, "author": "Alphager", "author_id": 21684, "author_profile": "https://Stackoverflow.com/users/21684", "pm_score": 4, "selected": false, "text": "<p>As far as i understand it, it is a node which is not a leaf.</p>\n" }, { "answer_id": 265823, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 8, "selected": true, "text": "<pre><code> I ROOT (root is also an INTERNAL NODE, unless it is leaf)\n / \\\n I I INTERNAL NODES\n / / \\\no o o EXTERNAL NODES (or leaves)\n</code></pre>\n\n<p>As the wonderful picture shows, internal nodes are nodes located between the root of the tree and the leaves. Note that the root is also an internal node except in the case it's the only node of the tree.</p>\n\n<p>What is said in one of the sites about an internal node having to have two children is for the tree to be a complete binary tree, not for the node to be internal. </p>\n" }, { "answer_id": 265832, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>An internal node or inner node is any\n node of a tree that has child nodes\n and is thus not a leaf node. An\n intermediate node between the root and\n the leaf nodes is called an internal\n node.</p>\n</blockquote>\n\n<p>Source: <a href=\"http://en.wikipedia.org/wiki/Tree_data_structure\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Tree_data_structure</a></p>\n" }, { "answer_id": 267165, "author": "orcmid", "author_id": 33810, "author_profile": "https://Stackoverflow.com/users/33810", "pm_score": 1, "selected": false, "text": "<p>Generally, an internal node is any node that is not a leaf (a node with no children). </p>\n\n<p>In extended binary trees (also comparison trees), internal nodes all have two children because each internal node corresponds to a comparison that must be made [The Art of Computer Programming (TAoCP) vol.3 Sorting and Searching, discussion and figure in section 5.3.1, p.181 (ed.2). By the way, the use of these trees to represent pairings (and byes) for elimination tournaments is addressed in section 5.4.1 of this material.] </p>\n\n<p>Vinko's diagram reflects this distinction, although the root node is also always either an internal node or a leaf node, in addition to being the only node with no parent.</p>\n\n<p>There is a broader discussion in Knuth's treatment of information structures and properties of trees [TAoCP vol.1 Fundamental Algorithms, discussion of path lengths in trees in section 2.3.4.5, p.p. 399-406 (ed.3) including exercises (many worked-out in the back of the book)]. </p>\n\n<p>It is useful to notice that binary search trees (where internal nodes also hold single values as well as having up to two children) are somewhat different [TAoCP vol.3, section 6.2.2]. The nomenclature still works, though.</p>\n" }, { "answer_id": 339599, "author": "Rich", "author_id": 42897, "author_profile": "https://Stackoverflow.com/users/42897", "pm_score": 0, "selected": false, "text": "<p>A node which has at least one child.</p>\n" }, { "answer_id": 2418728, "author": "suraj", "author_id": 290720, "author_profile": "https://Stackoverflow.com/users/290720", "pm_score": 0, "selected": false, "text": "<p>Ya internal node does not include the root. And a complete binary tree as terminology tells each internal node should have exact 2 nodes. But in a simple binary tree each internal node have atmost 2 nodes i.e it cannot contain more then 2 nodes but less then 2 is permisable</p>\n" }, { "answer_id": 4274921, "author": "Manoj Singh", "author_id": 519837, "author_profile": "https://Stackoverflow.com/users/519837", "pm_score": 0, "selected": false, "text": "<p>A binary tree can have zero , one nodes and can have maximum of two nodes. A binary tree have a left node and a right node in itself.</p>\n" }, { "answer_id": 20272225, "author": "user1767754", "author_id": 1767754, "author_profile": "https://Stackoverflow.com/users/1767754", "pm_score": 2, "selected": false, "text": "<p>An internal node (also known as an inner node, inode for short, or branch node) is any node of a tree that has child nodes. Similarly, an external node (also known as an outer node, leaf node, or terminal node) is any node that does not have child nodes.</p>\n\n<p>quick and simple.</p>\n" }, { "answer_id": 20272342, "author": "freedev", "author_id": 336827, "author_profile": "https://Stackoverflow.com/users/336827", "pm_score": 2, "selected": false, "text": "<p>Internal node: a node which is not the root and has at least one child.</p>\n" }, { "answer_id": 26893602, "author": "user3083948", "author_id": 3083948, "author_profile": "https://Stackoverflow.com/users/3083948", "pm_score": 3, "selected": false, "text": "<p>The most upvoted answer is incorrect. According to <em>Mathematical Structures for Computer Science</em> by Judith Gersting, an internal node is \"A node with no children is called a leaf of the tree; <strong>all non-leaves are called internal nodes</strong>\"</p>\n\n<p>So, for example (I = INTERNAL NODE):\n<code> \n I \n / \\\n * I\n /\\\n * *\n</code></p>\n" }, { "answer_id": 27778641, "author": "PRADOSH NAYAK", "author_id": 4419847, "author_profile": "https://Stackoverflow.com/users/4419847", "pm_score": 4, "selected": false, "text": "<p>From \"Introduction To Algorithms\", edited by Thomas H Cormen:</p>\n\n<blockquote>\n <p>A node with no child is called 'leaf node'. A non-leaf node is an\n 'internal node'.</p>\n</blockquote>\n" }, { "answer_id": 30327181, "author": "nil96", "author_id": 3245676, "author_profile": "https://Stackoverflow.com/users/3245676", "pm_score": 1, "selected": false, "text": "<p>Internal node – a node with at least one child.\nExternal node – a node with no children.</p>\n" }, { "answer_id": 44864347, "author": "SHASHI BHUSAN", "author_id": 4894450, "author_profile": "https://Stackoverflow.com/users/4894450", "pm_score": 0, "selected": false, "text": "<p>An internal node or inner node is any node of a tree that has child nodes and is thus not a leaf node or An intermediate node between the root and the leaf nodes is called an internal node</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29119/" ]
I'm scouring the internet for a definition of the term "Internal Node." I cannot find a succinct definition. Every source I'm looking at uses the term without defining it, and the usage doesn't yield a proper definition of what an internal node actually is. Here are the two places I've been mainly looking: [Link](https://planetmath.org/ExternalNode) assumes that internal nodes are nodes that have two subtrees that aren't null, but doesn't say what nodes in the original tree are internal vs. external. [http://www.math.bas.bg/~nkirov/2008/NETB201/slides/ch06/ch06-2.html](http://www.math.bas.bg/%7Enkirov/2008/NETB201/slides/ch06/ch06-2.html) seems to insinuate that internal nodes only exist in proper binary trees and doesn't yield much useful information about them. What actually *is* an internal node!?
``` I ROOT (root is also an INTERNAL NODE, unless it is leaf) / \ I I INTERNAL NODES / / \ o o o EXTERNAL NODES (or leaves) ``` As the wonderful picture shows, internal nodes are nodes located between the root of the tree and the leaves. Note that the root is also an internal node except in the case it's the only node of the tree. What is said in one of the sites about an internal node having to have two children is for the tree to be a complete binary tree, not for the node to be internal.
265,814
<p>How can I create a regex for a string such as this:</p> <pre><code>&lt;SERVER&gt; &lt;SERVERKEY&gt; &lt;COMMAND&gt; &lt;FOLDERPATH&gt; &lt;RETENTION&gt; &lt;TRANSFERMODE&gt; &lt;OUTPUTPATH&gt; &lt;LOGTO&gt; &lt;OPTIONAL-MAXSIZE&gt; &lt;OPTIONAL-OFFSET&gt; </code></pre> <p>Most of these fields are just simple words, but some of them can be paths, such as FOLDERPATH, OUTPUTPATH, these paths can also be paths with a filename and wildcard appended.</p> <p>Retention is a number, and transfer mode can be bin or ascii. The issue is, LOGTO which can be a path with the logfile name appended to it or can be NO, which means no log file.</p> <p>The main issue, is the optional arguments, they are both numbers, and OFFSET can't exist without MAXSIZE, but MAXSIZE can exist without offset.</p> <p>Heres some examples:</p> <pre><code>loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 300 loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 loveserver love copy /hats* 300 ascii C:\Puppies\no\ C:\log\love.log 256 </code></pre> <p>Now the main issue, is that paths can have spaces in them, so if I use . to match everything, the regex ends up breaking, when parsing the optional arguments where the LOG destination ends up getting attached to the outputpath.</p> <p>Also if I end up using . and start removing parts of it, the regex will start putting things where it shouldn't.</p> <p>Heres my regex:</p> <pre><code>^(\s+)?(?P&lt;SRCHOST&gt;.+)(\s+)(?P&lt;SRCKEY&gt;.+)(\s+)(?P&lt;COMMAND&gt;COPY)(\s+)(?P&lt;SRCDIR&gt;.+)(\s+)(?P&lt;RETENTION&gt;\d+)(\s+)(?P&lt;TRANSFER_MODE&gt;BIN|ASC|BINARY|ASCII)(\s+)(?P&lt;DSTDIR&gt;.+)(\s+)(?P&lt;LOGFILE&gt;.+)(\s+)?(?P&lt;SIZE&gt;\d+)?(\s+)?(?P&lt;OFFSET&gt;\d+)?$ </code></pre>
[ { "answer_id": 265839, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "<p>The problem is that because you're allowing spaces in filenames and using spaces to separate fields, the solution is ambiguous. You either need to use a different field separator character that can't appear in filenames, or use some other method of representing filenames with spaces in them, e.g. putting them in quotation marks.</p>\n" }, { "answer_id": 265884, "author": "Xetius", "author_id": 274, "author_profile": "https://Stackoverflow.com/users/274", "pm_score": 2, "selected": false, "text": "<p>it is theoretically possible, but you are making things incredibly difficult for yourself. You have a number of problems here:</p>\n\n<p>1) You are using space as a separator and you are also allowing spaces in the path names. You can avoid this by forcing the application to use paths without spaces in them.</p>\n\n<p>2) You have 2 optional parameters on the end. This means that with the line ending \"C:\\LogTo Path 256 300\" you have no idea if the path is C:\\LogTo Path 256 300 with no optional parameters or C:\\Log To Path 256 with one optional parameter or C:\\LogTo Path with 2 optional parameters.</p>\n\n<p>This would be easily remedied with a replacement algorithm on the output. Replacing spaces with underscore and underscore with double underscore. Therefore you could reverse this reliably after you have split the log file on spaces.</p>\n\n<p>Even as a human you could not reliably perform this function 100%. </p>\n\n<p>If you presume that all paths either end with a asterisk, a backslash or .log you could use positive lookahead to find the end of the paths, but without some kind of rules regarding this you are stuffed.</p>\n\n<p>I get the feeling that a single regex would be too difficult for this and would make anyone trying to maintain the code insane. I am a regex whore, using them whenever possible and I would not attempt this. </p>\n" }, { "answer_id": 265940, "author": "Stroboskop", "author_id": 23428, "author_profile": "https://Stackoverflow.com/users/23428", "pm_score": 0, "selected": false, "text": "<p>You need to restrict the fields between the paths in a way that the regexp can distinct them from the pathnames.</p>\n\n<p>So unless you put in a special separator, the sequence</p>\n\n<pre><code>&lt;OUTPUTPATH&gt; &lt;LOGTO&gt;\n</code></pre>\n\n<p>with optional spaces will not work.</p>\n\n<p>And if a path can look like those fields, you might get surprising results.\ne.g.</p>\n\n<pre><code>c:\\ 12 bin \\ 250 bin \\output\n</code></pre>\n\n<p>for </p>\n\n<pre><code>&lt;FOLDERPATH&gt; &lt;RETENTION&gt; &lt;TRANSFERMODE&gt; &lt;OUTPUTPATH&gt;\n</code></pre>\n\n<p>is indistinguishable.</p>\n\n<p>So, let's try to restrict allowed characters a bit:</p>\n\n<pre><code>&lt;SERVER&gt;, &lt;SERVERKEY&gt;, &lt;COMMAND&gt; no spaces -&gt; [^]+\n&lt;FOLDERPATH&gt; allow anything -&gt; .+\n&lt;RETENTION&gt; integer -&gt; [0-9]+\n&lt;TRANSFERMODE&gt; allow only bin and ascii -&gt; (bin|ascii)\n&lt;OUTPUTPATH&gt; allow anything -&gt; .+\n&lt;LOGTO&gt; allow anything -&gt; .+\n&lt;OPTIONAL-MAXSIZE&gt;[0-9]*\n&lt;OPTIONAL-OFFSET&gt;[0-9]*\n</code></pre>\n\n<p>So, i'd go with something along the lines of</p>\n\n<pre><code>[^]+ [^]+ [^]+ .+ [0-9]+ (bin|ascii) .+ \\&gt; .+( [0-9]* ( [0-9]*)?)?\n</code></pre>\n\n<p>With a \">\" to separate the two pathes. You might want to quote the pathnames instead.</p>\n\n<p>NB: This was done in a hurry.</p>\n" }, { "answer_id": 266010, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 2, "selected": true, "text": "<p>Just splitting on whitespace is never going to work. But if you can make some assumptions on the data it could be made to work.</p>\n\n<p>Some assumptions I had in mind:</p>\n\n<ul>\n<li><code>SERVER</code>, <code>SERVERKEY</code> and <code>COMMAND</code> not containing any spaces: <code>\\S+</code></li>\n<li><code>FOLDERPATH</code> beginning with a slash: <code>/.*?</code></li>\n<li><code>RETENTION</code> being a number: <code>\\d+</code></li>\n<li><code>TRANSFERMODE</code> not containing any spaces: <code>\\S+</code></li>\n<li><code>OUTPUTPATH</code> beginning with a drive and ending with a slash: <code>[A-Z]:\\\\.*?\\\\</code></li>\n<li><code>LOGTO</code> either being the word \"<code>NO</code>\", or a path beginning with a drive: <code>[A-Z]:\\\\.*?</code></li>\n<li><code>MAXSIZE</code> and <code>OFFSET</code> being a number: <code>\\d+</code></li>\n</ul>\n\n<p>Putting it all together:</p>\n\n<pre><code>^\\s*\n(?P&lt;SERVER&gt;\\S+)\\s+\n(?P&lt;SERVERKEY&gt;\\S+)\\s+\n(?P&lt;COMMAND&gt;\\S+)\\s+\n(?P&lt;FOLDERPATH&gt;/.*?)\\s+ # Slash not that important, but should start with non-whitespace\n(?P&lt;RETENTION&gt;\\d+)\\s+\n(?P&lt;TRANSFERMODE&gt;\\S+)\\s+\n(?P&lt;OUTPUTPATH&gt;[A-Z]:\\\\.*?\\\\)\\s+ # Could also support network paths\n(?P&lt;LOGTO&gt;NO|[A-Z]:\\\\.*?)\n(?:\n \\s+(?P&lt;MAXSIZE&gt;\\d+)\n (?:\n \\s+(?P&lt;OFFSET&gt;\\d+)\n )?\n)?\n\\s*$\n</code></pre>\n\n<p>In one line:</p>\n\n<pre><code>^\\s*(?P&lt;SERVER&gt;\\S+)\\s+(?P&lt;SERVERKEY&gt;\\S+)\\s+(?P&lt;COMMAND&gt;\\S+)\\s+(?P&lt;FOLDERPATH&gt;/.*?)\\s+(?P&lt;RETENTION&gt;\\d+)\\s+(?P&lt;TRANSFERMODE&gt;\\S+)\\s+(?P&lt;OUTPUTPATH&gt;[A-Z]:\\\\.*?\\\\)\\s+(?P&lt;LOGTO&gt;NO|[A-Z]:\\\\.*?)(?:\\s+(?P&lt;MAXSIZE&gt;\\d+)(?:\\s+(?P&lt;OFFSET&gt;\\d+))?)?\\s*$\n</code></pre>\n\n<p>Testing:</p>\n\n<pre><code>&gt;&gt;&gt; import re\n&gt;&gt;&gt; p = re.compile(r'^(?P&lt;SERVER&gt;\\S+)\\s+(?P&lt;SERVERKEY&gt;\\S+)\\s+(?P&lt;COMMAND&gt;\\S+)\\s+(?P&lt;FOLDERPATH&gt;/.*?)\\s+(?P&lt;RETENTION&gt;\\d+)\\s+(?P&lt;TRANSFERMODE&gt;\\S+)\\s+(?P&lt;OUTPUTPATH&gt;[A-Z]:\\\\.*?\\\\)\\s+(?P&lt;LOGTO&gt;NO|[A-Z]:\\\\.*?)(?:\\s+(?P&lt;MAXSIZE&gt;\\d+)(?:\\s+(?P&lt;OFFSET&gt;\\d+))?)?\\s*$',re.M)\n&gt;&gt;&gt; data = r\"\"\"loveserver love copy /muffin* 20 bin C:\\Puppies\\ NO 256 300\n... loveserver love copy /muffin* 20 bin C:\\Puppies\\ NO 256\n... loveserver love copy /hats* 300 ascii C:\\Puppies\\no\\ C:\\log\\love.log 256\"\"\"\n&gt;&gt;&gt; import pprint\n&gt;&gt;&gt; for match in p.finditer(data):\n... print pprint.pprint(match.groupdict())\n...\n{'COMMAND': 'copy',\n 'FOLDERPATH': '/muffin*',\n 'LOGTO': 'NO',\n 'MAXSIZE': '256',\n 'OFFSET': '300',\n 'OUTPUTPATH': 'C:\\\\Puppies\\\\',\n 'RETENTION': '20',\n 'SERVER': 'loveserver',\n 'SERVERKEY': 'love',\n 'TRANSFERMODE': 'bin'}\n{'COMMAND': 'copy',\n 'FOLDERPATH': '/muffin*',\n 'LOGTO': 'NO',\n 'MAXSIZE': '256',\n 'OFFSET': None,\n 'OUTPUTPATH': 'C:\\\\Puppies\\\\',\n 'RETENTION': '20',\n 'SERVER': 'loveserver',\n 'SERVERKEY': 'love',\n 'TRANSFERMODE': 'bin'}\n{'COMMAND': 'copy',\n 'FOLDERPATH': '/hats*',\n 'LOGTO': 'C:\\\\log\\\\love.log',\n 'MAXSIZE': '256',\n 'OFFSET': None,\n 'OUTPUTPATH': 'C:\\\\Puppies\\\\no\\\\',\n 'RETENTION': '300',\n 'SERVER': 'loveserver',\n 'SERVERKEY': 'love',\n 'TRANSFERMODE': 'ascii'}\n&gt;&gt;&gt;\n</code></pre>\n" }, { "answer_id": 266018, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": -1, "selected": false, "text": "<p>Are less than/greater than allowed inside the values? Because if not you have a very simple solution:</p>\n\n<p>Just replace ever occurance of \"&gt; \" with just \"&gt;\", split on \"&gt;&lt;\", and strip out all less than/greater than from each item. It's probably longer than the regex code, but it will be clearer what's going on.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34395/" ]
How can I create a regex for a string such as this: ``` <SERVER> <SERVERKEY> <COMMAND> <FOLDERPATH> <RETENTION> <TRANSFERMODE> <OUTPUTPATH> <LOGTO> <OPTIONAL-MAXSIZE> <OPTIONAL-OFFSET> ``` Most of these fields are just simple words, but some of them can be paths, such as FOLDERPATH, OUTPUTPATH, these paths can also be paths with a filename and wildcard appended. Retention is a number, and transfer mode can be bin or ascii. The issue is, LOGTO which can be a path with the logfile name appended to it or can be NO, which means no log file. The main issue, is the optional arguments, they are both numbers, and OFFSET can't exist without MAXSIZE, but MAXSIZE can exist without offset. Heres some examples: ``` loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 300 loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 loveserver love copy /hats* 300 ascii C:\Puppies\no\ C:\log\love.log 256 ``` Now the main issue, is that paths can have spaces in them, so if I use . to match everything, the regex ends up breaking, when parsing the optional arguments where the LOG destination ends up getting attached to the outputpath. Also if I end up using . and start removing parts of it, the regex will start putting things where it shouldn't. Heres my regex: ``` ^(\s+)?(?P<SRCHOST>.+)(\s+)(?P<SRCKEY>.+)(\s+)(?P<COMMAND>COPY)(\s+)(?P<SRCDIR>.+)(\s+)(?P<RETENTION>\d+)(\s+)(?P<TRANSFER_MODE>BIN|ASC|BINARY|ASCII)(\s+)(?P<DSTDIR>.+)(\s+)(?P<LOGFILE>.+)(\s+)?(?P<SIZE>\d+)?(\s+)?(?P<OFFSET>\d+)?$ ```
Just splitting on whitespace is never going to work. But if you can make some assumptions on the data it could be made to work. Some assumptions I had in mind: * `SERVER`, `SERVERKEY` and `COMMAND` not containing any spaces: `\S+` * `FOLDERPATH` beginning with a slash: `/.*?` * `RETENTION` being a number: `\d+` * `TRANSFERMODE` not containing any spaces: `\S+` * `OUTPUTPATH` beginning with a drive and ending with a slash: `[A-Z]:\\.*?\\` * `LOGTO` either being the word "`NO`", or a path beginning with a drive: `[A-Z]:\\.*?` * `MAXSIZE` and `OFFSET` being a number: `\d+` Putting it all together: ``` ^\s* (?P<SERVER>\S+)\s+ (?P<SERVERKEY>\S+)\s+ (?P<COMMAND>\S+)\s+ (?P<FOLDERPATH>/.*?)\s+ # Slash not that important, but should start with non-whitespace (?P<RETENTION>\d+)\s+ (?P<TRANSFERMODE>\S+)\s+ (?P<OUTPUTPATH>[A-Z]:\\.*?\\)\s+ # Could also support network paths (?P<LOGTO>NO|[A-Z]:\\.*?) (?: \s+(?P<MAXSIZE>\d+) (?: \s+(?P<OFFSET>\d+) )? )? \s*$ ``` In one line: ``` ^\s*(?P<SERVER>\S+)\s+(?P<SERVERKEY>\S+)\s+(?P<COMMAND>\S+)\s+(?P<FOLDERPATH>/.*?)\s+(?P<RETENTION>\d+)\s+(?P<TRANSFERMODE>\S+)\s+(?P<OUTPUTPATH>[A-Z]:\\.*?\\)\s+(?P<LOGTO>NO|[A-Z]:\\.*?)(?:\s+(?P<MAXSIZE>\d+)(?:\s+(?P<OFFSET>\d+))?)?\s*$ ``` Testing: ``` >>> import re >>> p = re.compile(r'^(?P<SERVER>\S+)\s+(?P<SERVERKEY>\S+)\s+(?P<COMMAND>\S+)\s+(?P<FOLDERPATH>/.*?)\s+(?P<RETENTION>\d+)\s+(?P<TRANSFERMODE>\S+)\s+(?P<OUTPUTPATH>[A-Z]:\\.*?\\)\s+(?P<LOGTO>NO|[A-Z]:\\.*?)(?:\s+(?P<MAXSIZE>\d+)(?:\s+(?P<OFFSET>\d+))?)?\s*$',re.M) >>> data = r"""loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 300 ... loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 ... loveserver love copy /hats* 300 ascii C:\Puppies\no\ C:\log\love.log 256""" >>> import pprint >>> for match in p.finditer(data): ... print pprint.pprint(match.groupdict()) ... {'COMMAND': 'copy', 'FOLDERPATH': '/muffin*', 'LOGTO': 'NO', 'MAXSIZE': '256', 'OFFSET': '300', 'OUTPUTPATH': 'C:\\Puppies\\', 'RETENTION': '20', 'SERVER': 'loveserver', 'SERVERKEY': 'love', 'TRANSFERMODE': 'bin'} {'COMMAND': 'copy', 'FOLDERPATH': '/muffin*', 'LOGTO': 'NO', 'MAXSIZE': '256', 'OFFSET': None, 'OUTPUTPATH': 'C:\\Puppies\\', 'RETENTION': '20', 'SERVER': 'loveserver', 'SERVERKEY': 'love', 'TRANSFERMODE': 'bin'} {'COMMAND': 'copy', 'FOLDERPATH': '/hats*', 'LOGTO': 'C:\\log\\love.log', 'MAXSIZE': '256', 'OFFSET': None, 'OUTPUTPATH': 'C:\\Puppies\\no\\', 'RETENTION': '300', 'SERVER': 'loveserver', 'SERVERKEY': 'love', 'TRANSFERMODE': 'ascii'} >>> ```
265,849
<p>That's it. It's a dumb dumb (embarrassing!) question, but I've never used C# before, only C++ and I can't seem to figure out how to access a Label on my main form from a secondary form and change the text. If anybody can let me know real quick what to do I'd be so grateful!</p> <p>BTW, I should really clarify. Sorry: I've got two separate .cs files that each look about like below. I was using the [Designer] in VS2008 to add in the label in Form1. When I type something like Form1.label1 it doesn't understand. The dropdown shows a list of methods and properties for Form1, but there's only about 7, like ControlCollection, Equals, MouseButtons, and a couple others... I can publicly define a variable in Form1 and that shows, but I don't know how to access the label...</p> <pre><code>namespace AnotherProgram { public partial class Form1 : Form { public Form1() { InitializeComponent(); } } } </code></pre>
[ { "answer_id": 265867, "author": "Aaron Smith", "author_id": 12969, "author_profile": "https://Stackoverflow.com/users/12969", "pm_score": 0, "selected": false, "text": "<p>You have to have a reference to Form1 from Form2. Then you need either a method or a property on Form 1 visible to Form2 that changes the label text to \"Hello\".</p>\n" }, { "answer_id": 265885, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "<p>You'll need a reference to the instance of Form1 - for example, if it's Form1 which is constructing Form2, you might pass <code>this</code> in as a constructor parameter.</p>\n\n<p>Then you'll need to either expose the label of Form1 via a property (or - ick! - a non-private field) or write a method/property which will set the text of the label. For example:</p>\n\n<pre><code>public class Form1 : Form \n{\n private Label label;\n\n // Construction etc as normal\n\n public string LabelText\n {\n get { return label.Text; }\n set { label.Text = value; }\n }\n\n public Form2 CreateForm2()\n {\n return new Form2(this);\n }\n}\n\npublic class Form2 : Form\n{\n private Form1 form1;\n\n public Form2(Form1 form1)\n {\n this.form1 = form1;\n // Normal construction\n }\n\n public void SayHello()\n {\n form1.LabelText = \"Hello\";\n }\n}\n</code></pre>\n" }, { "answer_id": 265887, "author": "Craig Norton", "author_id": 24804, "author_profile": "https://Stackoverflow.com/users/24804", "pm_score": 0, "selected": false, "text": "<blockquote>\n<pre><code>Public Class Form1\n Inherits Form\n\n\n Friend label1 As New Label\n\n\n Public Sub openForm2()\n Dim f As New Form2(Me)\n f.Show()\n End Sub\n\n\nEnd Class\n\n\nPublic Class Form2\n Inherits Form\n\n\n Private _ref As Form1\n\n\n Public Sub New()\n _ref = Nothing\n End Sub\n\n\n Public Sub New(ByVal formRef As Form1)\n _ref = formRef\n End Sub\n\n\n Public Sub accessLabel(ByVal setText As String)\n If (_ref IsNot Nothing) Then\n _ref.label1.Text = setText\n Else\n Throw New NullReferenceException(\"_ref is NULL\")\n End If\n End Sub\n\n\nEnd Class\n</code></pre>\n</blockquote>\n" }, { "answer_id": 268172, "author": "netadictos", "author_id": 31791, "author_profile": "https://Stackoverflow.com/users/31791", "pm_score": 0, "selected": false, "text": "<p>I think that delegates is the most powerful option, besides having properties in a Form: <a href=\"http://www.c-sharpcorner.com/UploadFile/mosessaur/winformsdelegates09042006094826AM/winformsdelegates.aspx\" rel=\"nofollow noreferrer\">http://www.c-sharpcorner.com/UploadFile/mosessaur/winformsdelegates09042006094826AM/winformsdelegates.aspx</a></p>\n\n<p>In the second form I define:</p>\n\n<pre><code>public delegate void AddItemDelegate(string item);\npublic AddItemDelegate AddItemCallback;\n</code></pre>\n\n<p>And from the form that opened it I write:</p>\n\n<pre><code>private void btnScenario2_Click(object sender, EventArgs e)\n{\n\n FrmDialog dlg = new FrmDialog();\n //Subscribe this form for callback\n dlg.AddItemCallback = new AddItemDelegate(this.AddItemCallbackFn);\n dlg.ShowDialog();\n\n}\nprivate void AddItemCallbackFn(string item)\n{\n\n lstBx.Items.Add(item);\n\n}\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
That's it. It's a dumb dumb (embarrassing!) question, but I've never used C# before, only C++ and I can't seem to figure out how to access a Label on my main form from a secondary form and change the text. If anybody can let me know real quick what to do I'd be so grateful! BTW, I should really clarify. Sorry: I've got two separate .cs files that each look about like below. I was using the [Designer] in VS2008 to add in the label in Form1. When I type something like Form1.label1 it doesn't understand. The dropdown shows a list of methods and properties for Form1, but there's only about 7, like ControlCollection, Equals, MouseButtons, and a couple others... I can publicly define a variable in Form1 and that shows, but I don't know how to access the label... ``` namespace AnotherProgram { public partial class Form1 : Form { public Form1() { InitializeComponent(); } } } ```
You'll need a reference to the instance of Form1 - for example, if it's Form1 which is constructing Form2, you might pass `this` in as a constructor parameter. Then you'll need to either expose the label of Form1 via a property (or - ick! - a non-private field) or write a method/property which will set the text of the label. For example: ``` public class Form1 : Form { private Label label; // Construction etc as normal public string LabelText { get { return label.Text; } set { label.Text = value; } } public Form2 CreateForm2() { return new Form2(this); } } public class Form2 : Form { private Form1 form1; public Form2(Form1 form1) { this.form1 = form1; // Normal construction } public void SayHello() { form1.LabelText = "Hello"; } } ```
265,850
<p>Usually, I need to retrieve data from a table in some range; for example, a separate page for each search result. In MySQL I use LIMIT keyword but in DB2 I don't know. Now I use this query for retrieve range of data.</p> <pre><code>SELECT * FROM( SELECT SMALLINT(RANK() OVER(ORDER BY NAME DESC)) AS RUNNING_NO , DATA_KEY_VALUE , SHOW_PRIORITY FROM EMPLOYEE WHERE NAME LIKE 'DEL%' ORDER BY NAME DESC FETCH FIRST 20 ROWS ONLY ) AS TMP ORDER BY TMP.RUNNING_NO ASC FETCH FIRST 10 ROWS ONLY </code></pre> <p>but I know it's bad style. So, how to query for highest performance?</p>
[ { "answer_id": 273106, "author": "Paul Morgan", "author_id": 16322, "author_profile": "https://Stackoverflow.com/users/16322", "pm_score": 2, "selected": false, "text": "<p>Not sure why you are creating the TMP table. Isn't RUNNING_NO aready in ascending sequence? I would think:</p>\n\n<pre><code>SELECT SMALLINT(RANK() OVER(ORDER BY NAME DESC)) AS RUNNING_NO,\n DATA_KEY_VALUE,\n SHOW_PRIORITY\n FROM EMPLOYEE\n WHERE NAME LIKE 'DEL%'\n ORDER BY NAME DESC\n FETCH FIRST 10 ROWS ONLY</code></pre>\n\n<p>would give the same results.</p>\n\n<p>Having an INDEX over NAME on the EMPLOYEE table will boost performance of this query.</p>\n" }, { "answer_id": 3033351, "author": "Fuangwith S.", "author_id": 24550, "author_profile": "https://Stackoverflow.com/users/24550", "pm_score": 4, "selected": true, "text": "<p>My requirement have been added into DB2 9.7.2 already.</p>\n\n<p>DB2 9.7.2 adds new syntax for limit query result as illustrate below:</p>\n\n<pre><code>SELECT * FROM TABLE LIMIT 5 OFFSET 20\n</code></pre>\n\n<p>the database will retrieve result from row no. 21 - 25 </p>\n" }, { "answer_id": 4592072, "author": "Pixie", "author_id": 526308, "author_profile": "https://Stackoverflow.com/users/526308", "pm_score": 2, "selected": false, "text": "<p>It's very difficult, it is depends which database do you have.</p>\n\n<p>for example:</p>\n\n<pre><code>SELECT * FROM ( \n SELECT \n ROW_NUMBER() OVER (ORDER BY ID_USER ASC) AS ROWNUM, \n ID_EMPLOYEE, FIRSTNAME, LASTNAME \n FROM EMPLOYEE \n WHERE FIRSTNAME LIKE 'DEL%' \n ) AS A WHERE A.rownum\nBETWEEN 1 AND 25\n</code></pre>\n" }, { "answer_id": 58862567, "author": "Kélisson Jean", "author_id": 5116302, "author_profile": "https://Stackoverflow.com/users/5116302", "pm_score": 0, "selected": false, "text": "<p>It's simple, to make a pagination just follow the syntax.</p>\n\n<pre><code>LIMIT (pageSize) OFFSET ((currentPage) * (pageSize))\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24550/" ]
Usually, I need to retrieve data from a table in some range; for example, a separate page for each search result. In MySQL I use LIMIT keyword but in DB2 I don't know. Now I use this query for retrieve range of data. ``` SELECT * FROM( SELECT SMALLINT(RANK() OVER(ORDER BY NAME DESC)) AS RUNNING_NO , DATA_KEY_VALUE , SHOW_PRIORITY FROM EMPLOYEE WHERE NAME LIKE 'DEL%' ORDER BY NAME DESC FETCH FIRST 20 ROWS ONLY ) AS TMP ORDER BY TMP.RUNNING_NO ASC FETCH FIRST 10 ROWS ONLY ``` but I know it's bad style. So, how to query for highest performance?
My requirement have been added into DB2 9.7.2 already. DB2 9.7.2 adds new syntax for limit query result as illustrate below: ``` SELECT * FROM TABLE LIMIT 5 OFFSET 20 ``` the database will retrieve result from row no. 21 - 25
265,855
<p>I've got a database here that runs entirely on GMT. The client machines, however, may run on many different time zones (including BST). When you pull data back using SqlConnection, it will translate the datetime value so, for instance</p> <p>19 August 2008</p> <p>becomes</p> <p>18 August 2008 23:00:00.</p> <p>My question is, is there a way to specify to the connection that you do not wish this translation to take place?</p>
[ { "answer_id": 265878, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "<p>Only keep UTC values in the database. Have your business objects always translate to/from UTC/local time when storing/retrieving from the database, so that users can view and enter local time values. You can do this by implementing the translation in the getter/setter methods of the BO so that the private variable is in UTC and thus when it is stored back to the database it is already in the form you need.</p>\n" }, { "answer_id": 265971, "author": "Craig Norton", "author_id": 24804, "author_profile": "https://Stackoverflow.com/users/24804", "pm_score": 2, "selected": false, "text": "<p>How are you accessing the data?</p>\n\n<p>I had the same problem when passing DataSets / DataTables from a webservice.</p>\n\n<p>I got round it by setting the DataColumn.DateTimeMode property in the DataTable</p>\n\n<pre><code>returnedDataTable.Columns(\"ColumnName\").DateTimeMode = DataSetDateTime.Unspecified\n</code></pre>\n\n<p>It was just fine after that.</p>\n\n<p>Don't know if this will help.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've got a database here that runs entirely on GMT. The client machines, however, may run on many different time zones (including BST). When you pull data back using SqlConnection, it will translate the datetime value so, for instance 19 August 2008 becomes 18 August 2008 23:00:00. My question is, is there a way to specify to the connection that you do not wish this translation to take place?
How are you accessing the data? I had the same problem when passing DataSets / DataTables from a webservice. I got round it by setting the DataColumn.DateTimeMode property in the DataTable ``` returnedDataTable.Columns("ColumnName").DateTimeMode = DataSetDateTime.Unspecified ``` It was just fine after that. Don't know if this will help.
265,879
<p>I am interested in using/learning RoR in a project where I have to use a .NET dll. Is Ruby capable of importing a .NET dll?</p>
[ { "answer_id": 265890, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 0, "selected": false, "text": "<p>If you use IronRuby (Ruby implementation built on .Net) then it should be able to. If you're already using .Net and want to try out Ruby then you might want to look into IronRuby.</p>\n\n<p>Outside of IronRuby I'm not sure. I haven't used Ruby myself, so I don't know what kinds of things it's capable of.</p>\n" }, { "answer_id": 266032, "author": "mackenir", "author_id": 25457, "author_profile": "https://Stackoverflow.com/users/25457", "pm_score": 2, "selected": false, "text": "<p>If you want to use 'normal' ruby (since I dont think IronRuby fully runs RoR yet) you might be able to go via COM - ie </p>\n\n<pre><code>\"Your Ruby Code\" -&gt; RubyCOM -&gt; \"COM-Callable Wrappers\" -&gt; \"Your .NET objects\"\n</code></pre>\n\n<p><a href=\"http://www.geocities.com/masonralph/rubycomdoc.html\" rel=\"nofollow noreferrer\">RubyCom</a></p>\n\n<p>That's a bit convoluted though. </p>\n\n<p><em>Edit: better COM-based option elsewhere in the answers</em></p>\n" }, { "answer_id": 266050, "author": "Cory Foy", "author_id": 4083, "author_profile": "https://Stackoverflow.com/users/4083", "pm_score": 1, "selected": false, "text": "<p>Another thing - it might be better to think about it more from a Service-Oriented Architecture point. Can you take that .NET DLL and expose it as a service? </p>\n\n<p>Behind the scenes, you can write Ruby modules in C, so you can always write an interop to do what you need. It will limit your deployment to Windows platforms, though (I haven't tried Ruby->Interop->Mono)</p>\n\n<p>Here's a presentation I gave a couple of years back called <a href=\"http://www.cornetdesign.com/files/RubyCSharpStlCodeCamp.ppt\" rel=\"nofollow noreferrer\">Ruby for C# Developers</a>. It's a little dated (It was before John Lam's project got folded into IronRuby), but might help a little.</p>\n" }, { "answer_id": 266403, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 6, "selected": true, "text": "<p>While IronRuby will make short work of talking to your .NET dll (it'll be literally no code at all), it was abandoned by microsoft, and it never got a large enough open source community to keep it going after that event. I wouldn't recommend it these days</p>\n\n<p>Regarding the COM solution, this may actually be a good way to go. </p>\n\n<p>You don't need the RubyCOM library - that lets other COM objects call into ruby code. To load COM objects from ruby, you just need the <code>win32ole</code> library, which comes as part of the standard library on windows ruby.</p>\n\n<p>Whether or not you can load the dll from COM will depend if the .NET dll was built to be 'Com Visible'.\nThe .NET framework defines a <code>ComVisibleAttribute</code>, which can be applied to either an entire assembly, or specific classes within an assembly. If it is set to true for either the whole assembly, or any classes, then the dll will already be callable from COM without any wrapper code. </p>\n\n<p>Here's a test I did.</p>\n\n<p>Create a new .NET dll project (class library). Here's an example class I used:</p>\n\n<pre><code>using System;\nusing System.IO;\n\nnamespace ComLib\n{\n public class LogWriter\n {\n public void WriteLine( string line )\n {\n using( var log = new StreamWriter( File.OpenWrite( @\"c:\\log.file\" ) ) )\n {\n log.WriteLine( line );\n }\n }\n }\n}\n</code></pre>\n\n<p>Now, under the visual studio project, there is a directory called <code>Properties</code> which contains <code>AssemblyInfo.cs</code>. In this file, there will be the following</p>\n\n<pre><code>[assembly: ComVisible( false )]\n</code></pre>\n\n<p>Change the false to true. If you don't want <em>every class</em> in the assembly exposed to COM, then you can leave it set to false in <code>AssemblyInfo.cs</code> and instead put it above each class you want to expose, like this:</p>\n\n<pre><code>[ComVisible( true )]\npublic class LogWriter ....\n</code></pre>\n\n<p>Now right click on the dll project itself, and from the popup menu, select 'properties'. In the list of sections, choose <code>Build</code></p>\n\n<p>Scroll down, and tick the 'Register for COM interop' checkbox. Now when you compile this DLL, visual studio will do the neccessary stuff to load the COM information into the registry. Note if you're on vista you need to run VS as an administrator for this to work.</p>\n\n<p>Now that this is done, recompile your dll, and then create a new ruby file.</p>\n\n<p>In this ruby file, do this:</p>\n\n<pre><code>require 'win32ole'\n\nlib = WIN32OLE.new('[Solution name].ComLib.LogWriter')\nlib.WriteLine('calling .net from ruby via COM, hooray!')\n</code></pre>\n\n<p>Where [Solution name] is to be replaced by the name of the solution you just created (default: \"ClassLibrary1\")</p>\n\n<p>Ruby that ruby file, and presto! you should see that the text gets written to <code>c:\\log.file</code>. </p>\n\n<p>One problem with this solution is that it requires that the .NET dll is already Com Visible, or if it's not, you have the ability to recompile it. If neither of these things are true, then you may have to look at other options.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 270384, "author": "Thibaut Barrère", "author_id": 20302, "author_profile": "https://Stackoverflow.com/users/20302", "pm_score": 0, "selected": false, "text": "<p>Although it's a dead project AFAIK, you may find the previous <a href=\"http://rubyforge.org/projects/rubyclr/\" rel=\"nofollow noreferrer\">RubyCLR project</a> by John Lam (who is now in charge of IronRuby) an interesting one.</p>\n" }, { "answer_id": 488612, "author": "Jirapong", "author_id": 28843, "author_profile": "https://Stackoverflow.com/users/28843", "pm_score": 0, "selected": false, "text": "<p>If you are interested in ASP.NET MVC with IronRuby together, You may find yourself to check out this source code from Jimmy - <a href=\"http://github.com/jschementi/ironrubymvc/tree/master\" rel=\"nofollow noreferrer\"><a href=\"http://github.com/jschementi/ironrubymvc/tree/master\" rel=\"nofollow noreferrer\">http://github.com/jschementi/ironrubymvc/tree/master</a></a></p>\n\n<p>Enjoy!</p>\n" }, { "answer_id": 7852643, "author": "Rich", "author_id": 8261, "author_profile": "https://Stackoverflow.com/users/8261", "pm_score": 2, "selected": false, "text": "<p>You can also write a native -> C# wrapper DLL using managed C++</p>\n\n<p>Export all the functions you want as C calls in the DLL, e.g.</p>\n\n<pre><code>extern \"C\" __declspec ( dllexport ) void CallManagedMethod() {\n Something^ myManagedObject ...\n}\n</code></pre>\n\n<p>Then use FFI to call that DLL from Ruby\n<a href=\"https://github.com/ffi/ffi\" rel=\"nofollow\">https://github.com/ffi/ffi</a></p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34766/" ]
I am interested in using/learning RoR in a project where I have to use a .NET dll. Is Ruby capable of importing a .NET dll?
While IronRuby will make short work of talking to your .NET dll (it'll be literally no code at all), it was abandoned by microsoft, and it never got a large enough open source community to keep it going after that event. I wouldn't recommend it these days Regarding the COM solution, this may actually be a good way to go. You don't need the RubyCOM library - that lets other COM objects call into ruby code. To load COM objects from ruby, you just need the `win32ole` library, which comes as part of the standard library on windows ruby. Whether or not you can load the dll from COM will depend if the .NET dll was built to be 'Com Visible'. The .NET framework defines a `ComVisibleAttribute`, which can be applied to either an entire assembly, or specific classes within an assembly. If it is set to true for either the whole assembly, or any classes, then the dll will already be callable from COM without any wrapper code. Here's a test I did. Create a new .NET dll project (class library). Here's an example class I used: ``` using System; using System.IO; namespace ComLib { public class LogWriter { public void WriteLine( string line ) { using( var log = new StreamWriter( File.OpenWrite( @"c:\log.file" ) ) ) { log.WriteLine( line ); } } } } ``` Now, under the visual studio project, there is a directory called `Properties` which contains `AssemblyInfo.cs`. In this file, there will be the following ``` [assembly: ComVisible( false )] ``` Change the false to true. If you don't want *every class* in the assembly exposed to COM, then you can leave it set to false in `AssemblyInfo.cs` and instead put it above each class you want to expose, like this: ``` [ComVisible( true )] public class LogWriter .... ``` Now right click on the dll project itself, and from the popup menu, select 'properties'. In the list of sections, choose `Build` Scroll down, and tick the 'Register for COM interop' checkbox. Now when you compile this DLL, visual studio will do the neccessary stuff to load the COM information into the registry. Note if you're on vista you need to run VS as an administrator for this to work. Now that this is done, recompile your dll, and then create a new ruby file. In this ruby file, do this: ``` require 'win32ole' lib = WIN32OLE.new('[Solution name].ComLib.LogWriter') lib.WriteLine('calling .net from ruby via COM, hooray!') ``` Where [Solution name] is to be replaced by the name of the solution you just created (default: "ClassLibrary1") Ruby that ruby file, and presto! you should see that the text gets written to `c:\log.file`. One problem with this solution is that it requires that the .NET dll is already Com Visible, or if it's not, you have the ability to recompile it. If neither of these things are true, then you may have to look at other options. Good luck!
265,888
<p>I'm having an issue getting validation error messages to display for a particular field in a Django form, where the field in question is a <strong>ModelMultipleChoiceField</strong>.</p> <p>In the <code>clean(self)</code> method for the Form, I try to add the error message to the field like so:</p> <pre><code>msg = 'error' self._errors['field_name'] = ErrorList([msg]) raise forms.ValidationError(msg) </code></pre> <p>This works okay where 'field_name' points to other field types, but for ModelMultipleChoiceField it just won't display. Should this be handled differently?</p>
[ { "answer_id": 314830, "author": "lawrence", "author_id": 56817, "author_profile": "https://Stackoverflow.com/users/56817", "pm_score": 0, "selected": false, "text": "<p>Why are you instantiating an ErrorList and writing to self._errors directly? Calling \"raise forms.ValidationError(msg)\" takes care of all that already. </p>\n\n<p>And what does your template look like?</p>\n" }, { "answer_id": 1265411, "author": "SmileyChris", "author_id": 143280, "author_profile": "https://Stackoverflow.com/users/143280", "pm_score": 2, "selected": false, "text": "<p>Yeah, it sounds like you're doing it wrong.</p>\n\n<p>You should be using the <a href=\"http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute\" rel=\"nofollow noreferrer\">clean_</a> method instead. Read through that whole document, in fact - it's very informative.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34759/" ]
I'm having an issue getting validation error messages to display for a particular field in a Django form, where the field in question is a **ModelMultipleChoiceField**. In the `clean(self)` method for the Form, I try to add the error message to the field like so: ``` msg = 'error' self._errors['field_name'] = ErrorList([msg]) raise forms.ValidationError(msg) ``` This works okay where 'field\_name' points to other field types, but for ModelMultipleChoiceField it just won't display. Should this be handled differently?
Yeah, it sounds like you're doing it wrong. You should be using the [clean\_](http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute) method instead. Read through that whole document, in fact - it's very informative.
265,896
<p>I've got a junk directory where I toss downloads, one-off projects, email drafts, and other various things that might be useful for a few days but don't need to be saved forever. To stop this directory from taking over my machine, I wrote a program that will delete all files older than a specified number of days and logs some statistics about the number of files deleted and their size just for fun.</p> <p>I noticed that a few project folders were living way longer than they should, so I started to investigate. In particular, it seemed that folders for projects in which I had used SVN were sticking around. It turns out that the read-only files in the .svn directories are not being deleted. I just did a simple test on a read-only file and discovered that <code>System.IO.File.Delete</code> and <code>System.IO.FileInfo.Delete</code> will not delete a read-only file.</p> <p>I don't care about protecting files in this particular directory; if something important is in there it's in the wrong place. Is there a .NET class that can delete read-only files, or am I going to have to check for read-only attributes and strip them?</p>
[ { "answer_id": 265909, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 2, "selected": false, "text": "<p>Why do you need to check? Just forcibly clear the read-only flag and delete the file.</p>\n" }, { "answer_id": 265916, "author": "mkoeller", "author_id": 33433, "author_profile": "https://Stackoverflow.com/users/33433", "pm_score": 1, "selected": false, "text": "<p>Hm, I think I'd rather put</p>\n\n<pre><code>&gt;del /F *\n</code></pre>\n\n<p>into a sheduled task. Maybe wrapped by a batch file for logging statistics.</p>\n\n<p>Am I missing something?</p>\n" }, { "answer_id": 265920, "author": "Tim Stewart", "author_id": 26002, "author_profile": "https://Stackoverflow.com/users/26002", "pm_score": 6, "selected": false, "text": "<p>According to <a href=\"http://msdn.microsoft.com/en-us/library/system.io.file.delete.aspx\" rel=\"noreferrer\">File.Delete's documentation,</a>, you'll have to strip the read-only attribute. You can set the file's attributes using <a href=\"http://msdn.microsoft.com/en-us/library/system.io.file.setattributes.aspx\" rel=\"noreferrer\">File.SetAttributes()</a>.</p>\n" }, { "answer_id": 265938, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 8, "selected": true, "text": "<p>According to <a href=\"http://msdn.microsoft.com/en-us/library/system.io.file.delete.aspx\" rel=\"noreferrer\">File.Delete's documentation,</a>, you'll have to strip the read-only attribute. You can set the file's attributes using <a href=\"http://msdn.microsoft.com/en-us/library/system.io.file.setattributes.aspx\" rel=\"noreferrer\">File.SetAttributes()</a>.</p>\n\n<pre><code>using System.IO;\n\nFile.SetAttributes(filePath, FileAttributes.Normal);\nFile.Delete(filePath);\n</code></pre>\n" }, { "answer_id": 8310592, "author": "Neil", "author_id": 148593, "author_profile": "https://Stackoverflow.com/users/148593", "pm_score": 5, "selected": false, "text": "<p>The equivalent if you happen to be working with a <code>FileInfo</code> object is:</p>\n\n<pre><code>file.IsReadOnly = false;\nfile.Delete();\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2547/" ]
I've got a junk directory where I toss downloads, one-off projects, email drafts, and other various things that might be useful for a few days but don't need to be saved forever. To stop this directory from taking over my machine, I wrote a program that will delete all files older than a specified number of days and logs some statistics about the number of files deleted and their size just for fun. I noticed that a few project folders were living way longer than they should, so I started to investigate. In particular, it seemed that folders for projects in which I had used SVN were sticking around. It turns out that the read-only files in the .svn directories are not being deleted. I just did a simple test on a read-only file and discovered that `System.IO.File.Delete` and `System.IO.FileInfo.Delete` will not delete a read-only file. I don't care about protecting files in this particular directory; if something important is in there it's in the wrong place. Is there a .NET class that can delete read-only files, or am I going to have to check for read-only attributes and strip them?
According to [File.Delete's documentation,](http://msdn.microsoft.com/en-us/library/system.io.file.delete.aspx), you'll have to strip the read-only attribute. You can set the file's attributes using [File.SetAttributes()](http://msdn.microsoft.com/en-us/library/system.io.file.setattributes.aspx). ``` using System.IO; File.SetAttributes(filePath, FileAttributes.Normal); File.Delete(filePath); ```
265,898
<p>I'm coding a small CMS to get a better understanding of how they work and to learn some new things about PHP. I have however come across a problem.</p> <p>I want to use mod_rewrite (though if someone has a better solution I'm up for trying it) to produce nice clean URLs, so site.com/index.php?page=2 can instead be site.com/tools</p> <p>By my understanding I need to alter my .htaccess file each time I add a new page and this is where I strike a problem, my PHP keeps telling me that I can't update it because it hasn't the permissions. A quick bit of chmod reveals that even with 777 permissions it can't do it, am I missing something?</p> <p>My source for mod_rewrite instructions is currently <a href="http://wettone.com/code/clean-urls" rel="noreferrer">this page here</a> incase it is important/useful.</p>
[ { "answer_id": 265934, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 4, "selected": true, "text": "<p>One approach is to rewrite everything to a handling script</p>\n\n<pre><code>RewriteEngine on\nRewriteBase /\n\n# only rewrite if the requested file doesn't exist\nRewriteCond %{REQUEST_FILENAME} !-s \n\n# pass the rest of the request into index.php to handle \nRewriteRule ^(.*)$ /index.php/$1 [L]\n</code></pre>\n\n<p>so if you have a request to <a href=\"http://yourserver/foo/bar/\" rel=\"nofollow noreferrer\">http://yourserver/foo/bar/</a></p>\n\n<p>what you actually get is a request to <a href=\"http://yourserver/index.php/foo/bar\" rel=\"nofollow noreferrer\">http://yourserver/index.php/foo/bar</a> - and you can leave index.php to decide what to do with /foo/bar (using $_SERVER['PATH_INFO'] -<a href=\"https://stackoverflow.com/users/22224/tom\">tom</a>)</p>\n\n<p>You only need to modify .htaccess the first time. All future requests for inexistent files can then be handled in PHP. </p>\n\n<p>You might also find <a href=\"http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html\" rel=\"nofollow noreferrer\">the docs for mod_rewrite</a> useful - but keep it simple or prepare to lose a lot of sleep and hair tracking down obscure errors.</p>\n" }, { "answer_id": 265948, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": false, "text": "<p>Your PHP should for very obvious reasons not be able to modify <code>.htaccess</code>. Even if you get that to work, I'm not sure if it is wise.</p>\n\n<p>How about using a more abstract setup in regard to mod_rewrite rules? Define your general URL pattern, as you would like to use it. For example:</p>\n\n<pre>\n/object/action/id\n</pre>\n\n<p>Then write a set of rules that reroute HTTP requests to a PHP page, which in turn makes the decision what page is to run (say, by including the relevant PHP script).</p>\n\n<pre>\nRewriteRule ^/(\\w+)/?(\\w+)?/?(\\d+)?$ /index.php?object=$1&action=$2&id=$3 [nocase]\n</pre>\n\n<p>This way you would not have to update <code>.htaccess</code> very often an still be flexible.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
I'm coding a small CMS to get a better understanding of how they work and to learn some new things about PHP. I have however come across a problem. I want to use mod\_rewrite (though if someone has a better solution I'm up for trying it) to produce nice clean URLs, so site.com/index.php?page=2 can instead be site.com/tools By my understanding I need to alter my .htaccess file each time I add a new page and this is where I strike a problem, my PHP keeps telling me that I can't update it because it hasn't the permissions. A quick bit of chmod reveals that even with 777 permissions it can't do it, am I missing something? My source for mod\_rewrite instructions is currently [this page here](http://wettone.com/code/clean-urls) incase it is important/useful.
One approach is to rewrite everything to a handling script ``` RewriteEngine on RewriteBase / # only rewrite if the requested file doesn't exist RewriteCond %{REQUEST_FILENAME} !-s # pass the rest of the request into index.php to handle RewriteRule ^(.*)$ /index.php/$1 [L] ``` so if you have a request to <http://yourserver/foo/bar/> what you actually get is a request to <http://yourserver/index.php/foo/bar> - and you can leave index.php to decide what to do with /foo/bar (using $\_SERVER['PATH\_INFO'] -[tom](https://stackoverflow.com/users/22224/tom)) You only need to modify .htaccess the first time. All future requests for inexistent files can then be handled in PHP. You might also find [the docs for mod\_rewrite](http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html) useful - but keep it simple or prepare to lose a lot of sleep and hair tracking down obscure errors.
265,914
<p>I am trying to monitor a tcp flow using flow monitor. attach-fmon wants link object which is not available in wireless connections. How can I solve this problem ? Are there any other solutions ?</p> <p>My code is here <a href="http://pastebin.com/f59241692" rel="nofollow noreferrer">http://pastebin.com/f59241692</a></p> <p>I got this error message</p> <pre><code>eid@eid-laptop:~/code/ns2/noisy$ ns mixed.tcl num_nodes is set 3 INITIALIZE THE LIST xListHead invalid command name "" while executing "$lnk attach-monitors $isnoop $osnoop $dsnoop $fm" (procedure "_o3" line 5) (Simulator attach-fmon line 5) invoked from within "$ns_ attach-fmon $wllink $fmon" (file "mixed.tcl" line 182) </code></pre>
[ { "answer_id": 266406, "author": "Joseph Bui", "author_id": 3275, "author_profile": "https://Stackoverflow.com/users/3275", "pm_score": 0, "selected": false, "text": "<p>I caution you that I have no experience with ns (Network Simulator). Clearly the variable $lnk has the value \"\" in the scope of the proc \"o3\" which is surely an \"object\" created by calling [new ...] at some point, though not necessarily in your code. Perhaps there is some initialization that you have to do so $ns_ or one of the other objects before you can attach a flow monitoring channel.</p>\n" }, { "answer_id": 736215, "author": "lothar", "author_id": 44434, "author_profile": "https://Stackoverflow.com/users/44434", "pm_score": -1, "selected": false, "text": "<p><a href=\"http://www.ethereal.com/\" rel=\"nofollow noreferrer\">Ethereal</a> is an open source network protocol analyzer.\nIt should be able to analyze and display the communication flow of your application.</p>\n" }, { "answer_id": 23770294, "author": "mjs", "author_id": 2139094, "author_profile": "https://Stackoverflow.com/users/2139094", "pm_score": 1, "selected": false, "text": "<p>Wireshark (<a href=\"http://wireshark.org\" rel=\"nofollow\">http://wireshark.org</a>) replaced ethereal in 2006, and is a free, open-source network protocol analyser. It can capture, and analyse data from pretty much any network interface, and will allow you to filter on the communication path of interest by filtering on port number etc.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to monitor a tcp flow using flow monitor. attach-fmon wants link object which is not available in wireless connections. How can I solve this problem ? Are there any other solutions ? My code is here <http://pastebin.com/f59241692> I got this error message ``` eid@eid-laptop:~/code/ns2/noisy$ ns mixed.tcl num_nodes is set 3 INITIALIZE THE LIST xListHead invalid command name "" while executing "$lnk attach-monitors $isnoop $osnoop $dsnoop $fm" (procedure "_o3" line 5) (Simulator attach-fmon line 5) invoked from within "$ns_ attach-fmon $wllink $fmon" (file "mixed.tcl" line 182) ```
Wireshark (<http://wireshark.org>) replaced ethereal in 2006, and is a free, open-source network protocol analyser. It can capture, and analyse data from pretty much any network interface, and will allow you to filter on the communication path of interest by filtering on port number etc.
265,944
<p>How do you reverse the effect of a merge on polarised branches without dying of agony?</p> <p>This problem has been plaguing me for <strong>months</strong> and I have finally given up. </p> <p>You have 1 Repository, with 2 <strong>Named</strong> Branches. A and B. </p> <p>Changes that occur to A will inevitably occur on B. </p> <p>Changes that occur directly on B MUST NEVER occur on A. </p> <p>In such a configuration, merging "B" into "A" produces a dire problem in the repository, as all the changes to B appear in A as if they were made in A. </p> <p>The only "normal" way to recover from this situation appears to be "backing out" the merge, ie: </p> <pre><code> hg up -r A hg backout -r BadMergeRev --parent BadMergerevBeforeOnA </code></pre> <p>Which looks all fine and dandy, until you decide to merge later in the correct direction, and you end up with all sorts of nasty things happening and code that was erased / commented out on specifically branch B suddenly becomes unerased or uncommented. </p> <p>There has not been a working viable solution to this so far other than "let it do its thing, and then hand fix all the problems" and that to be honest is a bit fubar. </p> <p>Here is an image clarifying the problem: </p> <p><em>[Original image lost]</em></p> <p>Files C &amp; E ( or changes C &amp; E ) must appear only on branch b, and not on branch a. Revision A9 here ( branch a, revno 9 ) is the start of the problem. </p> <p>Revisions A10 and A11 are the "Backout merge" and "merge the backout" phases. </p> <p>And revision B12 is mercurial, erroneously repeatedly dropping a change that was intended not to be dropped. </p> <p>This Dilemma has caused much frustration and blue smoke and I would like to put an end to it. </p> <h3>Note</h3> <p>It may be the obvious answer to try prohibiting the reverse merge from occurring, either with hooks or with policies, I have found the ability to muck this up is rather high and the chance of it happening so likely that even with countermeasures, you <em>must</em> still assume that inevitably, it <em>will</em> happen so that you can solve it when it does.</p> <h3>To Elaborate</h3> <p>In the model I have used Seperate files. These make the problem sound simple. These merely represent <em>arbitrary changes</em> which could be a separate line. </p> <p>Also, to add insult to injury, there have been substantial changes on branch A which leaves the standing problem "do the changes in branch A conflict with the changes in branch B which just turned up ( and got backed out ) which looks like a change on branch A instead " </p> <h3>On History Rewriting Tricks:</h3> <p>The problem with all these retro-active solutions is as follows:</p> <ol> <li>We have 9000 commits. </li> <li>Cloning freshly thus takes half an hour</li> <li>If there exists <em>even one</em> bad clone of the repository <em>somewhere</em>, there is a liklihood of it comming back in contact with the original repository, and banging it up all over again. </li> <li>Everyone has cloned this repository already, and now several days have passed with on-going commits.</li> <li>One such clone, happens to be a live site, so "wiping that one and starting from scratch" = "big nono" </li> </ol> <p>( I admit, many of the above are a bit daft, but they are outside of my control ). </p> <p>The only solutions that are viable are the ones that assume that people <em>can</em> and <em>will</em> do everything wrong, and that there is a way to 'undo' this wrongness. </p>
[ { "answer_id": 267973, "author": "Justin Love", "author_id": 30203, "author_profile": "https://Stackoverflow.com/users/30203", "pm_score": 2, "selected": false, "text": "<p>In a pinch, you can export the repository to a bunch diffs, edit history, and then glue back together just what you want - into a new repository, so no risk of damage. Probably not too bad for your example, but I don't know what the real history looks like.</p>\n\n<p>I referenced this page while performing a simpler operation:</p>\n\n<p><a href=\"http://strongdynamic.blogspot.com/2007/08/expunging-problem-file-from-mercurial.html\" rel=\"nofollow noreferrer\">http://strongdynamic.blogspot.com/2007/08/expunging-problem-file-from-mercurial.html</a></p>\n" }, { "answer_id": 269804, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>So you want to merge just some changesets from B into A? Backing out changesets like you have been doing is a really bad idea as you have already suffered.</p>\n\n<p>You should either use the transplant extension or have a third branch where you make common changes to merge into both A and B.</p>\n" }, { "answer_id": 270140, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": "<p>After much discussion with some of the helpful people on #mercurial on freenode, mpm has provided a <em>partial</em> solution that seems to work for my test case ( I generated a fake repository trying to replicate the scenario )</p>\n\n<p>However, on my actual repository, for reasons I don't quite understand, it is still less than perfect. </p>\n\n<p>Here is a diagram of the currently proposed way of resolving this problem: </p>\n\n<p><em>[Original image lost]</em></p>\n\n<p>Its now <em>less</em> of a problem to fix, but I'm still having to compare diffs ( ie: b46:b11 vs b46:b8 , a43:a10 vs a43:a9 ) and hand edit some changes back in. </p>\n\n<p>Not closing this question/taking an answer until I get a guaranteed way that works on any repository. </p>\n\n<h3>Important</h3>\n\n<p>Anyone trying this stuff should clone their repository and play with it like a sandbox first. As you should be doing with <strong>any</strong> merge process, because that way if it goes wrong you can just throw it out and start again. </p>\n" }, { "answer_id": 2093167, "author": "oenli", "author_id": 251438, "author_profile": "https://Stackoverflow.com/users/251438", "pm_score": 6, "selected": false, "text": "<p>I think I found a solution which permanently fixes the bad merge, and which does not require you to manually check any diffs. The trick is to go back in history and generate commits parallel to the bad merge.</p>\n\n<p>So we have repository with separate branches per maintained version of a single product. Like the situation posed in the question, all changes made on a branch of an earlier version (ie. the bugfixes for in that version) must all eventually be merged to the branches of the later versions.</p>\n\n<p>So specifically, if something is checked in on BRANCH_V8, it must be merged to BRANCH_V9.</p>\n\n<p>Now one of the developers makes following mistake : he merges all changes from BRANCH_V9 into BRANCH_V8 (ie. a merge in the wrong direction). Furthermore, after that bad merge he performs some extra commits before he notices his mistake.</p>\n\n<p>So the situation is as shown in the graphical log below.</p>\n\n<pre>o BRANCH_V8 - 13 - important commit right after the bad merge\n|\no BRANCH_V8 - 12 - wrong merge from BRANCH_V9\n|\\\n| o BRANCH_V8 - 11 - adding comment on BRANCH_V8 (ie. last known good state)\n| |\no | BRANCH_V9 - 10 - last commit on BRANCH_V9\n| |\n</pre>\n\n<p>We can fix this mistake as follows: </p>\n\n<ol>\n<li>update your local directory to the last good state of BRANCH_V8: <code>hg update 11</code> </li>\n<li>Create a new child of that last good state : \n\n<ol>\n<li>change some file <code>$EDITOR some/file.txt</code> (this is necessary because Mercurial does not allow empty commits)</li>\n<li>commit these changes <code>hg commit -m \"generating commit on BRANCH_V8 to rectify wrong merge from BRANCH_V9\"</code><br>\nThe situation now looks as follows : \n\n<pre>\no BRANCH_V8 - 14 - generating commit on BRANCH_V8 to rectify wrong merge from BRANCH_V9\n|\n| o BRANCH_V8 - 13 - important commit right after the bad merge\n| |\n| o BRANCH_V8 - 12 - wrong merge from BRANCH_V9\n|/|\no | BRANCH_V8 - 11 - adding comment on BRANCH_V8\n| |\n| o BRANCH_V9 - 10 - last commit on BRANCH_V9\n</pre></li>\n</ol></li>\n<li><p>Merge the newly generated head with the revision in which the bad merge happened, and throw away all changes before committing. <strong>Do not simply merge the two heads, because you will then lose the important commit which happened after the merge as well!</strong></p>\n\n<ol>\n<li>merge : <code>hg merge 12</code> (ignore any conflicts)</li>\n<li>throw away all changes : <code>hg revert -a --no-backup -r 14</code></li>\n<li>commit the changes : <code>hg commit -m \"throwing away wrong merge from BRANCH_V9\"</code>\nThe situtation now looks like :\n\n<pre>\no BRANCH_V8 - 15 - throwing away wrong merge from BRANCH_V9\n|\\\n| o BRANCH_V8 - 14 - generating commit on BRANCH_V8 to rectify wrong merge from BRANCH_V9\n| |\n+---o BRANCH_V8 - 13 - important commit right after the bad merge\n| |\no | BRANCH_V8 - 12 - wrong merge from BRANCH_V9\n|\\|\n| o BRANCH_V8 - 11 - adding comment on BRANCH_V8\n| |\no | BRANCH_V9 - 10 - last commit on BRANCH_V9\n| |\n</pre></li>\n</ol>\n\n<p>Ie. there are two heads on BRANCH_V8: one which contains the fix of the bad merge, and the other containing the left-over important commit on BRANCH_V8 which happened right after the merge.</p></li>\n<li>Merge the two heads on BRANCH_V8 :\n\n<ol>\n<li>merge : <code>hg merge</code></li>\n<li>commit : <code>hg commit -m \"merged two heads used to revert from bad merge\"</code></li>\n</ol></li>\n</ol>\n\n<p>The situation in the end on BRANCH_V8 is now corrected, and looks like this:</p>\n\n<pre>\no BRANCH_V8 - 16 - merged two heads used to revert from bad merge\n|\\\n| o BRANCH_V8 - 15 - throwing away wrong merge from BRANCH_V9\n| |\\\n| | o BRANCH_V8 - 14 - generating commit on BRANCH_V8 to rectify wrong merge from BRANCH_V9\n| | |\no | | BRANCH_V8 - 13 - important commit right after the bad merge\n|/ /\no | BRANCH_V8 - 12 - wrong merge from BRANCH_V9\n|\\|\n| o BRANCH_V8 - 11 - adding comment on BRANCH_V8\n| |\no | BRANCH_V9 - 10 - last commit on BRANCH_V9\n| |\n</pre>\n\n<p>Now the situation on BRANCH_V8 is correct. The only problem remaining is that the next merge from BRANCH_V8 to BRANCH_V9 will be incorrect, as it will merge in the 'fix' for the bad merge as well, which we do not want on BRANCH_V9. The trick here is to merge from BRANCH_V8 to BRANCH_V9 in separate changes :</p>\n\n<ul>\n<li>First merge, from BRANCH_V8 to BRANCH_V9, the correct changes on BRANCH_V8 from before the bad merge.</li>\n<li>Second merge in the merge mistake and its fix, and, without needing to check anything, throw away all changes</li>\n<li>Thirdly merge in the remaining changes from BRANCH_V8.</li>\n</ul>\n\n<p>In detail:</p>\n\n<ol>\n<li>Switch your working directory to BRANCH_V9 : <code>hg update BRANCH_V9</code></li>\n<li>Merge in the last good state of BRANCH_V8 (ie. the commit you generated to fix the bad merge). This merge is a merge like any regular merge, ie. conflicts should be resolved as usual, and nothing needs to be thrown away.\n\n<ol>\n<li>merge : <code>hg merge 14</code></li>\n<li>commit : <code>hg commit -m \"Merging in last good state of BRANCH_V8\"</code>\nThe situation is now :\n\n<pre>\n@ BRANCH_V9 - 17 - Merging in last good state of BRANCH_V8\n|\\\n| | o BRANCH_V8 - 16 - merged two heads used to revert from bad merge\n| | |\\\n| +---o BRANCH_V8 - 15 - throwing away wrong merge from BRANCH_V9\n| | | |\n| o | | BRANCH_V8 - 14 - generating commit on BRANCH_V8 to rectify wrong merge from BRANCH_V9\n| | | |\n| | o | BRANCH_V8 - 13 - important commit right after the bad merge\n| | |/\n+---o BRANCH_V8 - 12 - wrong merge from BRANCH_V9\n| |/\n| o BRANCH_V8 - 11 - adding comment on BRANCH_V8\n| |\no | BRANCH_V9 - 10 - last commit on BRANCH_V9\n| |\n</pre></li>\n</ol></li>\n<li>Merge in the bad merge on BRANCH_V8 + its fix, and throw away all changes :\n\n<ol>\n<li>merge : <code>hg merge 15</code></li>\n<li>revert all changes : <code>hg revert -a --no-backup -r 17</code></li>\n<li>commit the merge : <code>hg commit -m \"Merging in bad merge from BRANCH_V8 and its fix and throwing it all away\"</code>\nCurrent situation : \n\n<pre>\n@ BRANCH_V9 - 18 - Merging in bad merge from BRANCH_V8 and its fix and throwing it all away\n|\\\n| o BRANCH_V9 - 17 - Merging in last good state of BRANCH_V8\n| |\\\n+-----o BRANCH_V8 - 16 - merged two heads used to revert from bad merge\n| | | |\no---+ | BRANCH_V8 - 15 - throwing away wrong merge from BRANCH_V9\n| | | |\n| | o | BRANCH_V8 - 14 - generating commit on BRANCH_V8 to rectify wrong merge from BRANCH_V9\n| | | |\n+-----o BRANCH_V8 - 13 - important commit right after the bad merge\n| | |\no---+ BRANCH_V8 - 12 - wrong merge from BRANCH_V9\n|/ /\n| o BRANCH_V8 - 11 - adding comment on BRANCH_V8\n| |\no | BRANCH_V9 - 10 - last commit on BRANCH_V9\n| |\n</pre></li>\n</ol></li>\n<li>Merge in the left-over changes from BRANCH_V8 :\n\n<ol>\n<li>merge : <code>hg merge BRANCH_V8</code></li>\n<li>commit : <code>hg commit -m \"merging changes from BRANCH_V8\"</code></li>\n</ol></li>\n</ol>\n\n<p>In the end the situation looks like this:</p>\n\n<pre>\n@ BRANCH_V9 - 19 - merging changes from BRANCH_V8\n|\\\n| o BRANCH_V9 - 18 - Merging in bad merge from BRANCH_V8 and its fix and throwing it all away\n| |\\\n| | o BRANCH_V9 - 17 - Merging in last good state of BRANCH_V8\n| | |\\\no | | | BRANCH_V8 - 16 - merged two heads used to revert from bad merge\n|\\| | |\n| o---+ BRANCH_V8 - 15 - throwing away wrong merge from BRANCH_V9\n| | | |\n| | | o BRANCH_V8 - 14 - generating commit on BRANCH_V8 to rectify wrong merge from BRANCH_V9\n| | | |\no | | | BRANCH_V8 - 13 - important commit right after the bad merge\n|/ / /\no---+ BRANCH_V8 - 12 - wrong merge from BRANCH_V9\n|/ /\n| o BRANCH_V8 - 11 - adding comment on BRANCH_V8\n| |\no | BRANCH_V9 - 10 - last commit on BRANCH_V9\n| |\n</pre>\n\n<p>After all these steps, in which you do not have to check any diff manually, BRANCH_V8 and BRANCH_V9 are correct, and future merges from BRANCH_V8 to BRANCH_V9 will be correct as well.</p>\n" }, { "answer_id": 10203239, "author": "Kevin", "author_id": 1340389, "author_profile": "https://Stackoverflow.com/users/1340389", "pm_score": 2, "selected": false, "text": "<p>OK, start by making a new <em>empty</em> repository in a separate directory from the broken repository (hg init). Now, pull up to and including the last known good version into the new repository; make sure you <em>do not</em> pull the bad merge and <em>do</em> pull everything before it. In the old repository, update to the last known good version of A, and do this:</p>\n\n<pre><code>hg graft r1 r2 r3\n</code></pre>\n\n<p>where r1-3 are changes made after the botched merge. You may get conflicts at this point; fix them.</p>\n\n<p>This should produce new changes <em>against the last known good version of A</em>. Pull those new changes into the new repository. Just to double check that you didn't miss anything, do an hg incoming against the old repository. If you see anything other than the botched merge and r1-3, pull it. </p>\n\n<p>Throw the old repository away. You're done. The merge isn't in the new repository at all and you never had to rewrite history.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15614/" ]
How do you reverse the effect of a merge on polarised branches without dying of agony? This problem has been plaguing me for **months** and I have finally given up. You have 1 Repository, with 2 **Named** Branches. A and B. Changes that occur to A will inevitably occur on B. Changes that occur directly on B MUST NEVER occur on A. In such a configuration, merging "B" into "A" produces a dire problem in the repository, as all the changes to B appear in A as if they were made in A. The only "normal" way to recover from this situation appears to be "backing out" the merge, ie: ``` hg up -r A hg backout -r BadMergeRev --parent BadMergerevBeforeOnA ``` Which looks all fine and dandy, until you decide to merge later in the correct direction, and you end up with all sorts of nasty things happening and code that was erased / commented out on specifically branch B suddenly becomes unerased or uncommented. There has not been a working viable solution to this so far other than "let it do its thing, and then hand fix all the problems" and that to be honest is a bit fubar. Here is an image clarifying the problem: *[Original image lost]* Files C & E ( or changes C & E ) must appear only on branch b, and not on branch a. Revision A9 here ( branch a, revno 9 ) is the start of the problem. Revisions A10 and A11 are the "Backout merge" and "merge the backout" phases. And revision B12 is mercurial, erroneously repeatedly dropping a change that was intended not to be dropped. This Dilemma has caused much frustration and blue smoke and I would like to put an end to it. ### Note It may be the obvious answer to try prohibiting the reverse merge from occurring, either with hooks or with policies, I have found the ability to muck this up is rather high and the chance of it happening so likely that even with countermeasures, you *must* still assume that inevitably, it *will* happen so that you can solve it when it does. ### To Elaborate In the model I have used Seperate files. These make the problem sound simple. These merely represent *arbitrary changes* which could be a separate line. Also, to add insult to injury, there have been substantial changes on branch A which leaves the standing problem "do the changes in branch A conflict with the changes in branch B which just turned up ( and got backed out ) which looks like a change on branch A instead " ### On History Rewriting Tricks: The problem with all these retro-active solutions is as follows: 1. We have 9000 commits. 2. Cloning freshly thus takes half an hour 3. If there exists *even one* bad clone of the repository *somewhere*, there is a liklihood of it comming back in contact with the original repository, and banging it up all over again. 4. Everyone has cloned this repository already, and now several days have passed with on-going commits. 5. One such clone, happens to be a live site, so "wiping that one and starting from scratch" = "big nono" ( I admit, many of the above are a bit daft, but they are outside of my control ). The only solutions that are viable are the ones that assume that people *can* and *will* do everything wrong, and that there is a way to 'undo' this wrongness.
I think I found a solution which permanently fixes the bad merge, and which does not require you to manually check any diffs. The trick is to go back in history and generate commits parallel to the bad merge. So we have repository with separate branches per maintained version of a single product. Like the situation posed in the question, all changes made on a branch of an earlier version (ie. the bugfixes for in that version) must all eventually be merged to the branches of the later versions. So specifically, if something is checked in on BRANCH\_V8, it must be merged to BRANCH\_V9. Now one of the developers makes following mistake : he merges all changes from BRANCH\_V9 into BRANCH\_V8 (ie. a merge in the wrong direction). Furthermore, after that bad merge he performs some extra commits before he notices his mistake. So the situation is as shown in the graphical log below. ``` o BRANCH_V8 - 13 - important commit right after the bad merge | o BRANCH_V8 - 12 - wrong merge from BRANCH_V9 |\ | o BRANCH_V8 - 11 - adding comment on BRANCH_V8 (ie. last known good state) | | o | BRANCH_V9 - 10 - last commit on BRANCH_V9 | | ``` We can fix this mistake as follows: 1. update your local directory to the last good state of BRANCH\_V8: `hg update 11` 2. Create a new child of that last good state : 1. change some file `$EDITOR some/file.txt` (this is necessary because Mercurial does not allow empty commits) 2. commit these changes `hg commit -m "generating commit on BRANCH_V8 to rectify wrong merge from BRANCH_V9"` The situation now looks as follows : ``` o BRANCH_V8 - 14 - generating commit on BRANCH_V8 to rectify wrong merge from BRANCH_V9 | | o BRANCH_V8 - 13 - important commit right after the bad merge | | | o BRANCH_V8 - 12 - wrong merge from BRANCH_V9 |/| o | BRANCH_V8 - 11 - adding comment on BRANCH_V8 | | | o BRANCH_V9 - 10 - last commit on BRANCH_V9 ``` 3. Merge the newly generated head with the revision in which the bad merge happened, and throw away all changes before committing. **Do not simply merge the two heads, because you will then lose the important commit which happened after the merge as well!** 1. merge : `hg merge 12` (ignore any conflicts) 2. throw away all changes : `hg revert -a --no-backup -r 14` 3. commit the changes : `hg commit -m "throwing away wrong merge from BRANCH_V9"` The situtation now looks like : ``` o BRANCH_V8 - 15 - throwing away wrong merge from BRANCH_V9 |\ | o BRANCH_V8 - 14 - generating commit on BRANCH_V8 to rectify wrong merge from BRANCH_V9 | | +---o BRANCH_V8 - 13 - important commit right after the bad merge | | o | BRANCH_V8 - 12 - wrong merge from BRANCH_V9 |\| | o BRANCH_V8 - 11 - adding comment on BRANCH_V8 | | o | BRANCH_V9 - 10 - last commit on BRANCH_V9 | | ```Ie. there are two heads on BRANCH\_V8: one which contains the fix of the bad merge, and the other containing the left-over important commit on BRANCH\_V8 which happened right after the merge. 4. Merge the two heads on BRANCH\_V8 : 1. merge : `hg merge` 2. commit : `hg commit -m "merged two heads used to revert from bad merge"` The situation in the end on BRANCH\_V8 is now corrected, and looks like this: ``` o BRANCH_V8 - 16 - merged two heads used to revert from bad merge |\ | o BRANCH_V8 - 15 - throwing away wrong merge from BRANCH_V9 | |\ | | o BRANCH_V8 - 14 - generating commit on BRANCH_V8 to rectify wrong merge from BRANCH_V9 | | | o | | BRANCH_V8 - 13 - important commit right after the bad merge |/ / o | BRANCH_V8 - 12 - wrong merge from BRANCH_V9 |\| | o BRANCH_V8 - 11 - adding comment on BRANCH_V8 | | o | BRANCH_V9 - 10 - last commit on BRANCH_V9 | | ``` Now the situation on BRANCH\_V8 is correct. The only problem remaining is that the next merge from BRANCH\_V8 to BRANCH\_V9 will be incorrect, as it will merge in the 'fix' for the bad merge as well, which we do not want on BRANCH\_V9. The trick here is to merge from BRANCH\_V8 to BRANCH\_V9 in separate changes : * First merge, from BRANCH\_V8 to BRANCH\_V9, the correct changes on BRANCH\_V8 from before the bad merge. * Second merge in the merge mistake and its fix, and, without needing to check anything, throw away all changes * Thirdly merge in the remaining changes from BRANCH\_V8. In detail: 1. Switch your working directory to BRANCH\_V9 : `hg update BRANCH_V9` 2. Merge in the last good state of BRANCH\_V8 (ie. the commit you generated to fix the bad merge). This merge is a merge like any regular merge, ie. conflicts should be resolved as usual, and nothing needs to be thrown away. 1. merge : `hg merge 14` 2. commit : `hg commit -m "Merging in last good state of BRANCH_V8"` The situation is now : ``` @ BRANCH_V9 - 17 - Merging in last good state of BRANCH_V8 |\ | | o BRANCH_V8 - 16 - merged two heads used to revert from bad merge | | |\ | +---o BRANCH_V8 - 15 - throwing away wrong merge from BRANCH_V9 | | | | | o | | BRANCH_V8 - 14 - generating commit on BRANCH_V8 to rectify wrong merge from BRANCH_V9 | | | | | | o | BRANCH_V8 - 13 - important commit right after the bad merge | | |/ +---o BRANCH_V8 - 12 - wrong merge from BRANCH_V9 | |/ | o BRANCH_V8 - 11 - adding comment on BRANCH_V8 | | o | BRANCH_V9 - 10 - last commit on BRANCH_V9 | | ``` 3. Merge in the bad merge on BRANCH\_V8 + its fix, and throw away all changes : 1. merge : `hg merge 15` 2. revert all changes : `hg revert -a --no-backup -r 17` 3. commit the merge : `hg commit -m "Merging in bad merge from BRANCH_V8 and its fix and throwing it all away"` Current situation : ``` @ BRANCH_V9 - 18 - Merging in bad merge from BRANCH_V8 and its fix and throwing it all away |\ | o BRANCH_V9 - 17 - Merging in last good state of BRANCH_V8 | |\ +-----o BRANCH_V8 - 16 - merged two heads used to revert from bad merge | | | | o---+ | BRANCH_V8 - 15 - throwing away wrong merge from BRANCH_V9 | | | | | | o | BRANCH_V8 - 14 - generating commit on BRANCH_V8 to rectify wrong merge from BRANCH_V9 | | | | +-----o BRANCH_V8 - 13 - important commit right after the bad merge | | | o---+ BRANCH_V8 - 12 - wrong merge from BRANCH_V9 |/ / | o BRANCH_V8 - 11 - adding comment on BRANCH_V8 | | o | BRANCH_V9 - 10 - last commit on BRANCH_V9 | | ``` 4. Merge in the left-over changes from BRANCH\_V8 : 1. merge : `hg merge BRANCH_V8` 2. commit : `hg commit -m "merging changes from BRANCH_V8"` In the end the situation looks like this: ``` @ BRANCH_V9 - 19 - merging changes from BRANCH_V8 |\ | o BRANCH_V9 - 18 - Merging in bad merge from BRANCH_V8 and its fix and throwing it all away | |\ | | o BRANCH_V9 - 17 - Merging in last good state of BRANCH_V8 | | |\ o | | | BRANCH_V8 - 16 - merged two heads used to revert from bad merge |\| | | | o---+ BRANCH_V8 - 15 - throwing away wrong merge from BRANCH_V9 | | | | | | | o BRANCH_V8 - 14 - generating commit on BRANCH_V8 to rectify wrong merge from BRANCH_V9 | | | | o | | | BRANCH_V8 - 13 - important commit right after the bad merge |/ / / o---+ BRANCH_V8 - 12 - wrong merge from BRANCH_V9 |/ / | o BRANCH_V8 - 11 - adding comment on BRANCH_V8 | | o | BRANCH_V9 - 10 - last commit on BRANCH_V9 | | ``` After all these steps, in which you do not have to check any diff manually, BRANCH\_V8 and BRANCH\_V9 are correct, and future merges from BRANCH\_V8 to BRANCH\_V9 will be correct as well.
265,956
<p>I am pretty new to php, but I am learning! I have a simple form on a client website. I am testing the form and when I click submit, I get the following error:</p> <p>Form Mail Script</p> <pre><code>Wrong referrer (referring site). For security reasons the form can only be used, if the referring page is part of this website. Note for the Admin: Please add the name of your server to the referrer variable in the index.php configuration file: mywebsite.com </code></pre> <p>Powered by Form Mail Script</p> <p>I am looking through the forms configuration and support files but I do not understand exactly what it is I need to change.</p> <p>Can someone please explain to me what the Admin note above means and how to fix it?</p>
[ { "answer_id": 265981, "author": "Rob Prouse", "author_id": 30827, "author_profile": "https://Stackoverflow.com/users/30827", "pm_score": 2, "selected": false, "text": "<p>You are obviously using the Form Mail script on your page. It has a security feature that prevents other domains from submitting to the form. This is done to prevent bots from using the script to send out spam.</p>\n\n<p>In the configuration for the form mail script or in the script itself, you will find an array or variable with the referrers listed. This is the sites that you want to allow calling of this form mail. You should add your own domain to this list or assign it to this variable.</p>\n\n<p>Sorry, I haven't used this script, so I can't be more specific.</p>\n" }, { "answer_id": 265983, "author": "Karim", "author_id": 2494, "author_profile": "https://Stackoverflow.com/users/2494", "pm_score": 0, "selected": false, "text": "<p>Doing a quick search for the error you're seeing, I found this link: \n<a href=\"http://www.stadtaus.com/forum/t-3528.html\" rel=\"nofollow noreferrer\">http://www.stadtaus.com/forum/t-3528.html</a> </p>\n\n<p>Not sure if that helps you in this case since I'm unfamiliar with the tool you're using but it seemed like a good fit.</p>\n" }, { "answer_id": 266013, "author": "pd.", "author_id": 19066, "author_profile": "https://Stackoverflow.com/users/19066", "pm_score": 1, "selected": true, "text": "<p>The referrer is a value that's usually sent to a server by a client (your browser) along with a request. It indicates the URL from which the requested resource was linked or submitted. This error is part of a security mechanism in FormMail that is intended to prevent the script from handling input that doesn't originate from your website.</p>\n\n<p>For example, say your form is at <em><a href=\"http://www.foo.com/form.html\" rel=\"nofollow noreferrer\">http://www.foo.com/form.html</a></em> and your script is at <em><a href=\"http://www.foo.com/script.php\" rel=\"nofollow noreferrer\">http://www.foo.com/script.php</a></em>. If the script does not check the referrer value, I can create a form on my site at <em><a href=\"http://www.bar.com/myform.html\" rel=\"nofollow noreferrer\">http://www.bar.com/myform.html</a></em> and submit it to your script. Scripts that send mail are often abused in this manner to send spam.</p>\n\n<p>To fix your problem, find the parameter in your script's configuration file that indicates the referrers that your script should handle input from and change it to include your domain or the specific URL of your page.</p>\n\n<p>Note that referrer is generally misspelled as REFERER with only one 'R' within the context of the HTTP protocol.</p>\n" }, { "answer_id": 266105, "author": "pd.", "author_id": 19066, "author_profile": "https://Stackoverflow.com/users/19066", "pm_score": 2, "selected": false, "text": "<p>The line you want to change is:</p>\n\n<pre><code>$referring_server = 'http://www.mywebsite.com, scripts';\n</code></pre>\n\n<p>Changing it to something like this will probably work:</p>\n\n<pre><code>$referring_server = 'yourdomain.com';\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30043/" ]
I am pretty new to php, but I am learning! I have a simple form on a client website. I am testing the form and when I click submit, I get the following error: Form Mail Script ``` Wrong referrer (referring site). For security reasons the form can only be used, if the referring page is part of this website. Note for the Admin: Please add the name of your server to the referrer variable in the index.php configuration file: mywebsite.com ``` Powered by Form Mail Script I am looking through the forms configuration and support files but I do not understand exactly what it is I need to change. Can someone please explain to me what the Admin note above means and how to fix it?
The referrer is a value that's usually sent to a server by a client (your browser) along with a request. It indicates the URL from which the requested resource was linked or submitted. This error is part of a security mechanism in FormMail that is intended to prevent the script from handling input that doesn't originate from your website. For example, say your form is at *<http://www.foo.com/form.html>* and your script is at *<http://www.foo.com/script.php>*. If the script does not check the referrer value, I can create a form on my site at *<http://www.bar.com/myform.html>* and submit it to your script. Scripts that send mail are often abused in this manner to send spam. To fix your problem, find the parameter in your script's configuration file that indicates the referrers that your script should handle input from and change it to include your domain or the specific URL of your page. Note that referrer is generally misspelled as REFERER with only one 'R' within the context of the HTTP protocol.
265,960
<p>It seems like there should be a simpler way than:</p> <pre><code>import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) </code></pre> <p>Is there?</p>
[ { "answer_id": 265995, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 5, "selected": false, "text": "<p>Not necessarily simpler, but a different way, if you are more familiar with the re family. </p>\n\n<pre><code>import re, string\ns = \"string. With. Punctuation?\" # Sample string \nout = re.sub('[%s]' % re.escape(string.punctuation), '', s)\n</code></pre>\n" }, { "answer_id": 266000, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 5, "selected": false, "text": "<p>I usually use something like this:</p>\n\n<pre><code>&gt;&gt;&gt; s = \"string. With. Punctuation?\" # Sample string\n&gt;&gt;&gt; import string\n&gt;&gt;&gt; for c in string.punctuation:\n... s= s.replace(c,\"\")\n...\n&gt;&gt;&gt; s\n'string With Punctuation'\n</code></pre>\n" }, { "answer_id": 266162, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 11, "selected": true, "text": "<p>From an efficiency perspective, you're not going to beat </p>\n\n<pre><code>s.translate(None, string.punctuation)\n</code></pre>\n\n<p>For higher versions of Python use the following code:</p>\n\n<pre><code>s.translate(str.maketrans('', '', string.punctuation))\n</code></pre>\n\n<p>It's performing raw string operations in C with a lookup table - there's not much that will beat that but writing your own C code.</p>\n\n<p>If speed isn't a worry, another option though is:</p>\n\n<pre><code>exclude = set(string.punctuation)\ns = ''.join(ch for ch in s if ch not in exclude)\n</code></pre>\n\n<p>This is faster than s.replace with each char, but won't perform as well as non-pure python approaches such as regexes or string.translate, as you can see from the below timings. For this type of problem, doing it at as low a level as possible pays off.</p>\n\n<p>Timing code:</p>\n\n<pre><code>import re, string, timeit\n\ns = \"string. With. Punctuation\"\nexclude = set(string.punctuation)\ntable = string.maketrans(\"\",\"\")\nregex = re.compile('[%s]' % re.escape(string.punctuation))\n\ndef test_set(s):\n return ''.join(ch for ch in s if ch not in exclude)\n\ndef test_re(s): # From Vinko's solution, with fix.\n return regex.sub('', s)\n\ndef test_trans(s):\n return s.translate(table, string.punctuation)\n\ndef test_repl(s): # From S.Lott's solution\n for c in string.punctuation:\n s=s.replace(c,\"\")\n return s\n\nprint \"sets :\",timeit.Timer('f(s)', 'from __main__ import s,test_set as f').timeit(1000000)\nprint \"regex :\",timeit.Timer('f(s)', 'from __main__ import s,test_re as f').timeit(1000000)\nprint \"translate :\",timeit.Timer('f(s)', 'from __main__ import s,test_trans as f').timeit(1000000)\nprint \"replace :\",timeit.Timer('f(s)', 'from __main__ import s,test_repl as f').timeit(1000000)\n</code></pre>\n\n<p>This gives the following results:</p>\n\n<pre><code>sets : 19.8566138744\nregex : 6.86155414581\ntranslate : 2.12455511093\nreplace : 28.4436721802\n</code></pre>\n" }, { "answer_id": 2402306, "author": "pyrou", "author_id": 288908, "author_profile": "https://Stackoverflow.com/users/288908", "pm_score": 6, "selected": false, "text": "<pre><code>myString.translate(None, string.punctuation)\n</code></pre>\n" }, { "answer_id": 6577965, "author": "David Vuong", "author_id": 781292, "author_profile": "https://Stackoverflow.com/users/781292", "pm_score": 3, "selected": false, "text": "<p>This might not be the best solution however this is how I did it.</p>\n\n<pre><code>import string\nf = lambda x: ''.join([i for i in x if i not in string.punctuation])\n</code></pre>\n" }, { "answer_id": 7268456, "author": "Björn Lindqvist", "author_id": 189247, "author_profile": "https://Stackoverflow.com/users/189247", "pm_score": 5, "selected": false, "text": "<p><code>string.punctuation</code> is ASCII <em>only</em>! A more correct (but also much slower) way is to use the unicodedata module:</p>\n\n<pre><code># -*- coding: utf-8 -*-\nfrom unicodedata import category\ns = u'String — with - «punctation »...'\ns = ''.join(ch for ch in s if category(ch)[0] != 'P')\nprint 'stripped', s\n</code></pre>\n\n<p>You can generalize and strip other types of characters as well:</p>\n\n<pre><code>''.join(ch for ch in s if category(ch)[0] not in 'SP')\n</code></pre>\n\n<p>It will also strip characters like <code>~*+§$</code> which may or may not be \"punctuation\" depending on one's point of view.</p>\n" }, { "answer_id": 15853920, "author": "Disk Giant", "author_id": 2252764, "author_profile": "https://Stackoverflow.com/users/2252764", "pm_score": -1, "selected": false, "text": "<p>I like to use a function like this:</p>\n\n<pre><code>def scrub(abc):\n while abc[-1] is in list(string.punctuation):\n abc=abc[:-1]\n while abc[0] is in list(string.punctuation):\n abc=abc[1:]\n return abc\n</code></pre>\n" }, { "answer_id": 16799238, "author": "Eratosthenes", "author_id": 1499713, "author_profile": "https://Stackoverflow.com/users/1499713", "pm_score": 8, "selected": false, "text": "<p>Regular expressions are simple enough, if you know them. </p>\n\n<pre><code>import re\ns = \"string. With. Punctuation?\"\ns = re.sub(r'[^\\w\\s]','',s)\n</code></pre>\n" }, { "answer_id": 18570395, "author": "Martijn Pieters", "author_id": 100297, "author_profile": "https://Stackoverflow.com/users/100297", "pm_score": 4, "selected": false, "text": "<p>For Python 3 <code>str</code> or Python 2 <code>unicode</code> values, <a href=\"http://docs.python.org/3/library/stdtypes.html#str.translate\" rel=\"noreferrer\"><code>str.translate()</code></a> only takes a dictionary; codepoints (integers) are looked up in that mapping and anything mapped to <code>None</code> is removed.</p>\n\n<p>To remove (some?) punctuation then, use:</p>\n\n<pre><code>import string\n\nremove_punct_map = dict.fromkeys(map(ord, string.punctuation))\ns.translate(remove_punct_map)\n</code></pre>\n\n<p>The <a href=\"http://docs.python.org/3/library/stdtypes.html#dict.fromkeys\" rel=\"noreferrer\"><code>dict.fromkeys()</code> class method</a> makes it trivial to create the mapping, setting all values to <code>None</code> based on the sequence of keys.</p>\n\n<p>To remove <em>all</em> punctuation, not just ASCII punctuation, your table needs to be a little bigger; see <a href=\"https://stackoverflow.com/questions/11066400/remove-punctuation-from-unicode-formatted-strings/11066687#11066687\">J.F. Sebastian's answer</a> (Python 3 version):</p>\n\n<pre><code>import unicodedata\nimport sys\n\nremove_punct_map = dict.fromkeys(i for i in range(sys.maxunicode)\n if unicodedata.category(chr(i)).startswith('P'))\n</code></pre>\n" }, { "answer_id": 32719664, "author": "Dr.Tautology", "author_id": 5363840, "author_profile": "https://Stackoverflow.com/users/5363840", "pm_score": 3, "selected": false, "text": "<p>Here is a function I wrote. It's not very efficient, but it is simple and you can add or remove any punctuation that you desire:</p>\n\n<pre><code>def stripPunc(wordList):\n \"\"\"Strips punctuation from list of words\"\"\"\n puncList = [\".\",\";\",\":\",\"!\",\"?\",\"/\",\"\\\\\",\",\",\"#\",\"@\",\"$\",\"&amp;\",\")\",\"(\",\"\\\"\"]\n for punc in puncList:\n for word in wordList:\n wordList=[word.replace(punc,'') for word in wordList]\n return wordList\n</code></pre>\n" }, { "answer_id": 33192523, "author": "Dom Grey", "author_id": 4304362, "author_profile": "https://Stackoverflow.com/users/4304362", "pm_score": 3, "selected": false, "text": "<p>A one-liner might be helpful in not very strict cases:</p>\n\n<pre><code>''.join([c for c in s if c.isalnum() or c.isspace()])\n</code></pre>\n" }, { "answer_id": 36122360, "author": "Tim P", "author_id": 5480398, "author_profile": "https://Stackoverflow.com/users/5480398", "pm_score": 3, "selected": false, "text": "<p>Here's a one-liner for Python 3.5:</p>\n\n<pre><code>import string\n\"l*ots! o(f. p@u)n[c}t]u[a'ti\\\"on#$^?/\".translate(str.maketrans({a:None for a in string.punctuation}))\n</code></pre>\n" }, { "answer_id": 37221663, "author": "SparkAndShine", "author_id": 3067748, "author_profile": "https://Stackoverflow.com/users/3067748", "pm_score": 6, "selected": false, "text": "<p>For the convenience of usage, I sum up the note of striping punctuation from a string in both Python 2 and Python 3. Please refer to other answers for the detailed description.</p>\n\n<hr>\n\n<p><strong>Python 2</strong></p>\n\n<pre><code>import string\n\ns = \"string. With. Punctuation?\"\ntable = string.maketrans(\"\",\"\")\nnew_s = s.translate(table, string.punctuation) # Output: string without punctuation\n</code></pre>\n\n<hr>\n\n<p><strong>Python 3</strong></p>\n\n<pre><code>import string\n\ns = \"string. With. Punctuation?\"\ntable = str.maketrans(dict.fromkeys(string.punctuation)) # OR {key: None for key in string.punctuation}\nnew_s = s.translate(table) # Output: string without punctuation\n</code></pre>\n" }, { "answer_id": 37894054, "author": "Blairg23", "author_id": 1224827, "author_profile": "https://Stackoverflow.com/users/1224827", "pm_score": 4, "selected": false, "text": "<p>I haven't seen this answer yet. Just use a regex; it removes all characters besides word characters (<code>\\w</code>) and number characters (<code>\\d</code>), followed by a whitespace character (<code>\\s</code>):</p>\n\n<pre><code>import re\ns = \"string. With. Punctuation?\" # Sample string \nout = re.sub(ur'[^\\w\\d\\s]+', '', s)\n</code></pre>\n" }, { "answer_id": 39115253, "author": "Pablo Rodriguez Bertorello", "author_id": 5141805, "author_profile": "https://Stackoverflow.com/users/5141805", "pm_score": 3, "selected": false, "text": "<pre><code>&gt;&gt;&gt; s = \"string. With. Punctuation?\"\n&gt;&gt;&gt; s = re.sub(r'[^\\w\\s]','',s)\n&gt;&gt;&gt; re.split(r'\\s*', s)\n\n\n['string', 'With', 'Punctuation']\n</code></pre>\n" }, { "answer_id": 39901522, "author": "Zach", "author_id": 345660, "author_profile": "https://Stackoverflow.com/users/345660", "pm_score": 4, "selected": false, "text": "<p><code>string.punctuation</code> misses loads of punctuation marks that are commonly used in the real world. How about a solution that works for non-ASCII punctuation?</p>\n\n<pre><code>import regex\ns = u\"string. With. Some・Really Weird、Non?ASCII。 「(Punctuation)」?\"\nremove = regex.compile(ur'[\\p{C}|\\p{M}|\\p{P}|\\p{S}|\\p{Z}]+', regex.UNICODE)\nremove.sub(u\" \", s).strip()\n</code></pre>\n\n<p>Personally, I believe this is the best way to remove punctuation from a string in Python because:</p>\n\n<ul>\n<li>It removes all Unicode punctuation</li>\n<li>It's easily modifiable, e.g. you can remove the <code>\\{S}</code> if you want to remove punctuation, but keep symbols like <code>$</code>.</li>\n<li>You can get really specific about what you want to keep and what you want to remove, for example <code>\\{Pd}</code> will only remove dashes.</li>\n<li>This regex also normalizes whitespace. It maps tabs, carriage returns, and other oddities to nice, single spaces.</li>\n</ul>\n\n<p>This uses Unicode character properties, which <a href=\"https://en.wikipedia.org/wiki/Unicode_character_property\" rel=\"noreferrer\">you can read more about on Wikipedia</a>.</p>\n" }, { "answer_id": 40885971, "author": "ngub05", "author_id": 1952350, "author_profile": "https://Stackoverflow.com/users/1952350", "pm_score": 3, "selected": false, "text": "<p>Here's a solution without regex.</p>\n\n<pre><code>import string\n\ninput_text = \"!where??and!!or$$then:)\"\npunctuation_replacer = string.maketrans(string.punctuation, ' '*len(string.punctuation)) \nprint ' '.join(input_text.translate(punctuation_replacer).split()).strip()\n\nOutput&gt;&gt; where and or then\n</code></pre>\n\n<ul>\n<li>Replaces the punctuations with spaces </li>\n<li>Replace multiple spaces in between words with a single space </li>\n<li>Remove the trailing spaces, if any with\nstrip()</li>\n</ul>\n" }, { "answer_id": 41423791, "author": "Animeartist", "author_id": 4404805, "author_profile": "https://Stackoverflow.com/users/4404805", "pm_score": 2, "selected": false, "text": "<pre><code># FIRST METHOD\n# Storing all punctuations in a variable \npunctuation='!?,.:;&quot;\\')(_-'\nnewstring ='' # Creating empty string\nword = raw_input(&quot;Enter string: &quot;)\nfor i in word:\n if(i not in punctuation):\n newstring += i\nprint (&quot;The string without punctuation is&quot;, newstring)\n\n# SECOND METHOD\nword = raw_input(&quot;Enter string: &quot;)\npunctuation = '!?,.:;&quot;\\')(_-'\nnewstring = word.translate(None, punctuation)\nprint (&quot;The string without punctuation is&quot;,newstring)\n\n\n# Output for both methods\nEnter string: hello! welcome -to_python(programming.language)??,\nThe string without punctuation is: hello welcome topythonprogramminglanguage\n</code></pre>\n" }, { "answer_id": 41462367, "author": "Isayas Wakgari Kelbessa", "author_id": 7373754, "author_profile": "https://Stackoverflow.com/users/7373754", "pm_score": 2, "selected": false, "text": "<pre><code>with open('one.txt','r')as myFile:\n\n str1=myFile.read()\n\n print(str1)\n\n\n punctuation = ['(', ')', '?', ':', ';', ',', '.', '!', '/', '\"', \"'\"] \n\nfor i in punctuation:\n\n str1 = str1.replace(i,\" \") \n myList=[]\n myList.extend(str1.split(\" \"))\nprint (str1) \nfor i in myList:\n\n print(i,end='\\n')\n print (\"____________\")\n</code></pre>\n" }, { "answer_id": 41479924, "author": "Isayas Wakgari Kelbessa", "author_id": 7373754, "author_profile": "https://Stackoverflow.com/users/7373754", "pm_score": -1, "selected": false, "text": "<p>Remove stop words from the text file using Python </p>\n\n<pre><code>print('====THIS IS HOW TO REMOVE STOP WORS====')\n\nwith open('one.txt','r')as myFile:\n\n str1=myFile.read()\n\n stop_words =\"not\", \"is\", \"it\", \"By\",\"between\",\"This\",\"By\",\"A\",\"when\",\"And\",\"up\",\"Then\",\"was\",\"by\",\"It\",\"If\",\"can\",\"an\",\"he\",\"This\",\"or\",\"And\",\"a\",\"i\",\"it\",\"am\",\"at\",\"on\",\"in\",\"of\",\"to\",\"is\",\"so\",\"too\",\"my\",\"the\",\"and\",\"but\",\"are\",\"very\",\"here\",\"even\",\"from\",\"them\",\"then\",\"than\",\"this\",\"that\",\"though\",\"be\",\"But\",\"these\"\n\n myList=[]\n\n myList.extend(str1.split(\" \"))\n\n for i in myList:\n\n if i not in stop_words:\n\n print (\"____________\")\n\n print(i,end='\\n')\n</code></pre>\n" }, { "answer_id": 42012909, "author": "Haythem HADHAB", "author_id": 7508353, "author_profile": "https://Stackoverflow.com/users/7508353", "pm_score": 3, "selected": false, "text": "<pre><code>import re\ns = \"string. With. Punctuation?\" # Sample string \nout = re.sub(r'[^a-zA-Z0-9\\s]', '', s)\n</code></pre>\n" }, { "answer_id": 50215739, "author": "krinker", "author_id": 920085, "author_profile": "https://Stackoverflow.com/users/920085", "pm_score": 3, "selected": false, "text": "<p>Just as an update, I rewrote the @Brian example in Python 3 and made changes to it to move regex compile step inside of the function. My thought here was to time every single step needed to make the function work. Perhaps you are using distributed computing and can't have regex object shared between your workers and need to have <code>re.compile</code> step at each worker. Also, I was curious to time two different implementations of maketrans for Python 3</p>\n\n<pre><code>table = str.maketrans({key: None for key in string.punctuation})\n</code></pre>\n\n<p>vs </p>\n\n<pre><code>table = str.maketrans('', '', string.punctuation)\n</code></pre>\n\n<p>Plus I added another method to use set, where I take advantage of intersection function to reduce number of iterations.</p>\n\n<p>This is the complete code:</p>\n\n<pre><code>import re, string, timeit\n\ns = \"string. With. Punctuation\"\n\n\ndef test_set(s):\n exclude = set(string.punctuation)\n return ''.join(ch for ch in s if ch not in exclude)\n\n\ndef test_set2(s):\n _punctuation = set(string.punctuation)\n for punct in set(s).intersection(_punctuation):\n s = s.replace(punct, ' ')\n return ' '.join(s.split())\n\n\ndef test_re(s): # From Vinko's solution, with fix.\n regex = re.compile('[%s]' % re.escape(string.punctuation))\n return regex.sub('', s)\n\n\ndef test_trans(s):\n table = str.maketrans({key: None for key in string.punctuation})\n return s.translate(table)\n\n\ndef test_trans2(s):\n table = str.maketrans('', '', string.punctuation)\n return(s.translate(table))\n\n\ndef test_repl(s): # From S.Lott's solution\n for c in string.punctuation:\n s=s.replace(c,\"\")\n return s\n\n\nprint(\"sets :\",timeit.Timer('f(s)', 'from __main__ import s,test_set as f').timeit(1000000))\nprint(\"sets2 :\",timeit.Timer('f(s)', 'from __main__ import s,test_set2 as f').timeit(1000000))\nprint(\"regex :\",timeit.Timer('f(s)', 'from __main__ import s,test_re as f').timeit(1000000))\nprint(\"translate :\",timeit.Timer('f(s)', 'from __main__ import s,test_trans as f').timeit(1000000))\nprint(\"translate2 :\",timeit.Timer('f(s)', 'from __main__ import s,test_trans2 as f').timeit(1000000))\nprint(\"replace :\",timeit.Timer('f(s)', 'from __main__ import s,test_repl as f').timeit(1000000))\n</code></pre>\n\n<p>This is my results:</p>\n\n<pre><code>sets : 3.1830138750374317\nsets2 : 2.189873124472797\nregex : 7.142953420989215\ntranslate : 4.243278483860195\ntranslate2 : 2.427158243022859\nreplace : 4.579746678471565\n</code></pre>\n" }, { "answer_id": 57249726, "author": "Dehua Li", "author_id": 10333117, "author_profile": "https://Stackoverflow.com/users/10333117", "pm_score": 3, "selected": false, "text": "<p>Why none of you use this?</p>\n\n<pre><code> ''.join(filter(str.isalnum, s)) \n</code></pre>\n\n<p>Too slow?</p>\n" }, { "answer_id": 62187210, "author": "Rajan saha Raju", "author_id": 8589823, "author_profile": "https://Stackoverflow.com/users/8589823", "pm_score": 0, "selected": false, "text": "<p>Considering unicode. Code checked in python3.</p>\n\n<pre><code>from unicodedata import category\ntext = 'hi, how are you?'\ntext_without_punc = ''.join(ch for ch in text if not category(ch).startswith('P'))\n</code></pre>\n" }, { "answer_id": 63500846, "author": "Zain Sarwar", "author_id": 10873786, "author_profile": "https://Stackoverflow.com/users/10873786", "pm_score": 2, "selected": false, "text": "<p>Here's one other easy way to do it using RegEx</p>\n<pre><code>import re\n\npunct = re.compile(r'(\\w+)')\n\nsentence = 'This ! is : a # sample $ sentence.' # Text with punctuation\ntokenized = [m.group() for m in punct.finditer(sentence)]\nsentence = ' '.join(tokenized)\nprint(sentence) \n'This is a sample sentence'\n\n</code></pre>\n" }, { "answer_id": 63701027, "author": "Vivian", "author_id": 14147996, "author_profile": "https://Stackoverflow.com/users/14147996", "pm_score": 2, "selected": false, "text": "<p>Try that one :)</p>\n<pre><code>regex.sub(r'\\p{P}','', s)\n</code></pre>\n" }, { "answer_id": 66818521, "author": "aloha", "author_id": 3097391, "author_profile": "https://Stackoverflow.com/users/3097391", "pm_score": 3, "selected": false, "text": "<p>I was looking for a really simple solution. here's what I got:</p>\n<pre><code>import re \n\ns = &quot;string. With. Punctuation?&quot; \ns = re.sub(r'[\\W\\s]', ' ', s)\n\nprint(s)\n'string With Punctuation '\n</code></pre>\n" }, { "answer_id": 67282473, "author": "mohannatd", "author_id": 14111556, "author_profile": "https://Stackoverflow.com/users/14111556", "pm_score": 0, "selected": false, "text": "<p>You can also do this:</p>\n<pre><code>import string\n' '.join(word.strip(string.punctuation) for word in 'text'.split())\n</code></pre>\n" }, { "answer_id": 68774177, "author": "Dexter Legaspi", "author_id": 918858, "author_profile": "https://Stackoverflow.com/users/918858", "pm_score": 2, "selected": false, "text": "<p>The question does not have a lot of specifics, so the approach I took is to come up with a solution with the simplest interpretation of the problem: just remove the punctuation.</p>\n<p>Note that solutions presented don't account for contracted words (e.g., <code>you're</code>) or hyphenated words (e.g., <code>anal-retentive</code>)...which is debated as to whether they should or shouldn't be treated as punctuations...nor to account for non-English character set or anything like that...because those specifics were not mentioned in the question. Someone argued that space is punctuation, which is <a href=\"https://en.wikipedia.org/wiki/Space_(punctuation)\" rel=\"nofollow noreferrer\">technically correct</a>...but to me it makes zero sense in the context of the question at hand.</p>\n<pre class=\"lang-py prettyprint-override\"><code># using lambda\n''.join(filter(lambda c: c not in string.punctuation, s))\n\n# using list comprehension\n''.join('' if c in string.punctuation else c for c in s)\n</code></pre>\n" }, { "answer_id": 69451380, "author": "Bob Kline", "author_id": 1357340, "author_profile": "https://Stackoverflow.com/users/1357340", "pm_score": 1, "selected": false, "text": "<p>Apparently I can't supply edits to the selected answer, so here's an update which works for Python 3. The <code>translate</code> approach is still the most efficient option when doing non-trivial transformations.</p>\n<p>Credit for the original heavy lifting to @Brian above. And thanks to @ddejohn for his excellent suggestion for improvement to the original test.</p>\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python3\n\n&quot;&quot;&quot;Determination of most efficient way to remove punctuation in Python 3.\n\nResults in Python 3.8.10 on my system using the default arguments:\n\nset : 51.897\nregex : 17.901\ntranslate : 2.059\nreplace : 13.209\n&quot;&quot;&quot;\n\nimport argparse\nimport re\nimport string\nimport timeit\n\nparser = argparse.ArgumentParser()\nparser.add_argument(&quot;--filename&quot;, &quot;-f&quot;, default=argparse.__file__)\nparser.add_argument(&quot;--iterations&quot;, &quot;-i&quot;, type=int, default=10000)\nopts = parser.parse_args()\nwith open(opts.filename) as fp:\n s = fp.read()\nexclude = set(string.punctuation)\ntable = str.maketrans(&quot;&quot;, &quot;&quot;, string.punctuation)\nregex = re.compile(f&quot;[{re.escape(string.punctuation)}]&quot;)\n\ndef test_set(s):\n return &quot;&quot;.join(ch for ch in s if ch not in exclude)\n\ndef test_regex(s): # From Vinko's solution, with fix.\n return regex.sub(&quot;&quot;, s)\n\ndef test_translate(s):\n return s.translate(table)\n\ndef test_replace(s): # From S.Lott's solution\n for c in string.punctuation:\n s = s.replace(c, &quot;&quot;)\n return s\n\nopts = dict(globals=globals(), number=opts.iterations)\nsolutions = &quot;set&quot;, &quot;regex&quot;, &quot;translate&quot;, &quot;replace&quot;\nfor solution in solutions:\n elapsed = timeit.timeit(f&quot;test_{solution}(s)&quot;, **opts)\n print(f&quot;{solution:&lt;10}: {elapsed:6.3f}&quot;)\n</code></pre>\n" }, { "answer_id": 70186138, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 0, "selected": false, "text": "<p>When you deal with the Unicode strings, I suggest using <a href=\"https://pypi.org/project/regex/\" rel=\"nofollow noreferrer\">PyPi <code>regex</code> module</a> because it supports both Unicode property classes (like <code>\\p{X}</code> / <code>\\P{X}</code>) and POSIX character classes (like <code>[:name:]</code>).</p>\n<p>Just install the package by typing <code>pip install regex</code> (or <code>pip3 install regex</code>) in your terminal and hit ENTER.</p>\n<p>In case you need to remove punctuation and symbols of any kind (that is, anything other than letters, digits and whitespace) you can use</p>\n<pre class=\"lang-py prettyprint-override\"><code>regex.sub(r'[\\p{P}\\p{S}]', '', text) # to remove one by one\nregex.sub(r'[\\p{P}\\p{S}]+', '', text) # to remove all consecutive punctuation/symbols with one go\nregex.sub(r'[[:punct:]]+', '', text) # Same with a POSIX character class\n</code></pre>\n<p>See a <a href=\"https://tio.run/##K6gsycjPM/7/PzO3IL@oRKEoNT21gourJLWiRMFWQf3BkrUPlux7sGTDgyVLFDzzUjITFWzsbOziVPR0dBQVDAyM1LnyUsvjocrBmvWKS5M0itSjYwqqA2qBRHBtTHGstrqOgroCkACp1NTLyS9PLdLQ1CsuKcos0NDk4iooyswr0YAZpfn/PwA\" rel=\"nofollow noreferrer\">Python demo online</a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import regex\n\ntext = 'भारत India &lt;&gt;&lt;&gt;^$.,,! 002'\nnew_text = regex.sub(r'[\\p{P}\\p{S}\\s]+', ' ', text).lower().strip()\n# OR\n# new_text = regex.sub(r'[[:punct:]\\s]+', ' ', text).lower().strip()\n\nprint(new_text)\n# =&gt; भारत india 002\n</code></pre>\n<p>Here, I added a whitespace <code>\\s</code> pattern to the character class</p>\n" }, { "answer_id": 71686005, "author": "qwr", "author_id": 3163618, "author_profile": "https://Stackoverflow.com/users/3163618", "pm_score": 0, "selected": false, "text": "<p>For serious natural language processing (NLP), you should let a library like <a href=\"https://spacy.io/\" rel=\"nofollow noreferrer\">SpaCy</a> handle punctuation through <a href=\"https://spacy.io/usage/linguistic-features#native-tokenizers\" rel=\"nofollow noreferrer\">tokenization</a>, which you can then manually tweak to your needs.</p>\n<p>For example, how do you want to handle hyphens in words? Exceptional cases like abbreviations? Begin and end quotes? URLs? IN NLP it's often useful to separate out a contraction like &quot;let's&quot; into &quot;let&quot; and &quot;'s&quot; for further processing.</p>\n<p><a href=\"https://i.stack.imgur.com/dOzpF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dOzpF.png\" alt=\"SpaCy example tokenization\" /></a></p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
It seems like there should be a simpler way than: ``` import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) ``` Is there?
From an efficiency perspective, you're not going to beat ``` s.translate(None, string.punctuation) ``` For higher versions of Python use the following code: ``` s.translate(str.maketrans('', '', string.punctuation)) ``` It's performing raw string operations in C with a lookup table - there's not much that will beat that but writing your own C code. If speed isn't a worry, another option though is: ``` exclude = set(string.punctuation) s = ''.join(ch for ch in s if ch not in exclude) ``` This is faster than s.replace with each char, but won't perform as well as non-pure python approaches such as regexes or string.translate, as you can see from the below timings. For this type of problem, doing it at as low a level as possible pays off. Timing code: ``` import re, string, timeit s = "string. With. Punctuation" exclude = set(string.punctuation) table = string.maketrans("","") regex = re.compile('[%s]' % re.escape(string.punctuation)) def test_set(s): return ''.join(ch for ch in s if ch not in exclude) def test_re(s): # From Vinko's solution, with fix. return regex.sub('', s) def test_trans(s): return s.translate(table, string.punctuation) def test_repl(s): # From S.Lott's solution for c in string.punctuation: s=s.replace(c,"") return s print "sets :",timeit.Timer('f(s)', 'from __main__ import s,test_set as f').timeit(1000000) print "regex :",timeit.Timer('f(s)', 'from __main__ import s,test_re as f').timeit(1000000) print "translate :",timeit.Timer('f(s)', 'from __main__ import s,test_trans as f').timeit(1000000) print "replace :",timeit.Timer('f(s)', 'from __main__ import s,test_repl as f').timeit(1000000) ``` This gives the following results: ``` sets : 19.8566138744 regex : 6.86155414581 translate : 2.12455511093 replace : 28.4436721802 ```
265,970
<p>I'm more of a programmer than a designer, and I'm trying to embrace <code>&lt;div&gt;</code>s rather than using tables but am getting stuck.</p> <p>Here's what I'm trying to do. I am setting up a survey page. I want each question's text to sit at the top of the blue div, and wrap if it's too long. I want all of the red divs to line up at the top right corner of the container div.</p> <p><a href="http://img528.imageshack.us/img528/4330/divsforsurveyop2.jpg" rel="nofollow noreferrer">Layout http://img528.imageshack.us/img528/4330/divsforsurveyop2.jpg</a></p> <p>Here's what I've started with, it works fine so long as the frame is more than 420 pixels wide. Then the red div skips to the next line. I think I may have approached it wrong, perhaps I should be floating things to the right?</p> <pre><code>.greencontainer{ width:100%; spacing : 10 10 10 10 ; float: left; } .redcontainer{ float: left; width: 20px; padding: 2 0 2 0; font-size: 11px; font-family: sans-serif; text-align: center; } .bluecontainer{ clear: both; float: left; width: 400px; padding: 2 2 2 10; font-size: 11px; font-family: sans-serif; text-align: left; } </code></pre>
[ { "answer_id": 265980, "author": "Eric Wendelin", "author_id": 25066, "author_profile": "https://Stackoverflow.com/users/25066", "pm_score": 0, "selected": false, "text": "<p>Very little testing here, but I <em>think</em> you'll want \"clear: both;\" on .greencontainer instead of \"float: left\". Also remove \"clear: both\" from .bluecontainer</p>\n\n<p>See more info at: <a href=\"http://www.quirksmode.org/css/clearing.html\" rel=\"nofollow noreferrer\">http://www.quirksmode.org/css/clearing.html</a></p>\n" }, { "answer_id": 265986, "author": "Arief", "author_id": 34096, "author_profile": "https://Stackoverflow.com/users/34096", "pm_score": 1, "selected": false, "text": "<p>don't use clear:both on your bluecontainer because it will clear any element on both side(left and right). and you should make the redcontainer float to right.</p>\n" }, { "answer_id": 265988, "author": "Brian Cline", "author_id": 32536, "author_profile": "https://Stackoverflow.com/users/32536", "pm_score": 2, "selected": false, "text": "<p>Don't float anything but the red container, and float it to the right. Make sure the HTML for the red containers is placed before the HTML for the blue containers. Keep the static width on the blue container, and keep your clear:both on the green container.</p>\n" }, { "answer_id": 265999, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 0, "selected": false, "text": "<p>You have \"clear: both\" on the blue div. That is what I think causes the problem.</p>\n\n<p>Look at <a href=\"http://www.barelyfitz.com/screencast/html-training/css/positioning/\" rel=\"nofollow noreferrer\">http://www.barelyfitz.com/screencast/html-training/css/positioning/</a> which had some handy demonstrations.</p>\n" }, { "answer_id": 266007, "author": "philnash", "author_id": 28376, "author_profile": "https://Stackoverflow.com/users/28376", "pm_score": 3, "selected": true, "text": "<p>Here is what I would do:</p>\n\n<pre><code>&lt;div class=\"greencontainer\"&gt;\n &lt;div class=\"redcontainer\"&gt;\n &lt;input type=\"checkbox\" /&gt;\n &lt;/div&gt;\n &lt;div class=\"bluecontainer\"&gt;\n &lt;label&gt;Text about this checkbox...&lt;/label&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>with css:</p>\n\n<pre><code>.greencontainer{\n float:left;\n clear:left;\n width:100%;\n }\n .redcontainer{\n float:right;\n width:20px;\n }\n .bluecontainer{\n margin-right:20px;\n }\n</code></pre>\n\n<p>PS Padding values should always have units, unless they are zero.</p>\n" }, { "answer_id": 266057, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I don't think you need to float the green container at all as it is the containing div. Plus, a \"clear:both\" statement would only be needed if putting multiple blue/red divs in the same green container.</p>\n\n<p>Try</p>\n\n<pre>\n.greencontainer{\n width:100%;\nspacing : 10 10 10 10 ;\n\n}\n\n.bluecontainer{ \n float: left; \n width: 400px; \n padding: 2 2 2 10;\n font-size: 11px;\nfont-family: sans-serif; \n text-align: left; \n}\n.redcontainer{ \n float: right; \n width: 20px;\n padding: 2 0 2 0;\n font-size: 11px;\nfont-family: sans-serif; \n text-align: center; \n}\n</pre>\n\n<p>You may also need to add a right margin to the blue container or left-margin to the red container to get consistent spacing between them rather than using padding which relates to the spacing inside the div not around it</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28351/" ]
I'm more of a programmer than a designer, and I'm trying to embrace `<div>`s rather than using tables but am getting stuck. Here's what I'm trying to do. I am setting up a survey page. I want each question's text to sit at the top of the blue div, and wrap if it's too long. I want all of the red divs to line up at the top right corner of the container div. [Layout http://img528.imageshack.us/img528/4330/divsforsurveyop2.jpg](http://img528.imageshack.us/img528/4330/divsforsurveyop2.jpg) Here's what I've started with, it works fine so long as the frame is more than 420 pixels wide. Then the red div skips to the next line. I think I may have approached it wrong, perhaps I should be floating things to the right? ``` .greencontainer{ width:100%; spacing : 10 10 10 10 ; float: left; } .redcontainer{ float: left; width: 20px; padding: 2 0 2 0; font-size: 11px; font-family: sans-serif; text-align: center; } .bluecontainer{ clear: both; float: left; width: 400px; padding: 2 2 2 10; font-size: 11px; font-family: sans-serif; text-align: left; } ```
Here is what I would do: ``` <div class="greencontainer"> <div class="redcontainer"> <input type="checkbox" /> </div> <div class="bluecontainer"> <label>Text about this checkbox...</label> </div> </div> ``` with css: ``` .greencontainer{ float:left; clear:left; width:100%; } .redcontainer{ float:right; width:20px; } .bluecontainer{ margin-right:20px; } ``` PS Padding values should always have units, unless they are zero.
265,984
<p>Let's say we have defined a CSS class that is being applied to various elements on a page.</p> <pre><code>colourful { color: #DD00DD; background-color: #330033; } </code></pre> <p>People have complained about the colour, that they don't like pink/purple. So you want to give them the ability to change the style as they wish, and they can pick their favourite colours. You have a little colour-picker widget that invokes a Javascript function:</p> <pre><code>function changeColourful(colorRGB, backgroundColorRGB) { // answer goes here } </code></pre> <p>What goes in the body of that function?</p> <p>The intent being that when the user picks a new colour on the colour-picker all the elements with <code>class="colourful"</code> will have their style changed.</p>
[ { "answer_id": 266023, "author": "kemiller2002", "author_id": 1942, "author_profile": "https://Stackoverflow.com/users/1942", "pm_score": -1, "selected": false, "text": "<p>Something like</p>\n\n<pre><code>function changeColourful(colorRGB, backgroundColorRGB)\n {changeColor (document, colorRGB, backgroundColorRGB)}\n\nfunction changeColor (node, color, changeToColor)\n{\n for(var ii = 0 ; ii &lt; node.childNodes.length; ii++)\n {\n if(node.childNodes[ii].childNodes.length &gt; 0)\n {\n changeColor(node.childNodes[ii], color, changeToColor);\n }\n\n if(node[ii].style.backgroundColor == color)\n {\n node[ii].style.backgroundColor = changeToColor;\n }\n\n }\n\n\n}\n</code></pre>\n" }, { "answer_id": 266043, "author": "alex", "author_id": 26787, "author_profile": "https://Stackoverflow.com/users/26787", "pm_score": 3, "selected": false, "text": "<p>I would actually implement this server-side; just store the user's preferred colours in their session (via cookies or whatever is nice and easy for you) and generate the CSS dynamically, i.e.</p>\n\n<pre><code>colourful {\n color: ${userPrefs.colourfulColour};\n background-color: ${userPrefs.colourfulBackgroundColour};\n} \n</code></pre>\n\n<p>If it really suits you much better to do this via Javascript, you can manipulate the CSS using Javascript. See, for instance:</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/ms535871(VS.85).aspx\" rel=\"noreferrer\">Microsoft's Documentation</a></li>\n<li><a href=\"https://developer.mozilla.org/en/DOM/style\" rel=\"noreferrer\">https://developer.mozilla.org/en/DOM/style</a></li>\n</ul>\n" }, { "answer_id": 266062, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>First check if <code>document.styleSheets</code> is defined (see @alex's response).</p>\n\n<p>If not, this question should be helpful:<br>\n<a href=\"https://stackoverflow.com/questions/210377/get-all-elements-in-an-html-document-with-a-specific-css-class\">Get All Elements in an HTML document with a specific CSS Class</a></p>\n\n<p>See the link in the accepted answer and my response at the bottom.</p>\n\n<p>This is only one piece of the answer. You'll still have to go and apply the new values use each element's style property. </p>\n" }, { "answer_id": 266086, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Quick example for a specific div/colour - which could be dynamically passed in via a function</p>\n\n<pre>\ndocument.getElementById('Your Div Name Here').style.background = 'white';\n</pre>\n\n<p>Or, to change the class of the specified item</p>\n\n<pre>\ndocument.getElementById('Your Div Name Here').classname = 'newclassname'\n</pre>\n\n<p>That's assuming you can specify the divs in this way, if not, a combination of this and the node looping solution Kevin showed should do the trick </p>\n" }, { "answer_id": 266103, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 3, "selected": true, "text": "<p>I don't know about manipulating the class directly, but you can effectively do the same thing. Here's an example in jQuery.</p>\n\n<pre><code>$('.colourful').css('background-color', 'purple').css('color','red');\n</code></pre>\n\n<p>In plain javascript, you would have to do more work.</p>\n" }, { "answer_id": 266104, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 3, "selected": false, "text": "<pre><code>var setStyleRule = function(selector, rule) {\n var stylesheet = document.styleSheets[(document.styleSheets.length - 1)];\n if(stylesheet.addRule) {\n stylesheet.addRule(selector, rule)\n } else if(stylesheet.insertRule) {\n stylesheet.insertRule(selector + ' { ' + rule + ' }', stylesheet.cssRules.length);\n }\n};\n</code></pre>\n" }, { "answer_id": 266110, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 2, "selected": false, "text": "<p>jQuery:</p>\n\n<pre><code>function changeColourful(colorRGB, backgroundColorRGB)\n{\n $('.colourful').css({color:colorRGB,backgroundColor:backgroundColorRGB});\n}\n</code></pre>\n\n<p>If you wanted the changes to persist across pages you would would have to store them in a cookie and reapply the function every time.</p>\n" }, { "answer_id": 266875, "author": "vincent", "author_id": 34871, "author_profile": "https://Stackoverflow.com/users/34871", "pm_score": 2, "selected": false, "text": "<p>I just tried using an empty &lt;style> tag in the &lt;head>, then filling it dynamically. Seems to work in ff3, at least.</p>\n\n<p>So :</p>\n\n<p>In the &lt;head> , insert something like :</p>\n\n<pre><code>&lt;style id=\"customstyle\" type=\"text/css\"&gt;&lt;/style&gt;\n</code></pre>\n\n<p>Now you can use something like jquery to replace or append its content :</p>\n\n<p>for replacing :</p>\n\n<pre><code>$(\"#customstyle\").text(\".colourful { color: #345 ; }\");\n</code></pre>\n\n<p>appending :</p>\n\n<pre><code> $(\"#customstyle\").append(\".colourful { color: #345 ; }\");\n</code></pre>\n\n<p>If you want to save it somewhere, just grab the content :</p>\n\n<pre><code> var csscontent = $(\"#customstyle\").text();\n</code></pre>\n\n<p>.. then you could send it back to server through ajax.</p>\n" }, { "answer_id": 8695784, "author": "megar", "author_id": 1070873, "author_profile": "https://Stackoverflow.com/users/1070873", "pm_score": 1, "selected": false, "text": "<p>This is a complete example to change a background-image into a stylesheet.\nFirst part locate the right stylesheet. Here, I wanted the last one, whose href contained \"mycss.css\". You can also use the title property.</p>\n\n<p>Second part locate the right rule. Here, I put a marker \"MYCSSRULE\" so I can locate the right rule.</p>\n\n<p>The css rule in the mycss.css is: #map td, MYCSSRULE { background-image:url(\"img1.png\"); }</p>\n\n<p>The third part just alters the rule.</p>\n\n<p>This process does not work with internet explorer 6. (IE 8 is ok). Works with Firefox 3 and Webkit.</p>\n\n<p>Hope it helped.</p>\n\n<pre><code>function changeBgImg(newimage) {\n var i,n;\n var ssheets = document.styleSheets; // all styleSheets. Find the right one\n var ssheet;\n\n // find the last one whose href contain \"myhref\"\n n = ssheets.length;\n for (i=n-1; i&gt;=0 ;i--) {\n var thisheet = ssheets[i];\n if ( (null != thisheet.href) &amp;&amp; (thisheet.href.indexOf(\"mycss.css\") != -1) ) {\n ssheet = thisheet; break;\n }\n }\n\n if ( (null == ssheet) || (\"undefined\" == typeof(ssheet.cssRules))) {\n // stylesheet not found or internet explorer 6\n return;\n }\n\n // find the right rule\n var rule;\n n = ssheet.cssRules.length;\n for (i=0; i&lt;n; i++) {\n var r = ssheet.cssRules.item(i);\n if (typeof(r.selectorText) == \"undefined\") { continue; }\n if (r.selectorText.indexOf(\"MYCSSRULE\") != -1) {\n rule = r; break;\n }\n }\n\n if (null == rule) {\n // not found\n return;\n }\n\n rule.style.backgroundImage = \"url(\" + newImage + \")\";\n}\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/265984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34778/" ]
Let's say we have defined a CSS class that is being applied to various elements on a page. ``` colourful { color: #DD00DD; background-color: #330033; } ``` People have complained about the colour, that they don't like pink/purple. So you want to give them the ability to change the style as they wish, and they can pick their favourite colours. You have a little colour-picker widget that invokes a Javascript function: ``` function changeColourful(colorRGB, backgroundColorRGB) { // answer goes here } ``` What goes in the body of that function? The intent being that when the user picks a new colour on the colour-picker all the elements with `class="colourful"` will have their style changed.
I don't know about manipulating the class directly, but you can effectively do the same thing. Here's an example in jQuery. ``` $('.colourful').css('background-color', 'purple').css('color','red'); ``` In plain javascript, you would have to do more work.
266,002
<p>I'm using this XPath to get the value of a field:</p> <pre class="lang-none prettyprint-override"><code>//input[@type="hidden"][@name="val"]/@value </code></pre> <p>I get several results, but I only want the first. Using</p> <pre class="lang-none prettyprint-override"><code>//input[@type="hidden"][@name="val"]/@value[1] </code></pre> <p>Doesn't work. Once I have this, how do I pick up the value in Greasemonkey? I am trying things like:</p> <pre><code>alert("val " + val.snapshotItem); </code></pre> <p>But I think that's for the node, rather than the string.</p>
[ { "answer_id": 266083, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": false, "text": "<p>For the XPath, try:</p>\n\n<pre>\n//input[@type=\"hidden\" and @name=\"val\" and position() = 1]/@value\n</pre>\n\n<p>For use in a GreaseMonkey script, do something like this:</p>\n\n<pre><code>var result = document.evaluate(\n \"//input[@type='hidden' and @name='var' and position()=1]/@value\",\n document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null\n);\n\nvar hiddenval = result.snapshotItem(0);\n\nif (hiddenval)\n alert(\"Found: \" + hiddenval.nodeValue); \nelse\n alert(\"Not found.\");\n</code></pre>\n\n<p>Strictly speaking: Using <code>\"position()=1\"</code> in the XPath filter is not absolutely necessary, because only the first returned result is going to be used anyway (via <code>snapshotItem(0)</code>). But why build a larger result set than you really need.</p>\n\n<p>EDIT: Using an XPath result of the <code>ORDERED_NODE_SNAPSHOT_TYPE</code> type makes sure you get the nodes in <em>document order</em>. That means the first node of the result will also be the first node in the document.</p>\n" }, { "answer_id": 266337, "author": "savetheclocktower", "author_id": 25720, "author_profile": "https://Stackoverflow.com/users/25720", "pm_score": 2, "selected": false, "text": "<p>Tomalak has the right idea, but I'd do it a bit differently.</p>\n\n<pre><code>var result = document.evaluate(\n \"//input[@type='hidden' and @name='var']\",\n document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);\n\nvar input = result.iterateNext();\n\nif (input)\n alert(\"Found: \" + input.value); \nelse\n alert(\"Not found.\");\n</code></pre>\n\n<p>This way, you're specifying as part of the <em>result set</em> that you want only one item returned (the first one in the document, in this case). Also, here you're fetching the DOM node and then reading its <code>value</code> property to get the value. I've found this to be more reliable than fetching a string value through XPath (though your mileage may vary).</p>\n" }, { "answer_id": 609403, "author": "Daniel X Moore", "author_id": 68210, "author_profile": "https://Stackoverflow.com/users/68210", "pm_score": -1, "selected": false, "text": "<p>One possibility is to include jQuery in your scripts. This will provide a simpler syntax for accessing elements.</p>\n\n<pre><code>// ==UserScript==\n// @name MyScript\n// @namespace http://example.com\n// @description Example\n// @include *\n//\n// @require http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js\n// ==/UserScript==\n\nvar input = $(\"input[type='hidden'][name='var']\");\n\nif (input) {\n alert(\"Found: \" + input.val()); \n} else {\n alert(\"Not found.\");\n}\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm using this XPath to get the value of a field: ```none //input[@type="hidden"][@name="val"]/@value ``` I get several results, but I only want the first. Using ```none //input[@type="hidden"][@name="val"]/@value[1] ``` Doesn't work. Once I have this, how do I pick up the value in Greasemonkey? I am trying things like: ``` alert("val " + val.snapshotItem); ``` But I think that's for the node, rather than the string.
For the XPath, try: ``` //input[@type="hidden" and @name="val" and position() = 1]/@value ``` For use in a GreaseMonkey script, do something like this: ``` var result = document.evaluate( "//input[@type='hidden' and @name='var' and position()=1]/@value", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null ); var hiddenval = result.snapshotItem(0); if (hiddenval) alert("Found: " + hiddenval.nodeValue); else alert("Not found."); ``` Strictly speaking: Using `"position()=1"` in the XPath filter is not absolutely necessary, because only the first returned result is going to be used anyway (via `snapshotItem(0)`). But why build a larger result set than you really need. EDIT: Using an XPath result of the `ORDERED_NODE_SNAPSHOT_TYPE` type makes sure you get the nodes in *document order*. That means the first node of the result will also be the first node in the document.
266,015
<p>I want to have two items on the same line using <code>float: left</code> for the item on the left.</p> <p>I have no problems achieving this alone. The problem is, I want the two items to <strong>stay</strong> on the same line <em>even when you resize the browser very small</em>. You know... like how it was with tables.</p> <p>The goal is to keep the item on the right from wrapping <em>no matter what</em>.</p> <p>How to I tell the browser using CSS that I would rather <strong>stretch the containing <code>div</code></strong> than wrap it so the the <code>float: right;</code> div is below the <code>float: left;</code> <code>div</code>?</p> <p>what I want:</p> <pre><code> \ +---------------+ +------------------------/ | float: left; | | float: right; \ | | | / | | |content stretching \ Screen Edge | | |the div off the screen / &lt;--- +---------------+ +------------------------\ / </code></pre>
[ { "answer_id": 266025, "author": "Eric Wendelin", "author_id": 25066, "author_profile": "https://Stackoverflow.com/users/25066", "pm_score": 7, "selected": true, "text": "<p>Wrap your floating <code>&lt;div&gt;</code>s in a container <code>&lt;div&gt;</code> that uses this cross-browser min-width hack:</p>\n\n<pre><code>.minwidth { min-width:100px; width: auto !important; width: 100px; }\n</code></pre>\n\n<p>You <em>may</em> also need to set \"overflow\" but probably not.</p>\n\n<p>This works because:</p>\n\n<ul>\n<li>The <code>!important</code> declaration, combined with <code>min-width</code> cause everything to stay on the same line in IE7+</li>\n<li>IE6 does not implement <code>min-width</code>, but it has a bug such that <code>width: 100px</code> overrides the <code>!important</code> declaration, causing the container width to be 100px.</li>\n</ul>\n" }, { "answer_id": 266038, "author": "glenatron", "author_id": 15394, "author_profile": "https://Stackoverflow.com/users/15394", "pm_score": 2, "selected": false, "text": "<p>Are you sure that floated block-level elements are the best solution to this problem? </p>\n\n<p>Often with CSS difficulties in my experience it turns out that the reason I can't see a way of doing the thing I want is that I have got caught in a tunnel-vision with regard to my markup ( thinking \"how can I make <em>these</em> elements do <em>this</em>?\" ) rather than going back and looking at what exactly it is I need to achieve and maybe reworking my html slightly to facilitate that.</p>\n" }, { "answer_id": 267109, "author": "Steve Clay", "author_id": 3779, "author_profile": "https://Stackoverflow.com/users/3779", "pm_score": 3, "selected": false, "text": "<p>Another option: Do not float your right column; just give it a left margin to move it beyond the float. You'll need a hack or two to fix IE6, but that's the basic idea.</p>\n" }, { "answer_id": 274492, "author": "pkario", "author_id": 28207, "author_profile": "https://Stackoverflow.com/users/28207", "pm_score": 4, "selected": false, "text": "<p>Solution 1:\n<p>display:table-cell (not widely supported)\n<p>Solution 2:\n<p>tables</p>\n\n<p>(I hate hacks.)</p>\n" }, { "answer_id": 3336629, "author": "Rob Elliott", "author_id": 402473, "author_profile": "https://Stackoverflow.com/users/402473", "pm_score": 2, "selected": false, "text": "<p>i'd recommend using tables for this problem. i'm having a similar issue and as long as the table is just used to display some data and not for the main page layout it is fine.</p>\n" }, { "answer_id": 5547463, "author": "Czar", "author_id": 692241, "author_profile": "https://Stackoverflow.com/users/692241", "pm_score": 4, "selected": false, "text": "<p>Wrap your floaters in a div with a min-width greater than the combined width+margin of the floaters.</p>\n\n<p>No hacks or HTML tables needed.</p>\n" }, { "answer_id": 9978234, "author": "Inserve", "author_id": 1308275, "author_profile": "https://Stackoverflow.com/users/1308275", "pm_score": 7, "selected": false, "text": "<p>Another option is, instead of floating, to set the white-space property nowrap to a parent div:</p>\n\n<pre><code>.parent {\n white-space: nowrap;\n}\n</code></pre>\n\n<p>and reset the white-space and use an inline-block display so the divs stay on the same line but you can still give it a width.</p>\n\n<pre><code>.child {\n display:inline-block;\n width:300px;\n white-space: normal;\n}\n</code></pre>\n\n<p>Here is a JSFiddle: <a href=\"https://jsfiddle.net/9g8ud31o/\" rel=\"noreferrer\">https://jsfiddle.net/9g8ud31o/</a></p>\n" }, { "answer_id": 16628726, "author": "ScubaSteve", "author_id": 787958, "author_profile": "https://Stackoverflow.com/users/787958", "pm_score": -1, "selected": false, "text": "<p>The way I got around this was to use some jQuery. The reason I did it this way was because A and B were percent widths.</p>\n\n<p>HTML:</p>\n\n<pre><code>&lt;div class=\"floatNoWrap\"&gt;\n &lt;div id=\"A\" style=\"float: left;\"&gt;\n Content A\n &lt;/div&gt;\n &lt;div id=\"B\" style=\"float: left;\"&gt;\n Content B\n &lt;/div&gt;\n &lt;div style=\"clear: both;\"&gt;&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>.floatNoWrap\n{\n width: 100%;\n height: 100%;\n}\n</code></pre>\n\n<p>jQuery:</p>\n\n<pre><code>$(\"[class~='floatNoWrap']\").each(function () {\n $(this).css(\"width\", $(this).outerWidth());\n});\n</code></pre>\n" }, { "answer_id": 30431460, "author": "Bruce Allen", "author_id": 834328, "author_profile": "https://Stackoverflow.com/users/834328", "pm_score": 0, "selected": false, "text": "<p>When user reduces window size horizontally and this causes floats to stack vertically, remove the floats and on the second div (that was a float) use margin-top: -123px (your value) and margin-left: 444px (your value) to position the divs as they appeared with floats.\nWhen done this way, when the window narrows, the right-side div stays in place and disappears when page is too narrow to include it. ... which (to me) is better than having the right-side div \"jump\" down below the left-side div when the browser window is narrowed by the user.</p>\n" }, { "answer_id": 43114964, "author": "Nebojsha", "author_id": 3801270, "author_profile": "https://Stackoverflow.com/users/3801270", "pm_score": 1, "selected": false, "text": "<p>Add this line to your floated element selector</p>\n\n<pre><code>.floated {\n float: left;\n ...\n box-sizing: border-box;\n}\n</code></pre>\n\n<p>It will prevent padding and borders to be added to width, so element always stay in row, even if you have eg. three elements with width of 33.33333%</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2908/" ]
I want to have two items on the same line using `float: left` for the item on the left. I have no problems achieving this alone. The problem is, I want the two items to **stay** on the same line *even when you resize the browser very small*. You know... like how it was with tables. The goal is to keep the item on the right from wrapping *no matter what*. How to I tell the browser using CSS that I would rather **stretch the containing `div`** than wrap it so the the `float: right;` div is below the `float: left;` `div`? what I want: ``` \ +---------------+ +------------------------/ | float: left; | | float: right; \ | | | / | | |content stretching \ Screen Edge | | |the div off the screen / <--- +---------------+ +------------------------\ / ```
Wrap your floating `<div>`s in a container `<div>` that uses this cross-browser min-width hack: ``` .minwidth { min-width:100px; width: auto !important; width: 100px; } ``` You *may* also need to set "overflow" but probably not. This works because: * The `!important` declaration, combined with `min-width` cause everything to stay on the same line in IE7+ * IE6 does not implement `min-width`, but it has a bug such that `width: 100px` overrides the `!important` declaration, causing the container width to be 100px.
266,026
<p>Just looking for the relevant documentation. An example is not necessary, but would be appreciated. </p> <p>We have a situation where we are having to create 100s of virtual directories manually, and it seems like automating this would be a good way to make the process more efficient for now. </p> <p>Perhaps next year we can rework the server environment to allow something more sane, such as URL rewriting (unfortunately this does not seem feasible in the current cycle of the web application). Isn't it great to inherit crap code?</p> <p>~ William Riley-Land</p>
[ { "answer_id": 266045, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 2, "selected": false, "text": "<p>NOT TESTED (from an old code base and written by a former contractor of mine)</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.DirectoryServices;\nusing System.IO;\n\nnamespace Common.DirectoryServices\n{\n public class IISManager\n {\n\n private string _webSiteID;\n\n public string WebSiteID\n {\n get { return _webSiteID; }\n set { _webSiteID = value; }\n }\n\n private string _strServerName;\n public string ServerName\n {\n get\n {\n return _strServerName;\n }\n set\n {\n _strServerName = value;\n }\n }\n\n private string _strVDirName;\n public string VDirName\n {\n get\n {\n return _strVDirName;\n }\n set\n {\n _strVDirName = value;\n }\n }\n\n private string _strPhysicalPath;\n public string PhysicalPath\n {\n get\n {\n return _strPhysicalPath;\n }\n set\n {\n _strPhysicalPath = value;\n }\n }\n\n private VDirectoryType _directoryType;\n public VDirectoryType DirectoryType\n {\n get\n {\n return _directoryType;\n }\n set\n {\n _directoryType = value;\n }\n }\n\n public enum VDirectoryType\n {\n FTP_DIR, WEB_IIS_DIR\n };\n\n public string CreateVDir()\n {\n System.DirectoryServices.DirectoryEntry oDE;\n System.DirectoryServices.DirectoryEntries oDC;\n System.DirectoryServices.DirectoryEntry oVirDir;\n //try\n // {\n //check whether to create FTP or Web IIS Virtual Directory\n if (this.DirectoryType == VDirectoryType.WEB_IIS_DIR)\n {\n oDE = new DirectoryEntry(\"IIS://\" +\n this._strServerName + \"/W3SVC/\" + _webSiteID + \"/Root\");\n }\n else\n {\n oDE = new DirectoryEntry(\"IIS://\" +\n this._strServerName + \"/MSFTPSVC/1/Root\");\n }\n\n //Get Default Web Site\n oDC = oDE.Children;\n\n //Add row\n oVirDir = oDC.Add(this._strVDirName,\n oDE.SchemaClassName.ToString());\n\n //Commit changes for Schema class File\n oVirDir.CommitChanges();\n\n //Create physical path if it does not exists\n if (!Directory.Exists(this._strPhysicalPath))\n {\n Directory.CreateDirectory(this._strPhysicalPath);\n }\n\n //Set virtual directory to physical path\n oVirDir.Properties[\"Path\"].Value = this._strPhysicalPath;\n\n //Set read access\n oVirDir.Properties[\"AccessRead\"][0] = true;\n\n //Create Application for IIS Application (as for ASP.NET)\n if (this.DirectoryType == VDirectoryType.WEB_IIS_DIR)\n {\n oVirDir.Invoke(\"AppCreate\", true);\n oVirDir.Properties[\"AppFriendlyName\"][0] = this._strVDirName;\n }\n\n //Save all the changes\n oVirDir.CommitChanges();\n\n return null;\n\n // }\n //catch (Exception exc)\n //{\n // return exc.Message.ToString();\n //}\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 266058, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 3, "selected": false, "text": "<p>It is easier to do it with <a href=\"http://techtasks.com/code/viewbookcode/696\" rel=\"nofollow noreferrer\">vbscript</a> too..</p>\n\n<pre><code>' This code creates a virtual directory in the default Web Site\n' ---------------------------------------------------------------\n' From the book \"Windows Server Cookbook\" by Robbie Allen\n' ISBN: 0-596-00633-0\n' ---------------------------------------------------------------\n\n' ------ SCRIPT CONFIGURATION ------\nstrComputer = \"rallen-w2k3\"\nstrVdirName = \"&lt;VdirName&gt;\" 'e.g. employees\nstrVdirPath = \"&lt;Path&gt;\" 'e.g. D:\\resumes\n' ------ END CONFIGURATION ---------\nset objIIS = GetObject(\"IIS://\" &amp; strComputer &amp; \"/W3SVC/1\")\nset objWebSite = objIIS.GetObject(\"IISWebVirtualDir\",\"Root\")\nset objVdir = objWebSite.Create(\"IISWebVirtualDir\",strVdirName)\nobjVdir.AccessRead = True\nobjVdir.Path = strVdirPath\nobjVdir.SetInfo\nWScript.Echo \"Successfully created virtual directory: \" &amp; objVdir.Name\n</code></pre>\n" }, { "answer_id": 266061, "author": "Turnkey", "author_id": 13144, "author_profile": "https://Stackoverflow.com/users/13144", "pm_score": 3, "selected": true, "text": "<p>Evidently you can also do this via PowerShell scripting:</p>\n\n<pre><code>$objIIS = new-object System.DirectoryServices.DirectoryEntry(\"IIS://localhost/W3SVC/1/Root\")\n$children = $objIIS.psbase.children\n$vDir = $children.add(\"NewFolder\",$objIIS.psbase.SchemaClassName)\n$vDir.psbase.CommitChanges()\n$vDir.Path = \"C:\\Documents and Settings\\blah\\Desktop\\new\"\n$vDir.defaultdoc = \"Default.htm\"\n$vDir.psbase.CommitChanges()\n</code></pre>\n\n<p>Here is the documentation: <a href=\"http://msdn.microsoft.com/en-us/library/ms524732.aspx\" rel=\"nofollow noreferrer\">MSDN - Using IIS Programmatic Administration</a></p>\n" }, { "answer_id": 266182, "author": "silverbugg", "author_id": 29650, "author_profile": "https://Stackoverflow.com/users/29650", "pm_score": 1, "selected": false, "text": "<p>The WIX installer tool creates a way to manage this - you would define them as a part of the installation build instructions. It make some work to get all of the project configured but after that maintenance should be a breeze... Here is an excerpt from the Tutorial on creating the Virtual Directory entries...</p>\n\n<h2>6.3 Web Directory</h2>\n\n<blockquote>\n <p>The WiX toolset has additional libraries that allow the installer to perform additional tasks like creating a web directory in IIS. To use these extensions, all you have to do is to link against the appropriate WiX library. The linker will include the necessary helper DLLs into the installation package automatically.</p>\n \n <p>First, we have to create the web site with the files belonging to it:</p>\n \n <p>&lt;Directory Id='TARGETDIR' Name='SourceDir'&gt;<br>\n &nbsp;&nbsp;&lt;Directory Id='ProgramFilesFolder' Name='PFiles'&gt;<br>\n &nbsp;&nbsp;&nbsp;&nbsp;&lt;Directory Id='InstallDir' Name='Acme'&gt;<br>\n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;Component Id='default.phpComponent' Guid='YOURGUID-5314-4689-83CA-9DB5C04D5742'&gt;<br>\n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;File Id='default.htmFile' Name='default.htm' LongName='default.htm' KeyPath='yes'\n DiskId='1' Source='default.htm' /&gt;<br>\n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/Component&gt;<br>\n &nbsp;&nbsp;&nbsp;&nbsp;&lt;/Directory&gt;<br>\n &nbsp;&nbsp;&lt;/Directory&gt;<br></p>\n \n <p>The next step is to create the virtual directory:</p>\n \n <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;Component Id='TestWebVirtualDirComponent' Guid='YOURGUID-6304-410E-A808-E3585379EADB'><br>\n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;WebVirtualDir Id='TestWebVirtualDir' Alias='Test' Directory='InstallDir' WebSite='DefaultWebSite'><br>\n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;WebApplication Id='TestWebApplication' Name='Test' /><br>\n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/WebVirtualDir><br>\n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/Component><br>\n &nbsp;&nbsp;&nbsp;&nbsp;&lt;/Directory><br></p>\n \n <p>Finally, create an entry to reference the web site:</p>\n \n <p>&nbsp;&nbsp;&lt;WebSite Id='DefaultWebSite' Description='Default Web Site'><br>\n &nbsp;&nbsp;&nbsp;&lt;WebAddress Id='AllUnassigned' Port='80' /><br>\n &nbsp;&nbsp;&lt;/WebSite><br></p>\n</blockquote>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17847/" ]
Just looking for the relevant documentation. An example is not necessary, but would be appreciated. We have a situation where we are having to create 100s of virtual directories manually, and it seems like automating this would be a good way to make the process more efficient for now. Perhaps next year we can rework the server environment to allow something more sane, such as URL rewriting (unfortunately this does not seem feasible in the current cycle of the web application). Isn't it great to inherit crap code? ~ William Riley-Land
Evidently you can also do this via PowerShell scripting: ``` $objIIS = new-object System.DirectoryServices.DirectoryEntry("IIS://localhost/W3SVC/1/Root") $children = $objIIS.psbase.children $vDir = $children.add("NewFolder",$objIIS.psbase.SchemaClassName) $vDir.psbase.CommitChanges() $vDir.Path = "C:\Documents and Settings\blah\Desktop\new" $vDir.defaultdoc = "Default.htm" $vDir.psbase.CommitChanges() ``` Here is the documentation: [MSDN - Using IIS Programmatic Administration](http://msdn.microsoft.com/en-us/library/ms524732.aspx)
266,028
<p>We are looking to provide two <strong>custom Platform switches</strong> (the <strong>platform dropdown</strong> in the configuration manager) for our projects <strong>in Visual Studio</strong>. </p> <p>For example one for 'Desktop' and one for 'Web'. The target build tasks then compile the code in a custom way based on the platform switch. We don't want to add to the Debug Release switch because we would need those for each Desktop and Web platforms.</p> <p>We found one way to attempt this, is to modify the .csproj file to add something like this</p> <pre><code>&lt;Platform Condition=" '$(Platform)' == '' "&gt;Desktop&lt;/Platform&gt; </code></pre> <p>and add propertygroups like,</p> <pre><code> &lt;PropertyGroup Condition=" '$(Platform)' == 'Web' "&gt; &lt;DefineConstants&gt;/define Web&lt;/DefineConstants&gt; &lt;PlatformTarget&gt;Web&lt;/PlatformTarget&gt; &lt;/PropertyGroup&gt; &lt;PropertyGroup Condition=" '$(Platform)' == 'Desktop' "&gt; &lt;DefineConstants&gt;/define Desktop&lt;/DefineConstants&gt; &lt;PlatformTarget&gt;Desktop&lt;/PlatformTarget&gt; &lt;/PropertyGroup&gt; </code></pre> <p>But still this doesn't work, and compiler throws an error</p> <p><em>Invalid option 'Desktop' for /platform; must be anycpu, x86, Itanium or x64</em></p> <p>So does it have to be one of those options and can't we add our custom platforms?</p> <p>Has anyone been able to do this? any pointers would be helpful.</p> <p>Update: Using DebugDesktop and ReleaseDesktop will make it more complicated for users. Because 'desktop' and 'web' are actually platforms and also there is ability to add new platforms in the dropdown (i.e. ), I believe 'platform' switch should be used for the exact same purpose.</p>
[ { "answer_id": 266137, "author": "Joel Lucsy", "author_id": 645, "author_profile": "https://Stackoverflow.com/users/645", "pm_score": -1, "selected": false, "text": "<p>Rename \"Debug\" and \"Release\" to \"Debug Desktop\" and \"Release Desktop\" and copy them into names \"Debug Web\" and \"Release Web\". Then set your constants up that way.</p>\n" }, { "answer_id": 266171, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 2, "selected": true, "text": "<p>You should be able to use the Configuration Manager dialog to create new platforms.</p>\n" }, { "answer_id": 3000019, "author": "Gordon", "author_id": 302104, "author_profile": "https://Stackoverflow.com/users/302104", "pm_score": 1, "selected": false, "text": "<p>I've recently asked the same question and it appears that with Visual Studio 2010 you can define your own project platforms. (See <a href=\"https://devblogs.microsoft.com/cppblog/printfhello-msbuildn/\" rel=\"nofollow noreferrer\">Link</a>). Unfortunately, we are still using 2008.</p>\n" }, { "answer_id": 6463259, "author": "aster.x", "author_id": 506499, "author_profile": "https://Stackoverflow.com/users/506499", "pm_score": 3, "selected": false, "text": "<p>May be this subject will be interesting for somebody after three years. I had similar difficulties with configuring build platforms and resolved them.</p>\n\n<p>The error you gave was thrown because the PlatformTarget property was set with Desctop, not because the Platform property. These two properties have a little bit different meaning. The first one really eventually instructs all participants of build process which process architecture should be utilized, while the second one allows customize build circumstances inside IDE. </p>\n\n<p>When project is created in the Visual Studio, the ProcessTarget property may be set by default with AnyCPU under PropertyGroups that have conditional restrictions like this \"<strong>'...|$(Platform)' == '...|AnyCPU'</strong>\". But it doesn't enforce you to do the same. The ProcessTarget property can easily be set with AnyCPU for Platform property having other values.</p>\n\n<p>Considering described above, your sample may looks like this:</p>\n\n<pre><code>&lt;PropertyGroup Condition=\" '$(Platform)' == 'Web' \"&gt;\n &lt;DefineConstants&gt;Web&lt;/DefineConstants&gt;\n &lt;PlatformTarget&gt;AnyCPU&lt;/PlatformTarget&gt;\n&lt;/PropertyGroup&gt;\n&lt;PropertyGroup Condition=\" '$(Platform)' == 'Desktop' \"&gt;\n &lt;DefineConstants&gt;Desktop&lt;/DefineConstants&gt;\n &lt;PlatformTarget&gt;AnyCPU&lt;/PlatformTarget&gt;\n&lt;/PropertyGroup&gt;\n</code></pre>\n\n<p>it must be working.</p>\n\n<p>Hope it's useful for you.</p>\n" }, { "answer_id": 31859223, "author": "GGirard", "author_id": 2242485, "author_profile": "https://Stackoverflow.com/users/2242485", "pm_score": 0, "selected": false, "text": "<p>Looking for this too... But according to <a href=\"https://msdn.microsoft.com/en-us/library/bb629394.aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/bb629394.aspx</a>, the only valid values for MSBuild engine are \"Any CPU\", \"x86\", and \"x64\".\nIs this customization really supported?</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1747/" ]
We are looking to provide two **custom Platform switches** (the **platform dropdown** in the configuration manager) for our projects **in Visual Studio**. For example one for 'Desktop' and one for 'Web'. The target build tasks then compile the code in a custom way based on the platform switch. We don't want to add to the Debug Release switch because we would need those for each Desktop and Web platforms. We found one way to attempt this, is to modify the .csproj file to add something like this ``` <Platform Condition=" '$(Platform)' == '' ">Desktop</Platform> ``` and add propertygroups like, ``` <PropertyGroup Condition=" '$(Platform)' == 'Web' "> <DefineConstants>/define Web</DefineConstants> <PlatformTarget>Web</PlatformTarget> </PropertyGroup> <PropertyGroup Condition=" '$(Platform)' == 'Desktop' "> <DefineConstants>/define Desktop</DefineConstants> <PlatformTarget>Desktop</PlatformTarget> </PropertyGroup> ``` But still this doesn't work, and compiler throws an error *Invalid option 'Desktop' for /platform; must be anycpu, x86, Itanium or x64* So does it have to be one of those options and can't we add our custom platforms? Has anyone been able to do this? any pointers would be helpful. Update: Using DebugDesktop and ReleaseDesktop will make it more complicated for users. Because 'desktop' and 'web' are actually platforms and also there is ability to add new platforms in the dropdown (i.e. ), I believe 'platform' switch should be used for the exact same purpose.
You should be able to use the Configuration Manager dialog to create new platforms.
266,082
<p>How do I tell if my application (compiled in Visual&nbsp;Studio&nbsp;2008 as <em>Any CPU</em>) is running as a 32-bit or 64-bit application?</p>
[ { "answer_id": 266084, "author": "Redwood", "author_id": 1512, "author_profile": "https://Stackoverflow.com/users/1512", "pm_score": 3, "selected": false, "text": "<p>I found this code from <a href=\"http://bytes.com/forum/thread525905.html\" rel=\"nofollow noreferrer\">Martijn Boven</a> that does the trick:</p>\n\n<pre><code>public static bool Is64BitMode() {\n return System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8;\n}\n</code></pre>\n" }, { "answer_id": 397695, "author": "Perica Zivkovic", "author_id": 31822, "author_profile": "https://Stackoverflow.com/users/31822", "pm_score": 7, "selected": true, "text": "<pre><code>if (IntPtr.Size == 8) \n{\n // 64 bit machine\n} \nelse if (IntPtr.Size == 4) \n{\n // 32 bit machine\n}\n</code></pre>\n" }, { "answer_id": 3461579, "author": "Sam", "author_id": 417602, "author_profile": "https://Stackoverflow.com/users/417602", "pm_score": 7, "selected": false, "text": "<p>If you're using <a href=\"http://en.wikipedia.org/wiki/.NET_Framework\" rel=\"noreferrer\">.NET</a> 4.0, it's a one-liner for the current process:</p>\n\n<pre><code>Environment.Is64BitProcess\n</code></pre>\n\n<p>Reference: <em><a href=\"http://msdn.microsoft.com/en-us/library/system.environment.is64bitprocess.aspx\" rel=\"noreferrer\">Environment.Is64BitProcess Property </a></em> (MSDN)</p>\n" }, { "answer_id": 7297127, "author": "Scott Ge", "author_id": 927204, "author_profile": "https://Stackoverflow.com/users/927204", "pm_score": 3, "selected": false, "text": "<p>This code sample from Microsoft All-In-One Code Framework can answer your question:</p>\n\n<p><a href=\"http://code.msdn.microsoft.com/CSPlatformDetector-e7a99806\" rel=\"nofollow\">Detect the process running platform in C# (CSPlatformDetector)</a></p>\n\n<blockquote>\n <p>The CSPlatformDetector code sample demonstrates the following tasks\n related to platform detection:</p>\n \n <ol>\n <li>Detect the name of the current operating system. <em>(e.g. \"Microsoft Windows 7 Enterprise\")</em></li>\n <li>Detect the version of the current operating system. <em>(e.g. \"Microsoft Windows NT 6.1.7600.0\")</em></li>\n <li>Determine whether the current operating system is a 64-bit operating system. </li>\n <li>Determine whether the current process is a 64-bit process. </li>\n <li>Determine whether an arbitrary process running on the system is 64-bit.</li>\n </ol>\n</blockquote>\n\n<p>If you just want to determine whether the currently running process is a 64-bit \nprocess, you can use the <a href=\"http://msdn.microsoft.com/en-us/library/system.environment.is64bitprocess.aspx\" rel=\"nofollow\">Environment.Is64BitProcess</a> property that is new in .NET \nFramework 4.</p>\n\n<p>And if you want to detect whether an arbitrary application running on the system \nis a 64-bit process, you need to determine the OS bitness, and if it is 64-bit, \ncall <code>IsWow64Process()</code> with the target process handle:</p>\n\n<pre><code>static bool Is64BitProcess(IntPtr hProcess)\n{\n bool flag = false;\n\n if (Environment.Is64BitOperatingSystem)\n {\n // On 64-bit OS, if a process is not running under Wow64 mode, \n // the process must be a 64-bit process.\n flag = !(NativeMethods.IsWow64Process(hProcess, out flag) &amp;&amp; flag);\n }\n\n return flag;\n}\n</code></pre>\n" }, { "answer_id": 45617262, "author": "Owen Pauling", "author_id": 1688439, "author_profile": "https://Stackoverflow.com/users/1688439", "pm_score": 0, "selected": false, "text": "<p>In .Net Standard you can use <code>System.Runtime.InteropServices.RuntimeInformation.OSArchitecture</code></p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
How do I tell if my application (compiled in Visual Studio 2008 as *Any CPU*) is running as a 32-bit or 64-bit application?
``` if (IntPtr.Size == 8) { // 64 bit machine } else if (IntPtr.Size == 4) { // 32 bit machine } ```
266,115
<p>The title is kind of obscure. What I want to know is if this is possible:</p> <pre><code>string typeName = &lt;read type name from somwhere&gt;; Type myType = Type.GetType(typeName); MyGenericClass&lt;myType&gt; myGenericClass = new MyGenericClass&lt;myType&gt;(); </code></pre> <p>Obviously, MyGenericClass is described as:</p> <pre><code>public class MyGenericClass&lt;T&gt; </code></pre> <p>Right now, the compiler complains that 'The type or namespace 'myType' could not be found." There has got to be a way to do this.</p>
[ { "answer_id": 266127, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 4, "selected": false, "text": "<p>Unfortunately no there is not. Generic arguments must be resolvable at Compile time as either 1) a valid type or 2) another generic parameter. There is no way to create generic instances based on runtime values without the big hammer of using reflection.</p>\n" }, { "answer_id": 266282, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 9, "selected": true, "text": "<p>You can't do this without reflection. However, you <em>can</em> do it with reflection. Here's a complete example:</p>\n\n<pre><code>using System;\nusing System.Reflection;\n\npublic class Generic&lt;T&gt;\n{\n public Generic()\n {\n Console.WriteLine(\"T={0}\", typeof(T));\n }\n}\n\nclass Test\n{\n static void Main()\n {\n string typeName = \"System.String\";\n Type typeArgument = Type.GetType(typeName);\n\n Type genericClass = typeof(Generic&lt;&gt;);\n // MakeGenericType is badly named\n Type constructedClass = genericClass.MakeGenericType(typeArgument);\n\n object created = Activator.CreateInstance(constructedClass);\n }\n}\n</code></pre>\n\n<p>Note: if your generic class accepts multiple types, you must include the commas when you omit the type names, for example:</p>\n\n<pre><code>Type genericClass = typeof(IReadOnlyDictionary&lt;,&gt;);\nType constructedClass = genericClass.MakeGenericType(typeArgument1, typeArgument2);\n</code></pre>\n" }, { "answer_id": 26368508, "author": "Chris Marisic", "author_id": 37055, "author_profile": "https://Stackoverflow.com/users/37055", "pm_score": 2, "selected": false, "text": "<p>Some additional how to run with scissors code. Suppose you have a class similar to</p>\n\n<pre><code>public class Encoder() {\npublic void Markdown(IEnumerable&lt;FooContent&gt; contents) { do magic }\npublic void Markdown(IEnumerable&lt;BarContent&gt; contents) { do magic2 }\n}\n</code></pre>\n\n<p>Suppose at runtime you have a <strong>FooContent</strong> </p>\n\n<p><em>If</em> you were able to bind at compile time you would want </p>\n\n<pre><code>var fooContents = new List&lt;FooContent&gt;(fooContent)\nnew Encoder().Markdown(fooContents)\n</code></pre>\n\n<p><em>However</em> you cannot do this at runtime. To do this at runtime you would do along the lines of:</p>\n\n<pre><code>var listType = typeof(List&lt;&gt;).MakeGenericType(myType);\nvar dynamicList = Activator.CreateInstance(listType);\n((IList)dynamicList).Add(fooContent);\n</code></pre>\n\n<p>To dynamically invoke <code>Markdown(IEnumerable&lt;FooContent&gt; contents)</code></p>\n\n<pre><code>new Encoder().Markdown( (dynamic) dynamicList)\n</code></pre>\n\n<p>Note the usage of <code>dynamic</code> in the method call. At runtime <code>dynamicList</code> will be <code>List&lt;FooContent&gt;</code> (additionally also being <code>IEnumerable&lt;FooContent&gt;</code>) since even usage of dynamic is still rooted to a strongly typed language the run time binder will select the appropriate <code>Markdown</code> method. If there is no exact type matches, it will look for an object parameter method and if neither match a runtime binder exception will be raised alerting that no method matches.</p>\n\n<p>The obvious draw back to this approach is a huge loss of type safety at compile time. Nevertheless code along these lines will let you operate in a very dynamic sense that at runtime is still fully typed as you expect it to be.</p>\n" }, { "answer_id": 30814072, "author": "Master P", "author_id": 5005127, "author_profile": "https://Stackoverflow.com/users/5005127", "pm_score": 2, "selected": false, "text": "<p>My requirements were slightly different, but will hopefully help someone. I needed to read type from a config and instantiate the generic type dynamically.</p>\n\n<pre><code>namespace GenericTest\n{\n public class Item\n {\n }\n}\n\nnamespace GenericTest\n{\n public class GenericClass&lt;T&gt;\n {\n }\n}\n</code></pre>\n\n<p>Finally, here is how you call it. <a href=\"https://msdn.microsoft.com/en-us/library/w3f99sx1(v=vs.110).aspx\" rel=\"nofollow\">Define the type with a backtick</a>.</p>\n\n<pre><code>var t = Type.GetType(\"GenericTest.GenericClass`1[[GenericTest.Item, GenericTest]], GenericTest\");\nvar a = Activator.CreateInstance(t);\n</code></pre>\n" }, { "answer_id": 53961816, "author": "Todd Skelton", "author_id": 1212994, "author_profile": "https://Stackoverflow.com/users/1212994", "pm_score": 0, "selected": false, "text": "<p>If you know what types will be passed you can do this without reflection. A switch statement would work. Obviously, this would only work in a limited number of cases, but it'll be much faster than reflection.</p>\n\n<pre><code>public class Type1 { }\n\npublic class Type2 { }\n\npublic class Generic&lt;T&gt; { }\n\npublic class Program\n{\n public static void Main()\n {\n var typeName = nameof(Type1);\n\n switch (typeName)\n {\n case nameof(Type1):\n var type1 = new Generic&lt;Type1&gt;();\n // do something\n break;\n case nameof(Type2):\n var type2 = new Generic&lt;Type2&gt;();\n // do something\n break;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 56587641, "author": "EGN", "author_id": 1234374, "author_profile": "https://Stackoverflow.com/users/1234374", "pm_score": 0, "selected": false, "text": "<p>In this snippet I want to show how to create and use a dynamically created list. For example, I'm adding to the dynamic list here.</p>\n\n<pre><code>void AddValue&lt;T&gt;(object targetList, T valueToAdd)\n{\n var addMethod = targetList.GetType().GetMethod(\"Add\");\n addMethod.Invoke(targetList, new[] { valueToAdd } as object[]);\n}\n\nvar listType = typeof(List&lt;&gt;).MakeGenericType(new[] { dynamicType }); // dynamicType is the type you want\nvar list = Activator.CreateInstance(listType);\n\nAddValue(list, 5);\n</code></pre>\n\n<p>Similarly you can invoke any other method on the list.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9209/" ]
The title is kind of obscure. What I want to know is if this is possible: ``` string typeName = <read type name from somwhere>; Type myType = Type.GetType(typeName); MyGenericClass<myType> myGenericClass = new MyGenericClass<myType>(); ``` Obviously, MyGenericClass is described as: ``` public class MyGenericClass<T> ``` Right now, the compiler complains that 'The type or namespace 'myType' could not be found." There has got to be a way to do this.
You can't do this without reflection. However, you *can* do it with reflection. Here's a complete example: ``` using System; using System.Reflection; public class Generic<T> { public Generic() { Console.WriteLine("T={0}", typeof(T)); } } class Test { static void Main() { string typeName = "System.String"; Type typeArgument = Type.GetType(typeName); Type genericClass = typeof(Generic<>); // MakeGenericType is badly named Type constructedClass = genericClass.MakeGenericType(typeArgument); object created = Activator.CreateInstance(constructedClass); } } ``` Note: if your generic class accepts multiple types, you must include the commas when you omit the type names, for example: ``` Type genericClass = typeof(IReadOnlyDictionary<,>); Type constructedClass = genericClass.MakeGenericType(typeArgument1, typeArgument2); ```
266,116
<p>How do you programmatically obtain a picture of a .Net control?</p>
[ { "answer_id": 266139, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": true, "text": "<p>There's a method on every control called <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.control.drawtobitmap.aspx\" rel=\"noreferrer\">DrawToBitmap</a>. You don't need to p/invoke to do this.</p>\n\n<pre><code>Control c = new TextBox();\nSystem.Drawing.Bitmap bmp = new System.Drawing.Bitmap(c.Width, c.Height);\nc.DrawToBitmap(bmp, c.ClientRectangle);\n</code></pre>\n" }, { "answer_id": 266142, "author": "Alan", "author_id": 31223, "author_profile": "https://Stackoverflow.com/users/31223", "pm_score": 2, "selected": false, "text": "<p>For WinForms controls that support it, there is a method in the System.Windows.Forms.Control class:</p>\n\n<pre><code>public void DrawToBitmap(Bitmap bitmap, Rectangle targetBounds);\n</code></pre>\n\n<p>This does not work with all controls, however. Third party component vendors have more comprehensive solutions.</p>\n" }, { "answer_id": 266146, "author": "Joey", "author_id": 25962, "author_profile": "https://Stackoverflow.com/users/25962", "pm_score": 3, "selected": false, "text": "<p>You can get a picture of a .NET control programmatically pretty easily using the <strong><em>DrawToBitmap</em></strong> method of the Control class starting in .NET 2.0 </p>\n\n<p>Here is a sample in VB</p>\n\n<pre><code> Dim formImage As New Bitmap(\"C:\\File.bmp\")\n Me.DrawToBitmap(formImage, Me.Bounds)\n</code></pre>\n\n<p>And here it is in C#:</p>\n\n<pre><code> Bitmap formImage = New Bitmap(\"C:\\File.bmp\")\n this.DrawToBitmap(formImage, this.Bounds)\n</code></pre>\n" }, { "answer_id": 266165, "author": "Nick", "author_id": 26161, "author_profile": "https://Stackoverflow.com/users/26161", "pm_score": 1, "selected": false, "text": "<p>if it's not on the control you're trying to do, you can usually cast it to the base Control class and call the DrawToBitmap method there.</p>\n" }, { "answer_id": 266174, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.drawtobitmap\" rel=\"nofollow noreferrer\">Control.DrawToBitmap</a> will let you draw most controls to a bitmap. This does not work with RichTextBox and some others.<br></p>\n\n<p>If you want to capture these, or a control that has one of them, then you need to do PInvoke like described in this CodeProject article: <a href=\"http://www.codeproject.com/KB/graphics/imagecapture.aspx\" rel=\"nofollow noreferrer\">Image Capture</a><br></p>\n\n<p>Take care that some of these methods will capture whatever is on the screen, so if you have another window covering your control you will get that instead. </p>\n" }, { "answer_id": 6293657, "author": "R Muruganandhan", "author_id": 791012, "author_profile": "https://Stackoverflow.com/users/791012", "pm_score": 1, "selected": false, "text": "\n\n<pre class=\"lang-vb prettyprint-override\"><code>Panel1.Dock = DockStyle.None ' If Panel Dockstyle is in Fill mode\nPanel1.Width = 5000 ' Original Size without scrollbar\nPanel1.Height = 5000 ' Original Size without scrollbar\n\nDim bmp As New Bitmap(Me.Panel1.Width, Me.Panel1.Height)\nMe.Panel1.DrawToBitmap(bmp, New Rectangle(0, 0, Me.Panel1.Width, Me.Panel1.Height))\n'Me.Panel1.DrawToBitmap(bmp, Panel1.ClientRectangle)\nbmp.Save(\"C:\\panel.jpg\", System.Drawing.Imaging.ImageFormat.Jpeg)\n\nPanel1.Dock = DockStyle.Fill\n</code></pre>\n\n<p><strong>Note:</strong> Its working fine</p>\n" }, { "answer_id": 16408849, "author": "Mark Lakata", "author_id": 364818, "author_profile": "https://Stackoverflow.com/users/364818", "pm_score": 2, "selected": false, "text": "<p>This is how to do it for an entire <code>Form</code>, not just the Client area (which doesn't have the title bar and other dressing)</p>\n\n<pre><code> Rectangle r = this.Bounds;\n r.Offset(-r.X,-r.Y);\n Bitmap bitmap = new Bitmap(r.Width,r.Height);\n this.DrawToBitmap(bitmap, r);\n Clipboard.SetImage(bitmap);\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34787/" ]
How do you programmatically obtain a picture of a .Net control?
There's a method on every control called [DrawToBitmap](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.drawtobitmap.aspx). You don't need to p/invoke to do this. ``` Control c = new TextBox(); System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(c.Width, c.Height); c.DrawToBitmap(bmp, c.ClientRectangle); ```
266,123
<p>Maybe I should further qualify this - Is there a way to specify which direction a ComboBox will open without copying and pasting the entire ComboBox class and ripping out the code where it determines which direction it will open in...</p> <p>I'm my specific case - I need it to open upwards - always.</p> <p>UPDATE: You can't fix this by subclassing it because the function that handles the direction of the opening is:</p> <pre><code>private function displayDropdown(show:Boolean, trigger:Event = null):void </code></pre> <p>And that bad boy uses a fair amount of private variables which my subclass wouldn't have access to...</p>
[ { "answer_id": 266194, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 0, "selected": false, "text": "<p>I doubt it - you'd need to subclass the control (which isn't <em>that</em> big a deal.)</p>\n\n<p>Maybe you could mess with the real estate so it's placed in such a fashion (e.g. crowded into the lower right corner) that up is naturally coerced?</p>\n" }, { "answer_id": 266280, "author": "Dave DuPlantis", "author_id": 8174, "author_profile": "https://Stackoverflow.com/users/8174", "pm_score": 0, "selected": false, "text": "<p>I would recommend checking out <a href=\"http://www.typeoneerror.com/forcing-combobox-component-open-direction-in-flex/\" rel=\"nofollow noreferrer\">this post</a>. Yes, you do have to grab the ComboBox code and modify it, but at least now you have an idea where the modifications need to go.</p>\n" }, { "answer_id": 268915, "author": "Mitch Haile", "author_id": 28807, "author_profile": "https://Stackoverflow.com/users/28807", "pm_score": 3, "selected": true, "text": "<p>If you build up the Menu object yourself, you can place the menu anywhere you want by simply setting the x,y coordinates of the menu object. You'll need to calculate those coordinates, but you might be able to do this easily without subclassing ComboBox.</p>\n\n<p>I am doing something similar with PopUpButton; you might find it easier to work with PopUpButton. This is based on real code from my current project:</p>\n\n<pre><code>private function initMenu(): void {\n var m:Menu = new Menu();\n m.dataProvider = theMenuData;\n m.addEventListener(MenuEvent.ITEM_CLICK, menuClick);\n m.showRoot = false;\n // m.x = ... &lt;-- probably don't need to tweak this.\n // m.y = ... &lt;-- this is really the interesting one :-)\n theMenu.popUp = m;\n}\n&lt;mx:PopUpButton id=\"theMenu\" creationComplete=\"initMenu()\" ... /&gt;\n</code></pre>\n\n<p>BTW, to get the PopUpButton to act more like I wanted it (always popup, no matter where the click), setting openAlways=true in the MXML works like a charm.</p>\n" }, { "answer_id": 910802, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You could set the MaxDropDownHeight, if you set it big enough Windows will automatically set the direction upwards.</p>\n" }, { "answer_id": 3391504, "author": "newtriks", "author_id": 409023, "author_profile": "https://Stackoverflow.com/users/409023", "pm_score": 0, "selected": false, "text": "<p>This irritated me no end. I have uploaded a solution, its a simple Class that extends the PopUpButton and removes the logic of stage bounds detection as it failed 50% of the time anyway. My code just allows you to simply specify whether you want to open the menu up or down:</p>\n\n<p><a href=\"http://gist.github.com/505255\" rel=\"nofollow noreferrer\">http://gist.github.com/505255</a></p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3435/" ]
Maybe I should further qualify this - Is there a way to specify which direction a ComboBox will open without copying and pasting the entire ComboBox class and ripping out the code where it determines which direction it will open in... I'm my specific case - I need it to open upwards - always. UPDATE: You can't fix this by subclassing it because the function that handles the direction of the opening is: ``` private function displayDropdown(show:Boolean, trigger:Event = null):void ``` And that bad boy uses a fair amount of private variables which my subclass wouldn't have access to...
If you build up the Menu object yourself, you can place the menu anywhere you want by simply setting the x,y coordinates of the menu object. You'll need to calculate those coordinates, but you might be able to do this easily without subclassing ComboBox. I am doing something similar with PopUpButton; you might find it easier to work with PopUpButton. This is based on real code from my current project: ``` private function initMenu(): void { var m:Menu = new Menu(); m.dataProvider = theMenuData; m.addEventListener(MenuEvent.ITEM_CLICK, menuClick); m.showRoot = false; // m.x = ... <-- probably don't need to tweak this. // m.y = ... <-- this is really the interesting one :-) theMenu.popUp = m; } <mx:PopUpButton id="theMenu" creationComplete="initMenu()" ... /> ``` BTW, to get the PopUpButton to act more like I wanted it (always popup, no matter where the click), setting openAlways=true in the MXML works like a charm.
266,168
<p>Can someone post a simple example of starting two (Object Oriented) threads in C++. </p> <p>I'm looking for actual C++ thread objects that I can extend run methods on (or something similar) as opposed to calling a C-style thread library.</p> <p>I left out any OS specific requests in the hopes that whoever replied would reply with cross platform libraries to use. I'm just making that explicit now.</p>
[ { "answer_id": 266180, "author": "LorenzCK", "author_id": 3118, "author_profile": "https://Stackoverflow.com/users/3118", "pm_score": 3, "selected": false, "text": "<p>It largely depends on the library you decide to use. For instance, if you use the <a href=\"https://en.wikipedia.org/wiki/WxWidgets\" rel=\"nofollow noreferrer\">wxWidgets</a> library, the creation of a thread would look like this:</p>\n<pre><code>class RThread : public wxThread {\n\npublic:\n RThread()\n : wxThread(wxTHREAD_JOINABLE){\n }\nprivate:\n RThread(const RThread &amp;copy);\n\npublic:\n void *Entry(void){\n //Do...\n\n return 0;\n }\n\n};\n\nwxThread *CreateThread() {\n //Create thread\n wxThread *_hThread = new RThread();\n\n //Start thread\n _hThread-&gt;Create();\n _hThread-&gt;Run();\n\n return _hThread;\n}\n</code></pre>\n<p>If your main thread calls the CreateThread method, you'll create a new thread that will start executing the code in your &quot;Entry&quot; method. You'll have to keep a reference to the thread in most cases to join or stop it.</p>\n<p>More information is in the <a href=\"http://docs.wxwidgets.org/stable/wx_wxthread.html#wxthread\" rel=\"nofollow noreferrer\">wxThread documentation</a>.</p>\n" }, { "answer_id": 266198, "author": "Edward Kmett", "author_id": 34707, "author_profile": "https://Stackoverflow.com/users/34707", "pm_score": 6, "selected": false, "text": "<p>Well, technically any such object will wind up being built over a C-style thread library because C++ only just specified a stock <a href=\"http://en.cppreference.com/w/cpp/thread/thread\" rel=\"nofollow noreferrer\"><code>std::thread</code></a> model in <a href=\"https://en.wikipedia.org/wiki/C%2B%2B11\" rel=\"nofollow noreferrer\">C++0x</a>, which was just nailed down and hasn't yet been implemented.</p>\n<p>The problem is somewhat systemic. Technically the existing C++ memory model isn't strict enough to allow for well-defined semantics for all of the 'happens before' cases. <a href=\"https://en.wikipedia.org/wiki/Boehm_garbage_collector\" rel=\"nofollow noreferrer\">Hans Boehm</a> wrote an paper on the topic a while back and was instrumental in hammering out the C++0x standard on the topic.</p>\n<p><em><a href=\"http://www.hpl.hp.com/techreports/2004/HPL-2004-209.html\" rel=\"nofollow noreferrer\">Threads Cannot be Implemented as a Library</a></em></p>\n<p>That said, there are several cross-platform thread C++ libraries that work just fine in practice. The Intel thread building blocks contains a <em>tbb::thread</em> object that closely approximates the C++0x standard and <a href=\"https://en.wikipedia.org/wiki/Boost_%28C%2B%2B_libraries%29\" rel=\"nofollow noreferrer\">Boost</a> has a <em>boost::thread</em> library that does the same.</p>\n<ul>\n<li><p><em><a href=\"http://www.threadingbuildingblocks.org/\" rel=\"nofollow noreferrer\">oneAPI Threading Building Blocks</a></em></p>\n</li>\n<li><p><em><a href=\"http://www.boost.org/doc/libs/1_37_0/doc/html/thread.html\" rel=\"nofollow noreferrer\">Chapter 19. Thread</a></em> (Boost documentation)</p>\n</li>\n</ul>\n<p>Using <em>boost::thread</em>, you'd get something like:</p>\n<pre><code>#include &lt;boost/thread.hpp&gt;\n\nvoid task1() {\n // do stuff\n}\n\nvoid task2() {\n // do stuff\n}\n\nint main (int argc, char ** argv) {\n using namespace boost;\n thread thread_1 = thread(task1);\n thread thread_2 = thread(task2);\n\n // do other stuff\n thread_2.join();\n thread_1.join();\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 11229853, "author": "MasterMastic", "author_id": 825637, "author_profile": "https://Stackoverflow.com/users/825637", "pm_score": 10, "selected": true, "text": "<p>Create a function that you want the thread to execute, for example:</p>\n<pre><code>void task1(std::string msg)\n{\n std::cout &lt;&lt; &quot;task1 says: &quot; &lt;&lt; msg;\n}\n</code></pre>\n<p>Now create the <code>thread</code> object that will ultimately invoke the function above like so:</p>\n<pre><code>std::thread t1(task1, &quot;Hello&quot;);\n</code></pre>\n<p>(You need to <code>#include &lt;thread&gt;</code> to access the <code>std::thread</code> class.)</p>\n<p>The constructor's first argument is the function the thread will execute, followed by the function's parameters. The thread is automatically started upon construction.</p>\n<p>If later on you want to wait for the thread to be done executing the function, call:</p>\n<pre><code>t1.join();\n</code></pre>\n<p>(Joining means that the thread who invoked the new thread will wait for the new thread to finish execution, before it will continue its own execution.)</p>\n<hr />\n<h2>The Code</h2>\n<pre><code>#include &lt;string&gt;\n#include &lt;iostream&gt;\n#include &lt;thread&gt;\n\nusing namespace std;\n\n// The function we want to execute on the new thread.\nvoid task1(string msg)\n{\n cout &lt;&lt; &quot;task1 says: &quot; &lt;&lt; msg;\n}\n\nint main()\n{\n // Constructs the new thread and runs it. Does not block execution.\n thread t1(task1, &quot;Hello&quot;);\n\n // Do other things...\n\n // Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.\n t1.join();\n}\n</code></pre>\n<p><a href=\"http://en.cppreference.com/w/cpp/thread/thread\" rel=\"noreferrer\">More information about std::thread here</a></p>\n<ul>\n<li><em>On GCC, compile with <code>-std=c++0x -pthread</code>.</em></li>\n<li><em>This should work for any operating-system, granted your compiler supports this (<a href=\"https://en.wikipedia.org/wiki/C%2B%2B11\" rel=\"noreferrer\">C++11</a>) feature.</em></li>\n</ul>\n" }, { "answer_id": 16091180, "author": "Hohenheimsenberg", "author_id": 560678, "author_profile": "https://Stackoverflow.com/users/560678", "pm_score": 5, "selected": false, "text": "<p>There is also a <a href=\"https://en.wikipedia.org/wiki/POSIX\" rel=\"nofollow noreferrer\">POSIX</a> library for POSIX operating systems.</p>\n<p><a href=\"http://en.wikipedia.org/wiki/POSIX\" rel=\"nofollow noreferrer\">Check</a> for compatibility:</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;pthread.h&gt;\n#include &lt;iostream&gt;\n\nvoid *task(void *argument){\n char* msg;\n msg = (char*)argument;\n std::cout &lt;&lt; msg &lt;&lt; std::endl;\n}\n\nint main(){\n pthread_t thread1, thread2;\n int i1, i2;\n i1 = pthread_create(&amp;thread1, NULL, task, (void*) &quot;thread 1&quot;);\n i2 = pthread_create(&amp;thread2, NULL, task, (void*) &quot;thread 2&quot;);\n\n pthread_join(thread1, NULL);\n pthread_join(thread2, NULL);\n return 0;\n}\n</code></pre>\n<p>Compile with <em>-lpthread</em>.</p>\n<p><em><a href=\"https://en.wikipedia.org/wiki/Pthreads\" rel=\"nofollow noreferrer\">POSIX Threads</a></em></p>\n" }, { "answer_id": 44452404, "author": "Caner", "author_id": 448625, "author_profile": "https://Stackoverflow.com/users/448625", "pm_score": 5, "selected": false, "text": "<pre><code>#include &lt;thread&gt;\n#include &lt;iostream&gt;\n#include &lt;vector&gt;\nusing namespace std;\n\nvoid doSomething(int id) {\n cout &lt;&lt; id &lt;&lt; \"\\n\";\n}\n\n/**\n * Spawns n threads\n */\nvoid spawnThreads(int n)\n{\n std::vector&lt;thread&gt; threads(n);\n // spawn n threads:\n for (int i = 0; i &lt; n; i++) {\n threads[i] = thread(doSomething, i + 1);\n }\n\n for (auto&amp; th : threads) {\n th.join();\n }\n}\n\nint main()\n{\n spawnThreads(10);\n}\n</code></pre>\n" }, { "answer_id": 46286270, "author": "livingtech", "author_id": 18961, "author_profile": "https://Stackoverflow.com/users/18961", "pm_score": 4, "selected": false, "text": "<p>When searching for an example of a C++ class that calls one of its own instance methods in a new thread, this question comes up, but we were not able to use any of these answers that way. Here's an example that does that:</p>\n\n<p>Class.h</p>\n\n<pre><code>class DataManager\n{\npublic:\n bool hasData;\n void getData();\n bool dataAvailable();\n};\n</code></pre>\n\n<p>Class.cpp</p>\n\n<pre><code>#include \"DataManager.h\"\n\nvoid DataManager::getData()\n{\n // perform background data munging\n hasData = true;\n // be sure to notify on the main thread\n}\n\nbool DataManager::dataAvailable()\n{\n if (hasData)\n {\n return true;\n }\n else\n {\n std::thread t(&amp;DataManager::getData, this);\n t.detach(); // as opposed to .join, which runs on the current thread\n }\n}\n</code></pre>\n\n<p>Note that this example doesn't get into mutex or locking.</p>\n" }, { "answer_id": 47171594, "author": "Daksh Gupta", "author_id": 5662469, "author_profile": "https://Stackoverflow.com/users/5662469", "pm_score": 4, "selected": false, "text": "<p>Unless one wants a separate function in the global namespace, we can use lambda functions for creating threads.</p>\n<p>One of the major advantage of creating a thread using lambda is that we don't need to pass local parameters as an argument list. We can use the capture list for the same and the closure property of lambda will take care of the lifecycle.</p>\n<p>Here is sample code:</p>\n<pre><code>int main() {\n int localVariable = 100;\n\n thread th { [=]() {\n cout &lt;&lt; &quot;The value of local variable =&gt; &quot; &lt;&lt; localVariable &lt;&lt; endl;\n }};\n\n th.join();\n\n return 0;\n}\n</code></pre>\n<p>By far, I've found C++ lambdas to be the best way of creating threads especially for simpler thread functions.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2112692/" ]
Can someone post a simple example of starting two (Object Oriented) threads in C++. I'm looking for actual C++ thread objects that I can extend run methods on (or something similar) as opposed to calling a C-style thread library. I left out any OS specific requests in the hopes that whoever replied would reply with cross platform libraries to use. I'm just making that explicit now.
Create a function that you want the thread to execute, for example: ``` void task1(std::string msg) { std::cout << "task1 says: " << msg; } ``` Now create the `thread` object that will ultimately invoke the function above like so: ``` std::thread t1(task1, "Hello"); ``` (You need to `#include <thread>` to access the `std::thread` class.) The constructor's first argument is the function the thread will execute, followed by the function's parameters. The thread is automatically started upon construction. If later on you want to wait for the thread to be done executing the function, call: ``` t1.join(); ``` (Joining means that the thread who invoked the new thread will wait for the new thread to finish execution, before it will continue its own execution.) --- The Code -------- ``` #include <string> #include <iostream> #include <thread> using namespace std; // The function we want to execute on the new thread. void task1(string msg) { cout << "task1 says: " << msg; } int main() { // Constructs the new thread and runs it. Does not block execution. thread t1(task1, "Hello"); // Do other things... // Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution. t1.join(); } ``` [More information about std::thread here](http://en.cppreference.com/w/cpp/thread/thread) * *On GCC, compile with `-std=c++0x -pthread`.* * *This should work for any operating-system, granted your compiler supports this ([C++11](https://en.wikipedia.org/wiki/C%2B%2B11)) feature.*
266,184
<p>I'm trying to be responsible with my "DOM" references in this little Flash 8/AS2 project.</p> <p>What has become increasingly frustrating is obtaining references to other movie clips and objects. For example, currently my code to access the submit button of a form looks something like this</p> <pre><code>var b:Button = _level0.instance4.submitBtn; </code></pre> <p>I was hoping there was an instance-retrieval method for AS2 similar to AS3's <code>MovieClip.getChildByName()</code> or even Javascript's <code>document.getElementById()</code>. Because hard-coding the names of these anonymous instances (like <code>instance4</code> in the above) just feel really, really dirty.</p> <p>But, I can't find anything of the sort at <a href="http://flash-reference.icod.de/" rel="nofollow noreferrer">this AS2 Reference</a>.</p>
[ { "answer_id": 266604, "author": "moritzstefaner", "author_id": 23069, "author_profile": "https://Stackoverflow.com/users/23069", "pm_score": 2, "selected": true, "text": "<p>If the MovieClip was placed on the stage in the Flash IDE, you can give it a proper instance name in the properties panel.</p>\n\n<p>If it was dynamically added, you can also give it a name, and additionally store a reference:</p>\n\n<pre><code>var my_MC=createEmptyMovieClip(\"instanceName\", depth);\n</code></pre>\n\n<p>In either case, you can then adress them with <code>_parentClip.instanceName</code> or <code>my_MC.</code></p>\n" }, { "answer_id": 266912, "author": "Luke", "author_id": 21406, "author_profile": "https://Stackoverflow.com/users/21406", "pm_score": 0, "selected": false, "text": "<p>You could just write it yourself (code not tested but you get the idea):</p>\n\n<pre><code>MovieClip.prototype.getElementByName = function(name : String) : Object\n{\n var s : String;\n var mc : Movieclip = null;\n\n for( s in this )\n {\n if( this[s] instanceof MovieClip )\n {\n if( s == name )\n {\n mc = this[ s ];\n break;\n }\n\n mc = this[s].getElementByName( name );\n }\n }\n\n return( mc );\n}\n</code></pre>\n" }, { "answer_id": 279989, "author": "user36432", "author_id": 36432, "author_profile": "https://Stackoverflow.com/users/36432", "pm_score": 1, "selected": false, "text": "<p>There are a couple ways you can do this. The easiest way is to use Array notation. Your previous example, which looks like this:</p>\n\n<pre><code>var b:Button = _root.instance4.submitBtn;\n</code></pre>\n\n<p>would look like this in Array notation:</p>\n\n<pre><code>var b:Button = _root[\"instance4\"].submitBtn;\n</code></pre>\n\n<p>So if you wanted to loop through 100 buttons already created and set the alpha to 0:</p>\n\n<pre><code>for( var i:Number = 0; i &lt; 101; i++)\n{\n var button:Button = _root[\"instance\"+i].submitBtn;\n button._alpha = 0;\n}\n</code></pre>\n\n<p>You can also use eval(\"instance4\") to do the same thing, but I'm a little foggy on the scoping issues involved.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8815/" ]
I'm trying to be responsible with my "DOM" references in this little Flash 8/AS2 project. What has become increasingly frustrating is obtaining references to other movie clips and objects. For example, currently my code to access the submit button of a form looks something like this ``` var b:Button = _level0.instance4.submitBtn; ``` I was hoping there was an instance-retrieval method for AS2 similar to AS3's `MovieClip.getChildByName()` or even Javascript's `document.getElementById()`. Because hard-coding the names of these anonymous instances (like `instance4` in the above) just feel really, really dirty. But, I can't find anything of the sort at [this AS2 Reference](http://flash-reference.icod.de/).
If the MovieClip was placed on the stage in the Flash IDE, you can give it a proper instance name in the properties panel. If it was dynamically added, you can also give it a name, and additionally store a reference: ``` var my_MC=createEmptyMovieClip("instanceName", depth); ``` In either case, you can then adress them with `_parentClip.instanceName` or `my_MC.`
266,196
<p>I'm looking at having certain users access one database and other users accessing another database based on the company they belong to. What would be the best way to handle the connection strings and make sure the user connects to the right db when they login?</p> <p>Thanks for any ideas.</p>
[ { "answer_id": 266207, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 2, "selected": false, "text": "<p>Have a database table that stores the connection info for each user. Maybe something like the <a href=\"http://msdn.microsoft.com/en-us/library/aa479030.aspx\" rel=\"nofollow noreferrer\">Provider Model</a> would be useful?</p>\n" }, { "answer_id": 266211, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": "<p>I would use a dynamic connection string builder, and a master Database that mapped user accounts to other databases.</p>\n\n<p>Instead of storing all those connection strings, I'd use my connection string builder method to create the connections as needed based on info from the master. I'd also use Windows Authentication, so as to avoid storing passwords in your database.</p>\n" }, { "answer_id": 266225, "author": "GeekyMonkey", "author_id": 29900, "author_profile": "https://Stackoverflow.com/users/29900", "pm_score": 4, "selected": true, "text": "<p>In Web.Config or App.Config </p>\n\n<pre><code>&lt;connectionStrings&gt;\n &lt;add name=\"ConnectionForDudes\" providerName=\"System.Data.SqlClient\"\n connectionString=\"Data Source=___MALECONNECTIONHERE___\"/&gt;\n &lt;add name=\"ConnectionForChicks\" providerName=\"System.Data.SqlClient\"\n connectionString=\"Data Source=___FEMALECONNECTIONHERE___\"/&gt;\n&lt;/connectionStrings&gt;\n</code></pre>\n\n<p>When it's time to open the database, you get your connection string this way:</p>\n\n<pre><code>bool UserIsMale = true;\nstring ConnectionStringName = \"ConnectionFor\" + UserIsMale ? \"Dudes\" : \"Chicks\";\nstring ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString;\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34571/" ]
I'm looking at having certain users access one database and other users accessing another database based on the company they belong to. What would be the best way to handle the connection strings and make sure the user connects to the right db when they login? Thanks for any ideas.
In Web.Config or App.Config ``` <connectionStrings> <add name="ConnectionForDudes" providerName="System.Data.SqlClient" connectionString="Data Source=___MALECONNECTIONHERE___"/> <add name="ConnectionForChicks" providerName="System.Data.SqlClient" connectionString="Data Source=___FEMALECONNECTIONHERE___"/> </connectionStrings> ``` When it's time to open the database, you get your connection string this way: ``` bool UserIsMale = true; string ConnectionStringName = "ConnectionFor" + UserIsMale ? "Dudes" : "Chicks"; string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString; ```
266,199
<p>I'm trying to do a very simple button that changes color based on mouseover, mouseout and click, I'm doing this in prototype and the weird thing is if I used mouseover and mouseout, after I clicked on the button, the button wouldn't change to white, seems like it is because of the mouseout, here's my code</p> <pre><code>$("izzy").observe('mouseover', function() { $('izzy').setStyle({ color: '#FFFFFF' }); }); $("izzy").observe('mouseout', function() { $('izzy').setStyle({ color: '#666666' }); }); $("izzy").observe('click', function() { $('izzy').setStyle({ color: '#FFFFFF' }); }); </code></pre> <p>how can I fix it? Thanks.</p>
[ { "answer_id": 266212, "author": "schonarth", "author_id": 22116, "author_profile": "https://Stackoverflow.com/users/22116", "pm_score": 0, "selected": false, "text": "<p>If you move the cursor away from the button after clicking on it, the last event is mouseout, so it happens no matter if you click or not.</p>\n\n<p>If you want to avoid the mouseout effect when it is clicked, try setting a flag when clicking and abortind the mouseout event if the flag is set.</p>\n" }, { "answer_id": 266223, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 2, "selected": false, "text": "<p>Do you mean that you wan the mouse click to cause a permenant change in the style that is not replaced by mouseout? If so, try using a flag, like so:</p>\n\n<pre><code>var wasClicked = false;\n\n$(\"izzy\").observe('mouseover', function() {\n if (!wasClicked) $('izzy').setStyle({ color: '#FFFFFF' });\n});\n\n$(\"izzy\").observe('mouseout', function() {\n if (!wasClicked) $('izzy').setStyle({ color: '#666666' });\n});\n\n$(\"izzy\").observe('click', function() {\n $('izzy').setStyle({ color: '#FFFFFF' });\n wasClicked = true;\n});\n</code></pre>\n" }, { "answer_id": 266226, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "<p>Set a status to prevent the other events:</p>\n\n<pre><code>var clicked = false\n$(\"izzy\").observe('mouseover', function() {\n if(!clicked) {\n $('izzy').setStyle({ color: '#FFFFFF' });\n }\n});\n\n$(\"izzy\").observe('mouseout', function() {\n if(!clicked) {\n $('izzy').setStyle({ color: '#666666' });\n }\n});\n\n$(\"izzy\").observe('click', function() {\n clicked = true\n $('izzy').setStyle({ color: '#cccccc' });\n});\n</code></pre>\n" }, { "answer_id": 266228, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 4, "selected": true, "text": "<p>Unless there's something else happening in mouse over and out, why not use css? </p>\n\n<pre><code>#izzy:hover { color: '#FFFFFF'; }\n</code></pre>\n\n<p>However, I'm a little confused as to what exactly you want to happen. Assuming you want the button white if it has been clicked or if the mouse is over it. I'd have the click event handler add a clicked class, like so:</p>\n\n<pre><code>$(\"izzy\").observe('click', function() {\n $('izzy').addClass('selected');\n});\n</code></pre>\n\n<p>And the css as so</p>\n\n<pre><code>#izzy { color: '#666666'; }\n#izzy:hover, #izzy.selected { color: '#FFFFFF'; }\n</code></pre>\n\n<p>This has the advantage of separating the state - clicked/not-click and mouse over/not over - from the style - black or gray. Right now they're all mixed in together, creating confusion and opening yourself to bugs.</p>\n" }, { "answer_id": 342011, "author": "thoughtcrimes", "author_id": 37814, "author_profile": "https://Stackoverflow.com/users/37814", "pm_score": 0, "selected": false, "text": "<p>Using CSS for a hover and a selected class to colour the element is probably the best choice. However, if you just want a quick fix to code you already have in place you could stop observing the mouseout event after it has been clicked.</p>\n\n<pre><code>$(\"izzy\").observe('click', function(e) {\n e.element().setStyle({ color: '#FFFFFF' });\n e.element().stopObserving('mouseout');\n});\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34797/" ]
I'm trying to do a very simple button that changes color based on mouseover, mouseout and click, I'm doing this in prototype and the weird thing is if I used mouseover and mouseout, after I clicked on the button, the button wouldn't change to white, seems like it is because of the mouseout, here's my code ``` $("izzy").observe('mouseover', function() { $('izzy').setStyle({ color: '#FFFFFF' }); }); $("izzy").observe('mouseout', function() { $('izzy').setStyle({ color: '#666666' }); }); $("izzy").observe('click', function() { $('izzy').setStyle({ color: '#FFFFFF' }); }); ``` how can I fix it? Thanks.
Unless there's something else happening in mouse over and out, why not use css? ``` #izzy:hover { color: '#FFFFFF'; } ``` However, I'm a little confused as to what exactly you want to happen. Assuming you want the button white if it has been clicked or if the mouse is over it. I'd have the click event handler add a clicked class, like so: ``` $("izzy").observe('click', function() { $('izzy').addClass('selected'); }); ``` And the css as so ``` #izzy { color: '#666666'; } #izzy:hover, #izzy.selected { color: '#FFFFFF'; } ``` This has the advantage of separating the state - clicked/not-click and mouse over/not over - from the style - black or gray. Right now they're all mixed in together, creating confusion and opening yourself to bugs.
266,202
<h2>There seems to be two major conventions for organizing project files and then many variations.</h2> <p><strong>Convention 1: High-level type directories, project sub-directories</strong></p> <p>For example, the <a href="http://svn.wxwidgets.org/svn/wx/wxWidgets/trunk/" rel="nofollow noreferrer">wxWidgets</a> project uses this style:</p> <pre><code>/solution /bin /prj1 /prj2 /include /prj1 /prj2 /lib /prj1 /prj2 /src /prj1 /prj2 /test /prj1 /prj2 </code></pre> <p><strong>Pros:</strong></p> <ul> <li>If there are project dependencies, they can be managed from a single file</li> <li>Flat build file structure</li> </ul> <p><strong>Cons:</strong></p> <ul> <li>Since test has its own header and cpp files, when you generate the unit test applications for EXE files rather than libraries, they need to include the <a href="https://en.wikipedia.org/wiki/Object_file" rel="nofollow noreferrer">object files</a> from the application you are testing. This requires you to create inference rules and expand out relative paths for all the source files.</li> <li>Reusing any of the projects in another solution requires you to extract the proper files out of the tree structure and modify any build scripts</li> </ul> <p><strong>Convention 2: High-level project directories, type sub-directories</strong></p> <p>For example, the <a href="http://anonsvn.wireshark.org/wireshark/trunk/" rel="nofollow noreferrer">Wireshark</a> project uses this style</p> <pre><code>/solution /prj1 /bin /include /lib /src /test /prj2 /bin /include /lib /src /test </code></pre> <p><strong>Pros:</strong></p> <ul> <li>Projects themselves are self-contained within their folders, making them easier to move and reuse</li> <li>Allows for shorter inference rules in the build tools</li> <li>Facilitates hierarchical build scripts</li> </ul> <p><strong>Cons:</strong></p> <ul> <li>If there are dependencies between projects, you need an additional layer of build scripts above the project directories to manage the build order</li> </ul> <p>We are currently using convention 1 on our project and so far it has worked fairly well. Now, I am in the process of adding unit testing (via CxxTest) and facilitating the migration to continuous integration using <a href="https://en.wikipedia.org/wiki/Make_%28software%29#Modern_versions" rel="nofollow noreferrer">nmake</a>, convention 1 is causing some serious headaches in the creation of the proper nmake files.</p> <h2>My primary requirements/goals are:</h2> <ul> <li><p>Reduce the level of effort to maintain the build scripts of the entire solution.</p></li> <li><p>De-couple projects and their build steps within a solution from other projects.</p></li> <li><p>Facilitate continuous integration via the use of build scripts for check-out to release media generation for each commit (obviously leveraging other tools such as CruiseControl as well).</p></li> <li><p>Make adding or removing additional projects or source files as easy and least error-prone as possible for the developers.</p></li> </ul> <h2>So I ask:</h2> <ul> <li>Are there other pros and cons of either of these methods?</li> <li>Is there a clear agrument that favors only one of these conventions?</li> </ul>
[ { "answer_id": 267889, "author": "JXG", "author_id": 15456, "author_profile": "https://Stackoverflow.com/users/15456", "pm_score": 3, "selected": true, "text": "<p>[A partial answer.]</p>\n\n<p>In \"Convention 2: High-level project dirs, type sub-directories,\" your single con is</p>\n\n<blockquote>\n <p>If there are dependencies between\n projects, you need an additional layer\n of build scripts above the project\n directories to manage the build order</p>\n</blockquote>\n\n<p>That can also be viewed as a pro, in many projects.</p>\n\n<p>If you have a lot of repetitive general definitions, one would probably want an include file for the build scripts, where solution-wide constants &amp; parameters could be defined. So the \"additional layer of build scripts\" will frequently happen anyway, even if there are no (direct) dependencies.</p>\n\n<p>It's a pro in that there's still room for a more modular approach in building. On the other hand, if you want to reuse a project in another, unrelated solution, you would need to compose a different definitions file. (On the other other hand, if there were a single build file for the whole solution, as in Convention 1, you would need a different build script.) As for your maintenance requirement, that's (IMO) very project-dependent.</p>\n\n<p>My feeling leans towards Convention 2, but it's far from a clear win. In fact, your experience with Convention 1, which was working well until recently, may be the biggest pro of all: a team of people with experience with a certain organization is a valuable asset.</p>\n" }, { "answer_id": 268485, "author": "Thomas L Holaday", "author_id": 29403, "author_profile": "https://Stackoverflow.com/users/29403", "pm_score": 1, "selected": false, "text": "<p>Consider using <a href=\"http://support.microsoft.com/kb/205524\" rel=\"nofollow noreferrer\">NTFS junction points</a> so you can have both organizations at once. Quick definition: \"a junction point is Microsoft's implementation of symbolic links but it only works for directories.\"</p>\n\n<p>Use Convention 2 for the \"real\" layout, because it makes the projects easy to move around. Then make a Convention 1 view:</p>\n\n<pre><code>mkdir /solution/test\nlinkd /solution/test/prj1 /solution/prj1/test\nlinkd /solution/test/prj2 /solution/prj2/test\n</code></pre>\n\n<p>Now you have ...</p>\n\n<pre><code>/solution\n /test\n /prj1\n /prj2 \n</code></pre>\n\n<p>... which was the desired result.</p>\n\n<p>You could do the same thing for /src or the other directories if you find it beneficial. Test scripts that benefit from a Convention 1 view live in /solution/test. </p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2233/" ]
There seems to be two major conventions for organizing project files and then many variations. ---------------------------------------------------------------------------------------------- **Convention 1: High-level type directories, project sub-directories** For example, the [wxWidgets](http://svn.wxwidgets.org/svn/wx/wxWidgets/trunk/) project uses this style: ``` /solution /bin /prj1 /prj2 /include /prj1 /prj2 /lib /prj1 /prj2 /src /prj1 /prj2 /test /prj1 /prj2 ``` **Pros:** * If there are project dependencies, they can be managed from a single file * Flat build file structure **Cons:** * Since test has its own header and cpp files, when you generate the unit test applications for EXE files rather than libraries, they need to include the [object files](https://en.wikipedia.org/wiki/Object_file) from the application you are testing. This requires you to create inference rules and expand out relative paths for all the source files. * Reusing any of the projects in another solution requires you to extract the proper files out of the tree structure and modify any build scripts **Convention 2: High-level project directories, type sub-directories** For example, the [Wireshark](http://anonsvn.wireshark.org/wireshark/trunk/) project uses this style ``` /solution /prj1 /bin /include /lib /src /test /prj2 /bin /include /lib /src /test ``` **Pros:** * Projects themselves are self-contained within their folders, making them easier to move and reuse * Allows for shorter inference rules in the build tools * Facilitates hierarchical build scripts **Cons:** * If there are dependencies between projects, you need an additional layer of build scripts above the project directories to manage the build order We are currently using convention 1 on our project and so far it has worked fairly well. Now, I am in the process of adding unit testing (via CxxTest) and facilitating the migration to continuous integration using [nmake](https://en.wikipedia.org/wiki/Make_%28software%29#Modern_versions), convention 1 is causing some serious headaches in the creation of the proper nmake files. My primary requirements/goals are: ---------------------------------- * Reduce the level of effort to maintain the build scripts of the entire solution. * De-couple projects and their build steps within a solution from other projects. * Facilitate continuous integration via the use of build scripts for check-out to release media generation for each commit (obviously leveraging other tools such as CruiseControl as well). * Make adding or removing additional projects or source files as easy and least error-prone as possible for the developers. So I ask: --------- * Are there other pros and cons of either of these methods? * Is there a clear agrument that favors only one of these conventions?
[A partial answer.] In "Convention 2: High-level project dirs, type sub-directories," your single con is > > If there are dependencies between > projects, you need an additional layer > of build scripts above the project > directories to manage the build order > > > That can also be viewed as a pro, in many projects. If you have a lot of repetitive general definitions, one would probably want an include file for the build scripts, where solution-wide constants & parameters could be defined. So the "additional layer of build scripts" will frequently happen anyway, even if there are no (direct) dependencies. It's a pro in that there's still room for a more modular approach in building. On the other hand, if you want to reuse a project in another, unrelated solution, you would need to compose a different definitions file. (On the other other hand, if there were a single build file for the whole solution, as in Convention 1, you would need a different build script.) As for your maintenance requirement, that's (IMO) very project-dependent. My feeling leans towards Convention 2, but it's far from a clear win. In fact, your experience with Convention 1, which was working well until recently, may be the biggest pro of all: a team of people with experience with a certain organization is a valuable asset.
266,206
<p>I'm relatively new to C++. In Java, it's easy for me to instantiate and use a hashmap. I'd like to know how to do it in a simple way in C++, since I saw many different implementations and none of them looked simple to me.</p>
[ { "answer_id": 266231, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 2, "selected": false, "text": "<p>Try boost's <a href=\"http://www.boost.org/doc/libs/1_37_0/doc/html/unordered.html\" rel=\"nofollow noreferrer\">unordered</a> classes.</p>\n" }, { "answer_id": 266233, "author": "hazzen", "author_id": 5066, "author_profile": "https://Stackoverflow.com/users/5066", "pm_score": 6, "selected": true, "text": "<p>Most compilers should define <code>std::hash_map</code> for you; in the coming <code>C++0x</code> standard, it will be part of the standard library as <a href=\"http://en.cppreference.com/w/cpp/container/unordered_map\" rel=\"noreferrer\"><code>std::unordered_map</code></a>. The <a href=\"http://www.sgi.com/tech/stl/hash_map.html\" rel=\"noreferrer\">STL Page</a> on it is fairly standard. If you use Visual Studio, <a href=\"http://msdn.microsoft.com/en-us/library/6x7w9f6z(VS.71).aspx\" rel=\"noreferrer\">Microsoft</a> has a page on it.</p>\n\n<p>If you want to use your class as the value, not as the key, then you don't need to do anything special. All primitive types (things like <code>int</code>, <code>char</code>, <code>bool</code> and even <code>char *</code>) should \"just work\" as keys in a <code>hash_map</code>. However, for anything else you will have to define your own hashing and equality functions and then write \"functors\" that wrap them in a class.</p>\n\n<p>Assuming your class is called <code>MyClass</code> and you have already defined:</p>\n\n<pre><code>size_t MyClass::HashValue() const { /* something */ }\nbool MyClass::Equals(const MyClass&amp; other) const { /* something */ }\n</code></pre>\n\n<p>You will need to define two functors to wrap those methods in objects.</p>\n\n<pre><code>struct MyClassHash {\n size_t operator()(const MyClass&amp; p) const {\n return p.HashValue();\n }\n};\n\nstruct MyClassEqual {\n bool operator()(const MyClass&amp; c1, const MyClass&amp; c2) const {\n return c1.Equals(c2);\n }\n};\n</code></pre>\n\n<p>And instantiate your <code>hash_map</code>/<code>hash_set</code> as:</p>\n\n<pre><code>hash_map&lt;MyClass, DataType, MyClassHash, MyClassEqual&gt; my_hash_map;\nhash_set&lt;MyClass, MyClassHash, MyClassEqual&gt; my_hash_set;\n</code></pre>\n\n<p>Everything should work as expected after that.</p>\n" }, { "answer_id": 266235, "author": "dalle", "author_id": 19100, "author_profile": "https://Stackoverflow.com/users/19100", "pm_score": 3, "selected": false, "text": "<p>Take a look at <a href=\"http://www.boost.org/doc/libs/1_37_0/doc/html/unordered.html\" rel=\"nofollow noreferrer\">boost.unordered</a>, and its <a href=\"http://www.boost.org/doc/libs/1_37_0/doc/html/unordered/buckets.html\" rel=\"nofollow noreferrer\">data structure</a>.</p>\n" }, { "answer_id": 266452, "author": "Kasprzol", "author_id": 5957, "author_profile": "https://Stackoverflow.com/users/5957", "pm_score": 4, "selected": false, "text": "<p>Using hashmaps in C++ is easy! It's like using standard C++ map. You can use your's compiler/library implementation of <code>unordered_map</code> or use the one provided by <a href=\"http://www.boost.org/doc/libs/1_37_0/doc/html/unordered.html\" rel=\"noreferrer\">boost</a>, or some other vendor. Here's a quick sample. You will find more if you follow the links you were given.</p>\n\n<pre><code>#include &lt;unordered_map&gt;\n#include &lt;string&gt;\n#include &lt;iostream&gt;\n\nint main()\n{\n typedef std::tr1::unordered_map&lt; std::string, int &gt; hashmap;\n hashmap numbers;\n\n numbers[\"one\"] = 1;\n numbers[\"two\"] = 2;\n numbers[\"three\"] = 3;\n\n std::tr1::hash&lt; std::string &gt; hashfunc = numbers.hash_function();\n for( hashmap::const_iterator i = numbers.begin(), e = numbers.end() ; i != e ; ++i ) {\n std::cout &lt;&lt; i-&gt;first &lt;&lt; \" -&gt; \" &lt;&lt; i-&gt;second &lt;&lt; \" (hash = \" &lt;&lt; hashfunc( i-&gt;first ) &lt;&lt; \")\" &lt;&lt; std::endl;\n }\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 16635192, "author": "aozturk", "author_id": 2398929, "author_profile": "https://Stackoverflow.com/users/2398929", "pm_score": 2, "selected": false, "text": "<p>Check out <a href=\"https://goo.gl/mgfyZ3\" rel=\"nofollow\">Simple Hash Map (Hash Table) Implementation in C++</a> for a basic Hash Table with generic type key-value pairs and separate chaining strategy.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33857/" ]
I'm relatively new to C++. In Java, it's easy for me to instantiate and use a hashmap. I'd like to know how to do it in a simple way in C++, since I saw many different implementations and none of them looked simple to me.
Most compilers should define `std::hash_map` for you; in the coming `C++0x` standard, it will be part of the standard library as [`std::unordered_map`](http://en.cppreference.com/w/cpp/container/unordered_map). The [STL Page](http://www.sgi.com/tech/stl/hash_map.html) on it is fairly standard. If you use Visual Studio, [Microsoft](http://msdn.microsoft.com/en-us/library/6x7w9f6z(VS.71).aspx) has a page on it. If you want to use your class as the value, not as the key, then you don't need to do anything special. All primitive types (things like `int`, `char`, `bool` and even `char *`) should "just work" as keys in a `hash_map`. However, for anything else you will have to define your own hashing and equality functions and then write "functors" that wrap them in a class. Assuming your class is called `MyClass` and you have already defined: ``` size_t MyClass::HashValue() const { /* something */ } bool MyClass::Equals(const MyClass& other) const { /* something */ } ``` You will need to define two functors to wrap those methods in objects. ``` struct MyClassHash { size_t operator()(const MyClass& p) const { return p.HashValue(); } }; struct MyClassEqual { bool operator()(const MyClass& c1, const MyClass& c2) const { return c1.Equals(c2); } }; ``` And instantiate your `hash_map`/`hash_set` as: ``` hash_map<MyClass, DataType, MyClassHash, MyClassEqual> my_hash_map; hash_set<MyClass, MyClassHash, MyClassEqual> my_hash_set; ``` Everything should work as expected after that.
266,213
<p>Is there a way (preferrably using JavaScript) to determine whether a URL is to a SWF or a JPG? </p> <p>The obvious answer is to sniff the filename for ".jpg" or ".swf" but I'm dealing with banners that are dynamically decided by the server and usually have a lot of parameters and generally don't include an extension. </p> <p>so i'm wondering if I could load the file first and then read it somehow to determine whether it's SWF or JPG, and then place it, because the JavaScript code I'd need to display a JPG vs a SWF is very different. </p> <p>Thanks! </p>
[ { "answer_id": 266240, "author": "Sijin", "author_id": 8884, "author_profile": "https://Stackoverflow.com/users/8884", "pm_score": 2, "selected": false, "text": "<p>I am not sure the of the exact setup you have, but can you use the HTTP response and check the mime-type to determine image vs flash?</p>\n" }, { "answer_id": 266268, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "<p>If the URL doesn't have an extension then there is no way to tell without requesting the file from the server.</p>\n" }, { "answer_id": 266271, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 2, "selected": false, "text": "<p>I would extend Sijin's answer by saying:</p>\n\n<p>An HTTP HEAD request to the url can be used to examine the resource's mime-type. You \nwon't need to download the rest of the file that way.</p>\n" }, { "answer_id": 266273, "author": "loraderon", "author_id": 22092, "author_profile": "https://Stackoverflow.com/users/22092", "pm_score": 3, "selected": true, "text": "<p>You could use javascript to detect if it is a image by creating a dynamic img-tag.</p>\n\n<pre><code>function isImage(url, callback) {\n var img = document.createElement('img');\n img.onload = function() {\n callback(url);\n }\n img.src = url;\n}\n</code></pre>\n\n<p>And then calling it with:</p>\n\n<pre><code>isImage('http://animals.nationalgeographic.com/staticfiles/NGS/Shared/StaticFiles/animals/images/primary/bald-eagle-head.jpg', function(url) { alert(url + ' is a image'); });\n</code></pre>\n\n<p><strong>Update</strong>\nThis version will always execute the callback with a boolean value.</p>\n\n<pre><code> function isImage(url) {\n var img = document.createElement('img');\n img.onload = function() {\n isImageCallback(url, true);\n }\n img.onerror = function() {\n isImageCallback(url, false);\n }\n img.src = url;\n }\n\n function isImageCallback(url, result) {\n if (result)\n alert(url + ' is an image');\n else\n alert(url + ' is not an image');\n }\n</code></pre>\n\n<p>Put your logic in the isImageCallback function.</p>\n" }, { "answer_id": 266356, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "<p>Completely untested, basicly just an idea:</p>\n\n<pre><code>function isImage(url)\n{\n var http = getHTTPObject();\n http.onreadystatechange = function ()\n {\n if (http.readyState == 4)\n {\n var contentType = http.getResponseHeader(\"Content Type\");\n if (contentType == \"image/gif\" || contentType == \"image/jpeg\")\n return true;\n else\n return false;\n }\n }\n\n http.open(\"HEAD\",url,true);\n http.send(null);\n}\n\n\nfunction getHTTPObject() \n{\n if (window.XMLHttpRequest)\n {\n return new XMLHttpRequest();\n }\n else \n {\n if (window.ActiveXObject)\n {\n return new ActiveXObject(\"Microsoft.XMLHTTP\"); \n }\n }\n return false;\n}\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8349/" ]
Is there a way (preferrably using JavaScript) to determine whether a URL is to a SWF or a JPG? The obvious answer is to sniff the filename for ".jpg" or ".swf" but I'm dealing with banners that are dynamically decided by the server and usually have a lot of parameters and generally don't include an extension. so i'm wondering if I could load the file first and then read it somehow to determine whether it's SWF or JPG, and then place it, because the JavaScript code I'd need to display a JPG vs a SWF is very different. Thanks!
You could use javascript to detect if it is a image by creating a dynamic img-tag. ``` function isImage(url, callback) { var img = document.createElement('img'); img.onload = function() { callback(url); } img.src = url; } ``` And then calling it with: ``` isImage('http://animals.nationalgeographic.com/staticfiles/NGS/Shared/StaticFiles/animals/images/primary/bald-eagle-head.jpg', function(url) { alert(url + ' is a image'); }); ``` **Update** This version will always execute the callback with a boolean value. ``` function isImage(url) { var img = document.createElement('img'); img.onload = function() { isImageCallback(url, true); } img.onerror = function() { isImageCallback(url, false); } img.src = url; } function isImageCallback(url, result) { if (result) alert(url + ' is an image'); else alert(url + ' is not an image'); } ``` Put your logic in the isImageCallback function.
266,245
<p>I have a git repository with remote foo.</p> <p>foo is a web app, is contains some files and dirs directly in its root:</p> <pre><code>Rakefile app ... public script </code></pre> <p>My main git repository is a larger system which comprises this web app. I want to pull the commits from foo, but I need the files to reside inside the <code>web</code> dir. So they should become <code>web/app</code>, <code>web/public</code>, etc.</p> <p>I don't want to use foo as a submodule. I want to merge foo into the main repository and then get rid of it.</p>
[ { "answer_id": 266334, "author": "kch", "author_id": 13989, "author_profile": "https://Stackoverflow.com/users/13989", "pm_score": 2, "selected": false, "text": "<p>This answers my question:</p>\n\n<p><a href=\"http://www.kernel.org/pub/software/scm/git/docs/howto/using-merge-subtree.html\" rel=\"nofollow noreferrer\">http://www.kernel.org/pub/software/scm/git/docs/howto/using-merge-subtree.html</a></p>\n" }, { "answer_id": 267574, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 2, "selected": true, "text": "<p>Here's a community-wiki version of your answer if you'd like to accept it as the answer.</p>\n\n<hr>\n\n<p>This answers my question:</p>\n\n<p><a href=\"http://www.kernel.org/pub/software/scm/git/docs/howto/using-merge-subtree.html\" rel=\"nofollow noreferrer\">http://www.kernel.org/pub/software/scm/git/docs/howto/using-merge-subtree.html</a></p>\n" }, { "answer_id": 12243677, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 2, "selected": false, "text": "<p>The up-to-date resources for <strong>subtree merging</strong> are:</p>\n<ul>\n<li><a href=\"https://git-scm.com/book/en/v2/Git-Tools-Advanced-Merging#_subtree_merge\" rel=\"nofollow noreferrer\">Git Book chapter 7.8</a></li>\n<li><a href=\"http://www.kernel.org/pub/software/scm/git/docs/howto/using-merge-subtree.html\" rel=\"nofollow noreferrer\">How to use the subtree merge strategy</a></li>\n<li>GitHub article &quot;<a href=\"https://help.github.com/articles/working-with-subtree-merge\" rel=\"nofollow noreferrer\">Working with subtree merge</a>&quot;</li>\n</ul>\n<p>Cite from <a href=\"http://www.kernel.org/pub/software/scm/git/docs/howto/using-merge-subtree.html\" rel=\"nofollow noreferrer\">How to use the subtree merge strategy</a>:</p>\n<blockquote>\n<p>In this example, let’s say you have the repository at <code>/path/to/B</code> (but it can be an URL as well, if you want).\nYou want to merge the master branch of that repository to the <code>dir-B</code> subdirectory in your current branch.</p>\n</blockquote>\n<blockquote>\n<p>Here is the command sequence you need:</p>\n</blockquote>\n<pre><code>$ git remote add -f Bproject /path/to/B\n$ git merge -s ours --no-commit Bproject/master\n$ git read-tree --prefix=dir-B/ -u Bproject/master\n$ git commit -m &quot;Merge B project as our subdirectory&quot;\n\n$ git pull -s subtree Bproject master\n</code></pre>\n<p>See also for comments the article &quot;<a href=\"http://nuclearsquid.com/writings/subtree-merging-and-you/\" rel=\"nofollow noreferrer\">Subtree merging and you</a>&quot;.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13989/" ]
I have a git repository with remote foo. foo is a web app, is contains some files and dirs directly in its root: ``` Rakefile app ... public script ``` My main git repository is a larger system which comprises this web app. I want to pull the commits from foo, but I need the files to reside inside the `web` dir. So they should become `web/app`, `web/public`, etc. I don't want to use foo as a submodule. I want to merge foo into the main repository and then get rid of it.
Here's a community-wiki version of your answer if you'd like to accept it as the answer. --- This answers my question: <http://www.kernel.org/pub/software/scm/git/docs/howto/using-merge-subtree.html>
266,250
<p>I'm learning some PowerShell. Is it possible to see the source code for a built-in cmdlet like <a href="http://technet.microsoft.com/en-us/library/hh849800.aspx" rel="noreferrer">Get-ChildItem</a>?</p>
[ { "answer_id": 266259, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 0, "selected": false, "text": "<p>I do not believe that the source code for PowerShell has ever been released.</p>\n" }, { "answer_id": 266286, "author": "dalle", "author_id": 19100, "author_profile": "https://Stackoverflow.com/users/19100", "pm_score": 2, "selected": false, "text": "<p>You should be able to use <a href=\"http://en.wikipedia.org/wiki/.NET_Reflector\" rel=\"nofollow noreferrer\">.NET Reflector</a> to \"see\" the source code. You need to know the assembly though, but it should also accessible using the GetType method or similar.</p>\n\n<p>This <a href=\"http://www.codeplex.com/reflectoraddins/Wiki/View.aspx?title=PowerShellLanguage&amp;referringTitle=Home\" rel=\"nofollow noreferrer\">PowerShellLanguage .NET Reflector Add-In</a> can perhaps be useful.</p>\n" }, { "answer_id": 267600, "author": "halr9000", "author_id": 6637, "author_profile": "https://Stackoverflow.com/users/6637", "pm_score": 5, "selected": false, "text": "<p>Actually, your best bet is to go check out <a href=\"https://github.com/Pscx/Pscx\" rel=\"nofollow noreferrer\">PowerShell Community Extensions</a>. This open source software community project is &quot;aimed at providing a widely useful set of additional cmdlets...&quot;. The developers on the project are PowerShell MVPs and know their stuff.</p>\n<p>As far as using reflection on the existing PowerShell cmdlets, PowerShell MVP Oisin Grehan made a handy function titled &quot;<a href=\"https://web.archive.org/web/20190521090145/https://www.nivot.org/post/2008/10/30/ATrickToJumpDirectlyToACmdletsImplementationInReflector\" rel=\"nofollow noreferrer\">Reflect-Cmdlet</a>&quot;. I won't steal his code and place it here, but basically what you do is:</p>\n<pre><code>Get-Command Get-ChildItem | Reflect-Cmdlet\n</code></pre>\n<p>And then <a href=\"https://en.wikipedia.org/wiki/.NET_Reflector\" rel=\"nofollow noreferrer\">.NET Reflector</a> pops up with the right assembly opened up and expanded and everything. It's really pretty cool.</p>\n" }, { "answer_id": 1101186, "author": "Stephen Harrison", "author_id": 106755, "author_profile": "https://Stackoverflow.com/users/106755", "pm_score": 2, "selected": false, "text": "<p>You might also like to take a look at <a href=\"http://psmsi.codeplex.com/\" rel=\"nofollow noreferrer\">Windows Installer PowerShell Snap-In</a> on CodePlex. It's a smaller project than the community extensions, so it is easier to get your head around what's going on.</p>\n\n<p>Check out <em>Professional Windows PowerShell Programming: Snapins, Cmdlets, Hosts and Providers</em> (Wrox Professional Guides), ISBN: 0470173939 - it's one of the most useful books I've found for writing cmdlets and providers.</p>\n" }, { "answer_id": 8508209, "author": "ssvinarenko", "author_id": 61474, "author_profile": "https://Stackoverflow.com/users/61474", "pm_score": 1, "selected": false, "text": "<p>PowerShell cmdlets' assemblies are located in GAC. You can find \"Get-ChildItem\" cmdlet in:</p>\n\n<p><strong>Microsoft.PowerShell.Commands.Management assembly, Microsoft.PowerShell.Commands.GetChildItemCommand</strong> class.</p>\n\n<p>I've used ILSpy .NET decompiler and filtered GAC assemblies by \"powershell\" string. As I understand, <strong>Microsoft.PowerShell.Commands.*</strong> assemblies contain built-in cmdlets.</p>\n" }, { "answer_id": 20484505, "author": "ImpossibleSqui", "author_id": 3085094, "author_profile": "https://Stackoverflow.com/users/3085094", "pm_score": 4, "selected": false, "text": "<p>I think if you were just starting PowerShell, this is what you'd be looking for:</p>\n\n<pre><code>$metadata = New-Object system.management.automation.commandmetadata (Get-Command Get-Process)\n[System.management.automation.proxycommand]::Create($MetaData) | out-file C:\\powershell\\get-process.ps1\n</code></pre>\n\n<p>This will create a script which shows how <a href=\"http://technet.microsoft.com/en-us/library/hh849832.aspx\" rel=\"noreferrer\">Get-Process</a> runs. Put in any cmdlet you want to replace Get-Process. If you want to google more about it, this is how you would create a proxy function.</p>\n" }, { "answer_id": 31970228, "author": "JohnLBevan", "author_id": 361842, "author_profile": "https://Stackoverflow.com/users/361842", "pm_score": 0, "selected": false, "text": "<p>Some code can be found on the Reference Resource Site:\n<a href=\"http://referencesource.microsoft.com/#System.Management.Automation/System/Management/Automation/ChildItemCmdletProviderIntrinsics.cs,c6eed9f6a5417c19\" rel=\"nofollow\">http://referencesource.microsoft.com/#System.Management.Automation/System/Management/Automation/ChildItemCmdletProviderIntrinsics.cs,c6eed9f6a5417c19</a></p>\n\n<p>This only gives the outline though; not the code's detail.</p>\n" }, { "answer_id": 32189485, "author": "Michael Kropat", "author_id": 27581, "author_profile": "https://Stackoverflow.com/users/27581", "pm_score": 4, "selected": false, "text": "<p>For <strong>compiled</strong> Cmdlets, you can get the path to the <code>.dll</code> with:</p>\n<pre><code>(Get-Command Get-ChildItem).DLL\n</code></pre>\n<p>(Replace <code>Get-ChildItem</code> with the cmdlet you are interested in)</p>\n<p><strong>Example:</strong></p>\n<pre><code>PS C:\\Windows\\system32&gt; (Get-Command Get-StoragePool).DLL\n\nPS C:\\Windows\\system32&gt; \n</code></pre>\n<p>Once you know the path to the <code>.dll</code>, you can open it with a .NET disassembler like <a href=\"https://www.jetbrains.com/decompiler/\" rel=\"nofollow noreferrer\">dotPeek</a>:</p>\n<pre><code>&amp; dotPeek64.exe (Get-Command Get-ChildItem).DLL\n</code></pre>\n" }, { "answer_id": 39058300, "author": "Zev Spitz", "author_id": 111794, "author_profile": "https://Stackoverflow.com/users/111794", "pm_score": 5, "selected": false, "text": "<p><a href=\"https://github.com/PowerShell/PowerShell\">The source for Powershell is now available on Github.</a><br>\nThe source for <code>Get-ChildItem</code> can be found <a href=\"https://github.com/PowerShell/PowerShell/blob/c1faf1e6e10fc1ce45e84ef6f49ae7136c67a111/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs\">here</a>.</p>\n" }, { "answer_id": 66993858, "author": "user2173353", "author_id": 2173353, "author_profile": "https://Stackoverflow.com/users/2173353", "pm_score": 1, "selected": false, "text": "<p>For some cmdlets that are installed with <code>Install-Module</code> and contain source code and not binaries, (e.g. PSnmap):</p>\n<pre><code>Install-Module -Name PSnmap\n</code></pre>\n<p>...you can view their code by looking at the <code>Definition</code> property from:</p>\n<pre><code>Get-Command Invoke-PSnmap | Format-List\n</code></pre>\n<p>If not, most likely, you will need to decompile some binary (e.g. the file specified in the <code>DLL</code> property).</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm learning some PowerShell. Is it possible to see the source code for a built-in cmdlet like [Get-ChildItem](http://technet.microsoft.com/en-us/library/hh849800.aspx)?
Actually, your best bet is to go check out [PowerShell Community Extensions](https://github.com/Pscx/Pscx). This open source software community project is "aimed at providing a widely useful set of additional cmdlets...". The developers on the project are PowerShell MVPs and know their stuff. As far as using reflection on the existing PowerShell cmdlets, PowerShell MVP Oisin Grehan made a handy function titled "[Reflect-Cmdlet](https://web.archive.org/web/20190521090145/https://www.nivot.org/post/2008/10/30/ATrickToJumpDirectlyToACmdletsImplementationInReflector)". I won't steal his code and place it here, but basically what you do is: ``` Get-Command Get-ChildItem | Reflect-Cmdlet ``` And then [.NET Reflector](https://en.wikipedia.org/wiki/.NET_Reflector) pops up with the right assembly opened up and expanded and everything. It's really pretty cool.
266,255
<p>I try to instantiate an instance of <code>SPSite</code> on the farm server in a custom process (MyApp.exe) and I give it as parameter the whole URI (<a href="http://mysite:80/" rel="nofollow noreferrer">http://mysite:80/</a>). I also made sure that the account running <code>MyApp.exe</code> is <code>Site Collection Administrator</code>.</p> <p>However, I can't make an instance of <code>SPSite</code> whatever I am trying to do. It always throws a <code>FileNotFoundException</code>.</p> <p>Anyone got an idea?</p> <p>StackTrace:</p> <blockquote> <p>at Microsoft.SharePoint.SPSite..ctor(SPFarm farm, Uri requestUri, Boolean contextSite, SPUserToken userToken)<br> at Microsoft.SharePoint.SPSite..ctor(String requestUrl) at MyCompanyName.Service.HelperClass.GetItemStateInSharePoint(SharePointItem item) in C:\Workspaces\MyCompanyName\Development\Main\MyCompanyName.SharePoint\Service\HelperClass.cs:line 555</p> </blockquote> <p>Another side note... I have a Web Application + Site collection that I can access through the browser without any problem.</p>
[ { "answer_id": 266274, "author": "axk", "author_id": 578, "author_profile": "https://Stackoverflow.com/users/578", "pm_score": 1, "selected": false, "text": "<p>Stacktrace of the exception would be helpful.</p>\n\n<p>I think you possibly can get some idea of what file it is and what is happening by disabling \"just my code\" in tools -> options -> debugging and looking at the filename argument in the call stack of the exception when the debugger shows it (if you can debug it of course), or maybe the name shows up in the exception message.</p>\n" }, { "answer_id": 266277, "author": "vIceBerg", "author_id": 17766, "author_profile": "https://Stackoverflow.com/users/17766", "pm_score": 1, "selected": false, "text": "<p>Check your web.config and see if there's a config there with a file missing.</p>\n\n<p>Look in you 12 hive for the log. If your log settings are correct, you'll get the file missing.</p>\n\n<p>EDIT: Check also if ALL your DLL are in the GAC. Check if your web.config file contains all the information: namespace,Classname, NameSpace, Version=version_number, Culture-your_culture, PublicKeyToken=your_signed_token</p>\n" }, { "answer_id": 266295, "author": "slf", "author_id": 13263, "author_profile": "https://Stackoverflow.com/users/13263", "pm_score": 0, "selected": false, "text": "<p>I was plagued by this a few weeks ago. Ultimately I discovered that the file that could not be found was the SharePoint assembly itself. The runtime was failing to load the satellite assembly via late-binding. </p>\n\n<p>The solution to my problem was to register the SharePoint 12.0.0.0 Assemblies in the GAC. It doesn't sound like it's the same as your problem, but just FYI.</p>\n" }, { "answer_id": 266333, "author": "Lars Fastrup", "author_id": 27393, "author_profile": "https://Stackoverflow.com/users/27393", "pm_score": 5, "selected": true, "text": "<p>The FileNotFoundException is thrown by SharePoint when it cannot find the requested site collection in the SharePoint configuration database. My guess is that you have not yet created a site collection on the URL <a href=\"http://mysite:80\" rel=\"noreferrer\">http://mysite:80</a>. I see the following stack trace if I try and instantiate a new SPSite object with the URL of a non-existing site collection:</p>\n\n<pre><code>System.IO.FileNotFoundException : The site http://server/sites/bah could not be found in the Web application SPWebApplication \nName=SharePoint - 80 Parent=SPWebService.\nat Microsoft.SharePoint.SPSite..ctor(SPFarm farm, Uri requestUri, Boolean contextSite, SPUserToken userToken)\nat Microsoft.SharePoint.SPSite..ctor(String requestUrl)\n</code></pre>\n\n<p>Specify the proper URL of your site collection or open Central Administration and create a new Site Collection.</p>\n" }, { "answer_id": 266344, "author": "Abs", "author_id": 1245, "author_profile": "https://Stackoverflow.com/users/1245", "pm_score": 2, "selected": false, "text": "<p>It's also possible that the object model doesn't like the URL you're giving it. If you don't provide it with either the exact URL at which you created the site collection or an exact URL listed in your is configured in your Alternate Access Mappings, it will throw an exception that might not necessarily make sense. In your case you might try <code>http://mysite</code> or <code>http://machinename</code>.</p>\n" }, { "answer_id": 383238, "author": "axk", "author_id": 578, "author_profile": "https://Stackoverflow.com/users/578", "pm_score": 1, "selected": false, "text": "<p>I have recently discovered that this problem with the constructor can be cause by starnge behaviour of the constructor.<br>\nI'm taking about MOSS 2007.\nWhen you're passing a full site URL to the constructor, what it seems to do is to really consider only the site portion of the URL, choosing the web application which is 'currently seleced' in the web application selector control.<br>\nThus, for example, when you have \"<a href=\"http://webapp/sites/site\" rel=\"nofollow noreferrer\">http://webapp/sites/site</a>\" and have \"<a href=\"http://weabapp:22345\" rel=\"nofollow noreferrer\">http://weabapp:22345</a>\" currently selected (the last time you selected it in such a selector) when you call </p>\n\n<pre><code>SPSite site = new SPSite(\"http://webapp/sites/site\")\n</code></pre>\n\n<p>It tries to actually create a site object for \"<a href=\"http://webapp:22345/sites/site\" rel=\"nofollow noreferrer\">http://webapp:22345/sites/site</a>\" and fails.</p>\n" }, { "answer_id": 998475, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>We faced the same problem some days ago, and the solution was to set the application, that is trying to create de SPSite object, to use the same AppPool that the Sharepoint's web application.</p>\n\n<p>Hope it helps.</p>\n" }, { "answer_id": 1530075, "author": "Olof Szymczak", "author_id": 185440, "author_profile": "https://Stackoverflow.com/users/185440", "pm_score": 3, "selected": false, "text": "<p>Read this site <a href=\"http://community.bamboosolutions.com/forums/t/8179.aspx\" rel=\"nofollow noreferrer\">http://community.bamboosolutions.com/forums/t/8179.aspx</a> if you are running your OS x64 bit and are using MSTest (32bit) it will fail, use nunit works!!!</p>\n" }, { "answer_id": 1669292, "author": "John Fields", "author_id": 201969, "author_profile": "https://Stackoverflow.com/users/201969", "pm_score": 0, "selected": false, "text": "<p>The MSTest on x64 issue was the cause of this problem for me. Works in a console app.</p>\n" }, { "answer_id": 1835990, "author": "Kiran", "author_id": 223279, "author_profile": "https://Stackoverflow.com/users/223279", "pm_score": 0, "selected": false, "text": "<p>I have similar kind of issue.</p>\n\n<p>In my scenario, I was able to create the instance of SPSite from a console application, but when another team mate tried to do so, the application threw the same exception as mentioned above.</p>\n\n<p>Solution: I added the other teammate as administrator on Content Db server box (this may not be possible for everyone), the code works fine and no error</p>\n" }, { "answer_id": 3867253, "author": "Charles Chen", "author_id": 116051, "author_profile": "https://Stackoverflow.com/users/116051", "pm_score": 4, "selected": false, "text": "<p>Changing the platform target in the build properties to x64 solved this issue for me on SharePoint 2010.</p>\n" }, { "answer_id": 4350317, "author": "user379310", "author_id": 379310, "author_profile": "https://Stackoverflow.com/users/379310", "pm_score": 2, "selected": false, "text": "<p>This Issue is more of user permission issue give the following permission</p>\n\n<p>User Permission \n<strong>SharePoint Site</strong> --- Minimum Read Permission </p>\n\n<p><strong>Sharepoint Server</strong> --- Add to WSS_ADMIN_WPG group</p>\n\n<p><strong>Database</strong> --- Sharepoint Content DB (Site collection database) - db_owner permission\n Sharepoint Config DB (Config DB of sharepoint installation) - - db_owner permission </p>\n\n<p>Read more in my blog</p>\n\n<p><a href=\"http://sharepointinstallation.blogspot.com/2010/12/minimal-permission-required-to-execute.html\" rel=\"nofollow\">http://sharepointinstallation.blogspot.com/2010/12/minimal-permission-required-to-execute.html</a></p>\n" }, { "answer_id": 4825097, "author": "Lester", "author_id": 141069, "author_profile": "https://Stackoverflow.com/users/141069", "pm_score": 2, "selected": false, "text": "<p>If it is a console application accessing SharePoint 2010 you make sure your project's Build Target is x64 and the .NET Framework is 3.5.</p>\n" }, { "answer_id": 4886526, "author": "vibloggers", "author_id": 601527, "author_profile": "https://Stackoverflow.com/users/601527", "pm_score": 1, "selected": false, "text": "<p>I had the same issue. I wanted to run console application with my user id. I am web application owner + Farm Admin. Still was not able to run the application.</p>\n\n<p>Issue was resolved by </p>\n\n<ol>\n<li><p>Changing the platform target in build properties to x64</p></li>\n<li><p>In site settings -->Users and Permissions --> Site Collection Administrators there were two names. Removed other name and it started working. </p></li>\n</ol>\n" }, { "answer_id": 7989539, "author": "Hernan Veiras", "author_id": 375619, "author_profile": "https://Stackoverflow.com/users/375619", "pm_score": 1, "selected": false, "text": "<p>You can keep the project compilation target set to \"Any CPU\". The important this is to configure the MSTest host process to run in 64bits. Open your .testsettings file, go to Hosts tab and set \"Run tests in 64 bit...\"</p>\n\n<p>If after this when you run your tests VS tells you there aren't any, remove and add your test project again (I don't know a better workaround for this)</p>\n\n<p>Hope it helps!</p>\n" }, { "answer_id": 14608463, "author": "AshesToAshes", "author_id": 1164439, "author_profile": "https://Stackoverflow.com/users/1164439", "pm_score": 0, "selected": false, "text": "<p>Same problem on SharePoint 2010. However the issue was with our web service which was accessing the SharePoint object model. The app pool that this service should run under should be a farm admin.</p>\n" }, { "answer_id": 21269230, "author": "Aaron", "author_id": 3221067, "author_profile": "https://Stackoverflow.com/users/3221067", "pm_score": 1, "selected": false, "text": "<p>We had this same Issue, but I am familiar with the different causes, here is a summary:</p>\n\n<ol>\n<li>You could have mis-typed or otherwise inputted the wrong address</li>\n<li>The User account running the process does not have the required permissions, which are: Read Permission to the SharePoint site, and a dbo of the SharePoint Config db, and Content db.</li>\n<li>The process must be a 64 bit process (the default is 64bit \"Any CPU\") when building on a 64 bit server.</li>\n<li>The process must be targeted at .NET 3.5</li>\n</ol>\n" }, { "answer_id": 23747290, "author": "ndhar", "author_id": 3298844, "author_profile": "https://Stackoverflow.com/users/3298844", "pm_score": 0, "selected": false, "text": "<p>Switching to NUnit might not be an option for everyone.<br/>\nIn my case, the problem was that I was on a 64 bit server, I had Any CPU checked (so it was picking the correct version) but my Test Settings were set to \"Force tests to run in 32 bit process\" (GAH!)<br/></p>\n\n<p>In MSTest, Go to TEst->Edit Test Settings->Trace and Test Impact.<br/>\nChoose Hosts. <br/>\nMake sure you are running against the correct version.\n<img src=\"https://i.stack.imgur.com/UEAdd.png\" alt=\"Here&#39;s what you should be picking\"></p>\n\n<p>Here is my checklist for VS2010 SP1, MSTest.</p>\n\n<ul>\n<li>You need SP1 so that you can target tests to .NET 3.5. It will not work with .NET 4.0</li>\n<li>Make sure the site loads- i launched the site directly from the VS2010 editor, since it's a hyperlink</li>\n<li>Verify build settings. To Choose 64 bit if server is 64-bit.</li>\n<li>In my case I had a 64 bit server, but choosing x64 would fail! That was my first clue.</li>\n<li>Verify that the test settings support the correct bits.</li>\n</ul>\n" }, { "answer_id": 27125986, "author": "Terry B", "author_id": 4260632, "author_profile": "https://Stackoverflow.com/users/4260632", "pm_score": 0, "selected": false, "text": "<p>I had the same problem trying to access Sharepoint 2010.</p>\n\n<p>I fixed it by changing the Target Framework to .NET 3.5.- which is the supported version for Sharepoint 2010.</p>\n" }, { "answer_id": 29552559, "author": "NorthGork", "author_id": 4771929, "author_profile": "https://Stackoverflow.com/users/4771929", "pm_score": 0, "selected": false, "text": "<p>In my case it was definitely a permissions problem with the account I was logged into windows with.</p>\n\n<p>Try this command in SharePoint Management Shell running as Administrator:</p>\n\n<p>Get-SPSite '<a href=\"http://yoursite/yourcollection\" rel=\"nofollow\">http://yoursite/yourcollection</a>'</p>\n\n<p>If you get errors then logon to the SharePoint server as the app pool user or the account used to install SharePoint and try the above command again.</p>\n\n<p>If it works then you know your previous account has a permissions issue. To fix the problem, run this command in the same shell window and supply the account you want to use in VS:</p>\n\n<p>Add-SPShellAdmin -UserName Domain\\User</p>\n" }, { "answer_id": 54267635, "author": "Manoj Prajapati", "author_id": 10937521, "author_profile": "https://Stackoverflow.com/users/10937521", "pm_score": 0, "selected": false, "text": "<p>I had the same problem, I made below changes and it started working.</p>\n\n<ol>\n<li>Changing the platform target in visual studio to x64 </li>\n<li>make sure you are running visual studio in \"Administrator\" mode.</li>\n</ol>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24975/" ]
I try to instantiate an instance of `SPSite` on the farm server in a custom process (MyApp.exe) and I give it as parameter the whole URI (<http://mysite:80/>). I also made sure that the account running `MyApp.exe` is `Site Collection Administrator`. However, I can't make an instance of `SPSite` whatever I am trying to do. It always throws a `FileNotFoundException`. Anyone got an idea? StackTrace: > > at > Microsoft.SharePoint.SPSite..ctor(SPFarm > farm, Uri requestUri, Boolean > contextSite, SPUserToken userToken) > > at > Microsoft.SharePoint.SPSite..ctor(String > requestUrl) at > MyCompanyName.Service.HelperClass.GetItemStateInSharePoint(SharePointItem > item) in > C:\Workspaces\MyCompanyName\Development\Main\MyCompanyName.SharePoint\Service\HelperClass.cs:line > 555 > > > Another side note... I have a Web Application + Site collection that I can access through the browser without any problem.
The FileNotFoundException is thrown by SharePoint when it cannot find the requested site collection in the SharePoint configuration database. My guess is that you have not yet created a site collection on the URL <http://mysite:80>. I see the following stack trace if I try and instantiate a new SPSite object with the URL of a non-existing site collection: ``` System.IO.FileNotFoundException : The site http://server/sites/bah could not be found in the Web application SPWebApplication Name=SharePoint - 80 Parent=SPWebService. at Microsoft.SharePoint.SPSite..ctor(SPFarm farm, Uri requestUri, Boolean contextSite, SPUserToken userToken) at Microsoft.SharePoint.SPSite..ctor(String requestUrl) ``` Specify the proper URL of your site collection or open Central Administration and create a new Site Collection.
266,308
<p>Is there a way to compile a .vbproj or .csproj project file directly, just like Visual Studio does?</p> <p>When you compile in Visual Studio, the "output" window shows the actual call to the compiler, which normally looks like:</p> <p>vbc.exe [bunch of options] [looooong list of .vb files]</p> <p>I would like to programatically call "something" that would take the .vbproj file and do whatever Visual Studio does to generate this long command line. I know i <em>could</em> parse the .vbproj myself and generate that command line, but I'd rather save myself all the reverse engineering and trial-and-error...</p> <p>Is there a tool to do this? I'd rather be able to do it in a machine without having Visual Studio installed. However, if there's a way to call Visual Studio with some parameters to do it, then that'll be fine too.</p> <p>I looked briefly at MSBuild, and it looks like it works from a .proj project file that i'd have to make especially, and that I'd need to update every time I add a file to the .vbproj file. (I did look <em>briefly</em> at it, so it's very likely I missed something important)</p> <p>Any help will be greatly appreciated</p>
[ { "answer_id": 266318, "author": "Rob Prouse", "author_id": 30827, "author_profile": "https://Stackoverflow.com/users/30827", "pm_score": 3, "selected": false, "text": "<p>MSBuild can also take your solution file and use it to do the compile.</p>\n" }, { "answer_id": 266319, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "<p>MSBuild is the easiest way to go. For instance:</p>\n\n<pre><code>msbuild /property:Configuration=Release MyFile.vbproj\n</code></pre>\n" }, { "answer_id": 266335, "author": "AaronS", "author_id": 26932, "author_profile": "https://Stackoverflow.com/users/26932", "pm_score": 2, "selected": false, "text": "<p>You can use either MSBUILD or CSC. MSBuild, which as you mentioned, does use your project and solution files. CSC will compile specific files, or all files in a specific directory tree.</p>\n\n<p>You should also look at automating your builds with NAnt and/or CruiseControl.net.</p>\n\n<p>Also, here is an example on how to compile your code without visual studio using CSC.\n<a href=\"http://blog.slickedit.com/?p=163\" rel=\"nofollow noreferrer\">http://blog.slickedit.com/?p=163</a></p>\n" }, { "answer_id": 896397, "author": "Sayed Ibrahim Hashimi", "author_id": 105999, "author_profile": "https://Stackoverflow.com/users/105999", "pm_score": 2, "selected": false, "text": "<p>Just so you know .vbproj and .csproj files are MSBuild. So everything that you've read, you can apply to those files directly.</p>\n\n<p>Sayed Ibrahim Hashimi</p>\n\n<p>My Book: <a href=\"https://rads.stackoverflow.com/amzn/click/com/0735626286\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Inside the Microsoft Build Engine : Using MSBuild and Team Foundation Build</a></p>\n" }, { "answer_id": 18820303, "author": "JWPlatt", "author_id": 2782594, "author_profile": "https://Stackoverflow.com/users/2782594", "pm_score": -1, "selected": false, "text": "<p>At the top of a .vbproj file is a . Add this line to the property group to suppress the VB runtime:</p>\n\n<pre><code>&lt;NoVBRuntimeReference&gt;On&lt;/NoVBRuntimeReference&gt;\n</code></pre>\n\n<p>MSBuild does the rest. No need to use the command line if you have the IDE.</p>\n" }, { "answer_id": 46141807, "author": "Alexander Ivanov", "author_id": 2311055, "author_profile": "https://Stackoverflow.com/users/2311055", "pm_score": 1, "selected": false, "text": "<p>In project solution folder:</p>\n\n<pre><code>msbuild wpfapp1.sln /p:BuildProjectReferences=true\n</code></pre>\n\n<p>MSbuild is usually located in:</p>\n\n<pre><code>C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\n</code></pre>\n\n<p>(or something similar, depending on the version)</p>\n\n<p>csc.exe compiles files, msbuild compiles projects and solutions</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3314/" ]
Is there a way to compile a .vbproj or .csproj project file directly, just like Visual Studio does? When you compile in Visual Studio, the "output" window shows the actual call to the compiler, which normally looks like: vbc.exe [bunch of options] [looooong list of .vb files] I would like to programatically call "something" that would take the .vbproj file and do whatever Visual Studio does to generate this long command line. I know i *could* parse the .vbproj myself and generate that command line, but I'd rather save myself all the reverse engineering and trial-and-error... Is there a tool to do this? I'd rather be able to do it in a machine without having Visual Studio installed. However, if there's a way to call Visual Studio with some parameters to do it, then that'll be fine too. I looked briefly at MSBuild, and it looks like it works from a .proj project file that i'd have to make especially, and that I'd need to update every time I add a file to the .vbproj file. (I did look *briefly* at it, so it's very likely I missed something important) Any help will be greatly appreciated
MSBuild is the easiest way to go. For instance: ``` msbuild /property:Configuration=Release MyFile.vbproj ```
266,326
<p>Am I safe in casting a C++ bool to a Windows API BOOL via this construct</p> <pre><code>bool mybool = true; BOOL apiboolean = mybool ? TRUE : FALSE; </code></pre> <p>I'd assume this is a yes because I don't see any obvious problems but I wanted to take a moment to ask only because this may be more subtle than it appears. </p> <p><em>Thanks to Dima for (gently) pointing out my carelessness in the way I'd originally phrased the question.</em> </p>
[ { "answer_id": 266338, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 4, "selected": true, "text": "<p>Do you mean</p>\n\n<pre><code>\nbool b;\n...\nBOOL apiboolean = b ? TRUE : FALSE;\n</code></pre>\n\n<p>If so, then yes, this will work.</p>\n" }, { "answer_id": 266468, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "<p>Yes, that will work, but</p>\n\n<pre><code>bool b;\n...\nBOOL apiboolean = (BOOL) b;\n</code></pre>\n\n<p>should work just as well, as does the reverse:</p>\n\n<pre><code>bool bb = (bool) apiboolean;\n</code></pre>\n" }, { "answer_id": 4853474, "author": "Martin Ba", "author_id": 321013, "author_profile": "https://Stackoverflow.com/users/321013", "pm_score": 1, "selected": false, "text": "<p>Visual Studio 2005 will simply accept:</p>\n\n<pre><code>bool b = true;\nBOOL apiboolean = b;\n</code></pre>\n\n<p><em>no casting required</em>.</p>\n\n<p>Note that the other way round BOOL->bool does not simply work like this.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2820/" ]
Am I safe in casting a C++ bool to a Windows API BOOL via this construct ``` bool mybool = true; BOOL apiboolean = mybool ? TRUE : FALSE; ``` I'd assume this is a yes because I don't see any obvious problems but I wanted to take a moment to ask only because this may be more subtle than it appears. *Thanks to Dima for (gently) pointing out my carelessness in the way I'd originally phrased the question.*
Do you mean ``` bool b; ... BOOL apiboolean = b ? TRUE : FALSE; ``` If so, then yes, this will work.
266,327
<p>A pattern that's started to show up a lot in one of the web apps I'm working are links that used to just be a regular a-tag link now need a popup box asking "are you sure?" before the link will go. (If the user hits cancel, nothing happens.)</p> <p>We've got a solution that works, but somehow we're a web app shop without a Javascript expert, so I'm left with this crawling feeling like there's a better way to get the job done.</p> <p>So, JS experts, what's the most standards-compliant, cross-browser way to get this done?</p> <p>(For the record, this is already a site that requires JS, so no need to have a "non-JS" version. But, it does need to work in any and all reasonably modern browsers.)</p> <p>(Also, for bonus points it would be nice if people with JS turned off didn't have the links work, rather than bypassing the confirm box.)</p>
[ { "answer_id": 266347, "author": "Electrons_Ahoy", "author_id": 19074, "author_profile": "https://Stackoverflow.com/users/19074", "pm_score": 3, "selected": false, "text": "<p>Here's how we've been doing it:</p>\n\n<pre><code>&lt;a href=\"#\" onClick=\"goThere(); return false;\"&gt;Go to new page&lt;/a&gt;`\n\nfunction goThere() \n{ \n if( confirm(\"Are you sure?\") ) \n { \n window.location.href=\"newPage.aspx\"; \n } \n}\n</code></pre>\n\n<p>(EDIT: Code reformatted to avoid horizontal scroll)</p>\n" }, { "answer_id": 266349, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;a href=\"http://...\" onclick=\"return confirm('are you sure?')\"&gt;text&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 266430, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 1, "selected": false, "text": "<p>A class-binding version (no need for inline onclick attributes): link this external &lt; script> after all confirmable controls:</p>\n\n<pre><code>// dangerous - warnings on potentially harmful actions\n// usage: add class=\"dangerous\" to &lt;a&gt;, &lt;input&gt; or &lt;button&gt;\n// Optionally add custom confirmation message to title attribute\n\nfunction dangerous_bind() {\n var lists= [\n document.getElementsByTagName('input'),\n document.getElementsByTagName('button'),\n document.getElementsByTagName('a')\n ];\n for (var listi= lists.length; listi--&gt;0;) { var els= lists[listi];\n for (var eli= els.length; eli--&gt;0;) { var el= els[eli];\n if (array_contains(el.className.split(' '), 'dangerous'))\n el.onclick= dangerous_click;\n }\n }\n}\n\nfunction array_contains(a, x) {\n for (var i= a.length; i--&gt;0;)\n if (a[i]==x) return true;\n return false;\n}\n\nfunction dangerous_click() {\n return confirm(this.title || 'Are you sure?');\n}\n\ndangerous_bind();\n</code></pre>\n\n<p>This is a slightly long-winded due to the binding working on submits/buttons as well. Generally though it makes sense to have ‘dangerous’ options you will want to confirm on buttons rather than links. GET requests as fired by links shouldn't really have any active effect.</p>\n" }, { "answer_id": 266432, "author": "Josh", "author_id": 2204759, "author_profile": "https://Stackoverflow.com/users/2204759", "pm_score": 2, "selected": false, "text": "<p>In jquery it is something like:</p>\n\n<pre><code>$(\"a\").click(function() {if(confirm('yadda yadda')) event.stopPropagation();});\n</code></pre>\n\n<p>If I understand what jgreep mentioned, if you only want the confirm to appear on a few links, you would bind the click handler only to links with the right class. You could do this only for anchors or for any html element that has the class.</p>\n\n<pre><code>$(\".conf\").click(function() {if(confirm('yadda yadda')) event.stopPropagation();});\n</code></pre>\n" }, { "answer_id": 266435, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": "<pre><code>var links = document.getElementsByTagName('A');\n\nfor (var i = 0; i &lt; links.length; i++)\n{ \n links[i].onclick = function ()\n { \n return Confirm(\"Are you sure?\");\n }\n}\n</code></pre>\n\n<p>This applies the message to all links, however its a little harder to make the links not work without javascript automatically (actually its impossible).</p>\n" }, { "answer_id": 266443, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 5, "selected": true, "text": "<p><strong>Unobtrusive Javascript</strong></p>\n\n<p>The best practice is to add event handler methods to the links.</p>\n\n<p>The <em>confirm()</em> function produces the dialog box you described, and returns true or false depending on the user's choice.</p>\n\n<p>Event handler methods on links have a special behavior, which is that they kill the link action if they return false.</p>\n\n<pre><code>var link = document.getElementById('confirmToFollow');\n\nlink.onclick = function () {\n return confirm(\"Are you sure?\");\n};\n</code></pre>\n\n<p>If you want the link to <strong>require javascript</strong>, the HTML must be edited. Remove the href:</p>\n\n<pre><code>&lt;a href=\"#\" id=\"confirmToFollow\"...\n</code></pre>\n\n<p>You can explicitly set the link destination in the event handler:</p>\n\n<pre><code>var link = document.getElementById('confirmToFollow');\n\nlink.onclick = function () {\n if( confirm(\"Are you sure?\") ) {\n window.location = \"http://www.stackoverflow.com/\";\n }\n return false;\n};\n</code></pre>\n\n<p>If you want the same method called on multiple links, you can acquire a nodeList of the links you want, and apply the method to each as you loop through the nodeList:</p>\n\n<pre><code>var allLinks = document.getElementsByTagName('a');\nfor (var i=0; i &lt; allLinks.length; i++) {\n allLinks[i].onclick = function () {\n return confirm(\"Are you sure?\");\n };\n}\n</code></pre>\n\n<p>There are further permutations of the same idea here, such as using a classname to determine which links will listen for the method, and to pass a unique location into each based on some other criteria. They are six of one, half dozen of another.</p>\n\n<p><strong>Alternative Approaches (not encouraged practices):</strong></p>\n\n<p>One <strong>discouraged practice</strong> is to attach a method via an <strong>onclick attribute</strong>:</p>\n\n<pre><code>&lt;a href=\"mypage.html\" onclick=\"...\n</code></pre>\n\n<p>Another <strong>discouraged practice</strong> is to set the <strong>href attribute</strong> to a function call:</p>\n\n<pre><code>&lt;a href=\"javascript: confirmLink() ...\n</code></pre>\n\n<p>Note that these discouraged practices are all working solutions.</p>\n" }, { "answer_id": 266445, "author": "Esteban Küber", "author_id": 34813, "author_profile": "https://Stackoverflow.com/users/34813", "pm_score": 2, "selected": false, "text": "<p>If you are using jQuery you would do:</p>\n\n<pre><code>jQuery(document).ready(\n jQuery(\"a\").click(){\n //you'd place here your extra logic\n document.location.href = this.href;\n }\n);\n</code></pre>\n" }, { "answer_id": 266462, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 1, "selected": false, "text": "<p>Take a look at <a href=\"https://stackoverflow.com/questions/233467/whats-the-best-way-to-open-new-browser-window\">What’s the best way to open new browser window</a>. You can do something similar, but throw up the confirmation prior to opening a new window.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19074/" ]
A pattern that's started to show up a lot in one of the web apps I'm working are links that used to just be a regular a-tag link now need a popup box asking "are you sure?" before the link will go. (If the user hits cancel, nothing happens.) We've got a solution that works, but somehow we're a web app shop without a Javascript expert, so I'm left with this crawling feeling like there's a better way to get the job done. So, JS experts, what's the most standards-compliant, cross-browser way to get this done? (For the record, this is already a site that requires JS, so no need to have a "non-JS" version. But, it does need to work in any and all reasonably modern browsers.) (Also, for bonus points it would be nice if people with JS turned off didn't have the links work, rather than bypassing the confirm box.)
**Unobtrusive Javascript** The best practice is to add event handler methods to the links. The *confirm()* function produces the dialog box you described, and returns true or false depending on the user's choice. Event handler methods on links have a special behavior, which is that they kill the link action if they return false. ``` var link = document.getElementById('confirmToFollow'); link.onclick = function () { return confirm("Are you sure?"); }; ``` If you want the link to **require javascript**, the HTML must be edited. Remove the href: ``` <a href="#" id="confirmToFollow"... ``` You can explicitly set the link destination in the event handler: ``` var link = document.getElementById('confirmToFollow'); link.onclick = function () { if( confirm("Are you sure?") ) { window.location = "http://www.stackoverflow.com/"; } return false; }; ``` If you want the same method called on multiple links, you can acquire a nodeList of the links you want, and apply the method to each as you loop through the nodeList: ``` var allLinks = document.getElementsByTagName('a'); for (var i=0; i < allLinks.length; i++) { allLinks[i].onclick = function () { return confirm("Are you sure?"); }; } ``` There are further permutations of the same idea here, such as using a classname to determine which links will listen for the method, and to pass a unique location into each based on some other criteria. They are six of one, half dozen of another. **Alternative Approaches (not encouraged practices):** One **discouraged practice** is to attach a method via an **onclick attribute**: ``` <a href="mypage.html" onclick="... ``` Another **discouraged practice** is to set the **href attribute** to a function call: ``` <a href="javascript: confirmLink() ... ``` Note that these discouraged practices are all working solutions.
266,357
<p>I have been trying to tokenize a string using SPACE as delimiter but it doesn't work. Does any one have suggestion on why it doesn't work?</p> <p>Edit: tokenizing using:</p> <pre><code>strtok(string, " "); </code></pre> <p>The code is like the following</p> <pre><code>pch = strtok (str," "); while (pch != NULL) { printf ("%s\n",pch); pch = strtok (NULL, " "); } </code></pre>
[ { "answer_id": 266381, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 0, "selected": false, "text": "<p>When reading the strtok documentation, I see you need to pass in a NULL pointer after the first \"initializing\" call. Maybe you didn't do that. Just a guess of course.</p>\n" }, { "answer_id": 266405, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 6, "selected": false, "text": "<p>Do it like this:</p>\n\n<pre><code>char s[256];\nstrcpy(s, \"one two three\");\nchar* token = strtok(s, \" \");\nwhile (token) {\n printf(\"token: %s\\n\", token);\n token = strtok(NULL, \" \");\n}\n</code></pre>\n\n<p>Note: <code>strtok</code> modifies the string its tokenising, so it cannot be a <code>const char*</code>. </p>\n" }, { "answer_id": 266407, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 5, "selected": false, "text": "<p>Here's an example of <code>strtok</code> usage, keep in mind that <code>strtok</code> is destructive of its input string (and therefore can't <em>ever</em> be used on a string constant</p>\n\n<pre><code>char *p = strtok(str, \" \");\nwhile(p != NULL) {\n printf(\"%s\\n\", p);\n p = strtok(NULL, \" \");\n}\n</code></pre>\n\n<p>Basically the thing to note is that passing a <code>NULL</code> as the first parameter to <code>strtok</code> tells it to get the next token from the string it was previously tokenizing.</p>\n" }, { "answer_id": 266425, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 2, "selected": false, "text": "<p>You can simplify the code by introducing an extra variable.</p>\n\n<pre><code>#include &lt;string.h&gt;\n#include &lt;stdio.h&gt;\n\nint main()\n{\n char str[100], *s = str, *t = NULL;\n\n strcpy(str, \"a space delimited string\");\n while ((t = strtok(s, \" \")) != NULL) {\n s = NULL;\n printf(\":%s:\\n\", t);\n }\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 266478, "author": "Kieveli", "author_id": 15852, "author_profile": "https://Stackoverflow.com/users/15852", "pm_score": 3, "selected": false, "text": "<p>strtok can be very dangerous. It is not thread safe. Its intended use is to be called over and over in a loop, passing in the output from the previous call. The strtok function has an internal variable that stores the state of the strtok call. This state is not unique to each thread - it is global. If any other code uses strtok in another thread, you get problems. Not the kind of problems you want to track down either!</p>\n\n<p>I'd recommend looking for a regex implementation, or using sscanf to pull apart the string.</p>\n\n<p>Try this:</p>\n\n<pre><code>char strprint[256];\nchar text[256];\nstrcpy(text, \"My string to test\");\nwhile ( sscanf( text, \"%s %s\", strprint, text) &gt; 0 ) {\n printf(\"token: %s\\n\", strprint);\n}\n</code></pre>\n\n<p>Note: The 'text' string is destroyed as it's separated. This may not be the preferred behaviour =)</p>\n" }, { "answer_id": 18580007, "author": "Fernando", "author_id": 2740941, "author_profile": "https://Stackoverflow.com/users/2740941", "pm_score": 2, "selected": false, "text": "<p>I've made some string functions in order to split values, by using less pointers as I could because this code is intended to run on PIC18F processors. Those processors does not handle really good with pointers when you have few free RAM available:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\nchar POSTREQ[255] = \"pwd=123456&amp;apply=Apply&amp;d1=88&amp;d2=100&amp;pwr=1&amp;mpx=Internal&amp;stmo=Stereo&amp;proc=Processor&amp;cmp=Compressor&amp;ip1=192&amp;ip2=168&amp;ip3=10&amp;ip4=131&amp;gw1=192&amp;gw2=168&amp;gw3=10&amp;gw4=192&amp;pt=80&amp;lic=&amp;A=A\";\n\nint findchar(char *string, int Start, char C) {\n while((string[Start] != 0)) { Start++; if(string[Start] == C) return Start; }\n return -1;\n}\n\nint findcharn(char *string, int Times, char C) {\n int i = 0, pos = 0, fnd = 0;\n\n while(i &lt; Times) {\n fnd = findchar(string, pos, C);\n if(fnd &lt; 0) return -1;\n if(fnd &gt; 0) pos = fnd;\n i++;\n }\n return fnd;\n}\n\nvoid mid(char *in, char *out, int start, int end) {\n int i = 0;\n int size = end - start;\n\n for(i = 0; i &lt; size; i++){\n out[i] = in[start + i + 1];\n }\n out[size] = 0;\n}\n\nvoid getvalue(char *out, int index) {\n mid(POSTREQ, out, findcharn(POSTREQ, index, '='), (findcharn(POSTREQ, index, '&amp;') - 1));\n}\n\nvoid main() {\n char n_pwd[7];\n char n_d1[7];\n\n getvalue(n_d1, 1);\n\n printf(\"Value: %s\\n\", n_d1);\n} \n</code></pre>\n" }, { "answer_id": 19721184, "author": "jitsceait", "author_id": 2671935, "author_profile": "https://Stackoverflow.com/users/2671935", "pm_score": -1, "selected": false, "text": "<pre><code>int not_in_delimiter(char c, char *delim){\n\n while(*delim != '\\0'){\n if(c == *delim) return 0;\n delim++;\n }\n return 1;\n}\n\nchar *token_separater(char *source, char *delimiter, char **last){\n\nchar *begin, *next_token;\nchar *sbegin;\n\n/*Get the start of the token */\nif(source)\n begin = source;\nelse\n begin = *last;\n\nsbegin = begin;\n\n/*Scan through the string till we find character in delimiter. */\nwhile(*begin != '\\0' &amp;&amp; not_in_delimiter(*begin, delimiter)){\n begin++;\n}\n\n/* Check if we have reached at of the string */\nif(*begin == '\\0') {\n/* We dont need to come further, hence return NULL*/\n *last = NULL;\n return sbegin;\n}\n/* Scan the string till we find a character which is not in delimiter */\n next_token = begin;\n while(next_token != '\\0' &amp;&amp; !not_in_delimiter(*next_token, delimiter)) {\n next_token++;\n }\n /* If we have not reached at the end of the string */\n if(*next_token != '\\0'){\n *last = next_token--;\n *next_token = '\\0';\n return sbegin;\n}\n}\n\n void main(){\n\n char string[10] = \"abcb_dccc\";\n char delim[10] = \"_\";\n char *token = NULL;\n char *last = \"\" ;\n token = token_separater(string, delim, &amp;last);\n printf(\"%s\\n\", token);\n while(last){\n token = token_separater(NULL, delim, &amp;last);\n printf(\"%s\\n\", token);\n }\n</code></pre>\n\n<p>}</p>\n\n<p>You can read detail analysis at blog mentioned in my profile :)</p>\n" }, { "answer_id": 35493995, "author": "fnisi", "author_id": 1884351, "author_profile": "https://Stackoverflow.com/users/1884351", "pm_score": 0, "selected": false, "text": "<p>Here is another <code>strtok()</code> implementation, which has the ability to recognize consecutive delimiters (standard library's <code>strtok()</code> does not have this)</p>\n\n<p>The function is a part of BSD licensed string library, called <a href=\"https://github.com/fnoyanisi/zString\" rel=\"nofollow\">zString</a>. You are more than welcome to contribute :)</p>\n\n<p><a href=\"https://github.com/fnoyanisi/zString\" rel=\"nofollow\">https://github.com/fnoyanisi/zString</a></p>\n\n<pre><code>char *zstring_strtok(char *str, const char *delim) {\n static char *static_str=0; /* var to store last address */\n int index=0, strlength=0; /* integers for indexes */\n int found = 0; /* check if delim is found */\n\n /* delimiter cannot be NULL\n * if no more char left, return NULL as well\n */\n if (delim==0 || (str == 0 &amp;&amp; static_str == 0))\n return 0;\n\n if (str == 0)\n str = static_str;\n\n /* get length of string */\n while(str[strlength])\n strlength++;\n\n /* find the first occurance of delim */\n for (index=0;index&lt;strlength;index++)\n if (str[index]==delim[0]) {\n found=1;\n break;\n }\n\n /* if delim is not contained in str, return str */\n if (!found) {\n static_str = 0;\n return str;\n }\n\n /* check for consecutive delimiters\n *if first char is delim, return delim\n */\n if (str[0]==delim[0]) {\n static_str = (str + 1);\n return (char *)delim;\n }\n\n /* terminate the string\n * this assignmetn requires char[], so str has to\n * be char[] rather than *char\n */\n str[index] = '\\0';\n\n /* save the rest of the string */\n if ((str + index + 1)!=0)\n static_str = (str + index + 1);\n else\n static_str = 0;\n\n return str;\n}\n</code></pre>\n\n<p>As mentioned in previous posts, since <code>strtok()</code>, or the one I implmented above, relies on a <code>static *char</code> variable to preserve the location of last delimiter between consecutive calls, extra care should be taken while dealing with multi-threaded aplications.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/382480/" ]
I have been trying to tokenize a string using SPACE as delimiter but it doesn't work. Does any one have suggestion on why it doesn't work? Edit: tokenizing using: ``` strtok(string, " "); ``` The code is like the following ``` pch = strtok (str," "); while (pch != NULL) { printf ("%s\n",pch); pch = strtok (NULL, " "); } ```
Do it like this: ``` char s[256]; strcpy(s, "one two three"); char* token = strtok(s, " "); while (token) { printf("token: %s\n", token); token = strtok(NULL, " "); } ``` Note: `strtok` modifies the string its tokenising, so it cannot be a `const char*`.
266,364
<p>I've got a DB table where we store a lot of MD5 hashes (and yes I know that they aren't 100% unique...) where we have a lot of comparison queries against those strings. This table can become quite large with over 5M rows.</p> <p>My question is this: Is it wise to keep the data as hexadecimal strings or should I convert the hex to binary or decimals for better querying?</p>
[ { "answer_id": 266381, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 0, "selected": false, "text": "<p>When reading the strtok documentation, I see you need to pass in a NULL pointer after the first \"initializing\" call. Maybe you didn't do that. Just a guess of course.</p>\n" }, { "answer_id": 266405, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 6, "selected": false, "text": "<p>Do it like this:</p>\n\n<pre><code>char s[256];\nstrcpy(s, \"one two three\");\nchar* token = strtok(s, \" \");\nwhile (token) {\n printf(\"token: %s\\n\", token);\n token = strtok(NULL, \" \");\n}\n</code></pre>\n\n<p>Note: <code>strtok</code> modifies the string its tokenising, so it cannot be a <code>const char*</code>. </p>\n" }, { "answer_id": 266407, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 5, "selected": false, "text": "<p>Here's an example of <code>strtok</code> usage, keep in mind that <code>strtok</code> is destructive of its input string (and therefore can't <em>ever</em> be used on a string constant</p>\n\n<pre><code>char *p = strtok(str, \" \");\nwhile(p != NULL) {\n printf(\"%s\\n\", p);\n p = strtok(NULL, \" \");\n}\n</code></pre>\n\n<p>Basically the thing to note is that passing a <code>NULL</code> as the first parameter to <code>strtok</code> tells it to get the next token from the string it was previously tokenizing.</p>\n" }, { "answer_id": 266425, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 2, "selected": false, "text": "<p>You can simplify the code by introducing an extra variable.</p>\n\n<pre><code>#include &lt;string.h&gt;\n#include &lt;stdio.h&gt;\n\nint main()\n{\n char str[100], *s = str, *t = NULL;\n\n strcpy(str, \"a space delimited string\");\n while ((t = strtok(s, \" \")) != NULL) {\n s = NULL;\n printf(\":%s:\\n\", t);\n }\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 266478, "author": "Kieveli", "author_id": 15852, "author_profile": "https://Stackoverflow.com/users/15852", "pm_score": 3, "selected": false, "text": "<p>strtok can be very dangerous. It is not thread safe. Its intended use is to be called over and over in a loop, passing in the output from the previous call. The strtok function has an internal variable that stores the state of the strtok call. This state is not unique to each thread - it is global. If any other code uses strtok in another thread, you get problems. Not the kind of problems you want to track down either!</p>\n\n<p>I'd recommend looking for a regex implementation, or using sscanf to pull apart the string.</p>\n\n<p>Try this:</p>\n\n<pre><code>char strprint[256];\nchar text[256];\nstrcpy(text, \"My string to test\");\nwhile ( sscanf( text, \"%s %s\", strprint, text) &gt; 0 ) {\n printf(\"token: %s\\n\", strprint);\n}\n</code></pre>\n\n<p>Note: The 'text' string is destroyed as it's separated. This may not be the preferred behaviour =)</p>\n" }, { "answer_id": 18580007, "author": "Fernando", "author_id": 2740941, "author_profile": "https://Stackoverflow.com/users/2740941", "pm_score": 2, "selected": false, "text": "<p>I've made some string functions in order to split values, by using less pointers as I could because this code is intended to run on PIC18F processors. Those processors does not handle really good with pointers when you have few free RAM available:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\nchar POSTREQ[255] = \"pwd=123456&amp;apply=Apply&amp;d1=88&amp;d2=100&amp;pwr=1&amp;mpx=Internal&amp;stmo=Stereo&amp;proc=Processor&amp;cmp=Compressor&amp;ip1=192&amp;ip2=168&amp;ip3=10&amp;ip4=131&amp;gw1=192&amp;gw2=168&amp;gw3=10&amp;gw4=192&amp;pt=80&amp;lic=&amp;A=A\";\n\nint findchar(char *string, int Start, char C) {\n while((string[Start] != 0)) { Start++; if(string[Start] == C) return Start; }\n return -1;\n}\n\nint findcharn(char *string, int Times, char C) {\n int i = 0, pos = 0, fnd = 0;\n\n while(i &lt; Times) {\n fnd = findchar(string, pos, C);\n if(fnd &lt; 0) return -1;\n if(fnd &gt; 0) pos = fnd;\n i++;\n }\n return fnd;\n}\n\nvoid mid(char *in, char *out, int start, int end) {\n int i = 0;\n int size = end - start;\n\n for(i = 0; i &lt; size; i++){\n out[i] = in[start + i + 1];\n }\n out[size] = 0;\n}\n\nvoid getvalue(char *out, int index) {\n mid(POSTREQ, out, findcharn(POSTREQ, index, '='), (findcharn(POSTREQ, index, '&amp;') - 1));\n}\n\nvoid main() {\n char n_pwd[7];\n char n_d1[7];\n\n getvalue(n_d1, 1);\n\n printf(\"Value: %s\\n\", n_d1);\n} \n</code></pre>\n" }, { "answer_id": 19721184, "author": "jitsceait", "author_id": 2671935, "author_profile": "https://Stackoverflow.com/users/2671935", "pm_score": -1, "selected": false, "text": "<pre><code>int not_in_delimiter(char c, char *delim){\n\n while(*delim != '\\0'){\n if(c == *delim) return 0;\n delim++;\n }\n return 1;\n}\n\nchar *token_separater(char *source, char *delimiter, char **last){\n\nchar *begin, *next_token;\nchar *sbegin;\n\n/*Get the start of the token */\nif(source)\n begin = source;\nelse\n begin = *last;\n\nsbegin = begin;\n\n/*Scan through the string till we find character in delimiter. */\nwhile(*begin != '\\0' &amp;&amp; not_in_delimiter(*begin, delimiter)){\n begin++;\n}\n\n/* Check if we have reached at of the string */\nif(*begin == '\\0') {\n/* We dont need to come further, hence return NULL*/\n *last = NULL;\n return sbegin;\n}\n/* Scan the string till we find a character which is not in delimiter */\n next_token = begin;\n while(next_token != '\\0' &amp;&amp; !not_in_delimiter(*next_token, delimiter)) {\n next_token++;\n }\n /* If we have not reached at the end of the string */\n if(*next_token != '\\0'){\n *last = next_token--;\n *next_token = '\\0';\n return sbegin;\n}\n}\n\n void main(){\n\n char string[10] = \"abcb_dccc\";\n char delim[10] = \"_\";\n char *token = NULL;\n char *last = \"\" ;\n token = token_separater(string, delim, &amp;last);\n printf(\"%s\\n\", token);\n while(last){\n token = token_separater(NULL, delim, &amp;last);\n printf(\"%s\\n\", token);\n }\n</code></pre>\n\n<p>}</p>\n\n<p>You can read detail analysis at blog mentioned in my profile :)</p>\n" }, { "answer_id": 35493995, "author": "fnisi", "author_id": 1884351, "author_profile": "https://Stackoverflow.com/users/1884351", "pm_score": 0, "selected": false, "text": "<p>Here is another <code>strtok()</code> implementation, which has the ability to recognize consecutive delimiters (standard library's <code>strtok()</code> does not have this)</p>\n\n<p>The function is a part of BSD licensed string library, called <a href=\"https://github.com/fnoyanisi/zString\" rel=\"nofollow\">zString</a>. You are more than welcome to contribute :)</p>\n\n<p><a href=\"https://github.com/fnoyanisi/zString\" rel=\"nofollow\">https://github.com/fnoyanisi/zString</a></p>\n\n<pre><code>char *zstring_strtok(char *str, const char *delim) {\n static char *static_str=0; /* var to store last address */\n int index=0, strlength=0; /* integers for indexes */\n int found = 0; /* check if delim is found */\n\n /* delimiter cannot be NULL\n * if no more char left, return NULL as well\n */\n if (delim==0 || (str == 0 &amp;&amp; static_str == 0))\n return 0;\n\n if (str == 0)\n str = static_str;\n\n /* get length of string */\n while(str[strlength])\n strlength++;\n\n /* find the first occurance of delim */\n for (index=0;index&lt;strlength;index++)\n if (str[index]==delim[0]) {\n found=1;\n break;\n }\n\n /* if delim is not contained in str, return str */\n if (!found) {\n static_str = 0;\n return str;\n }\n\n /* check for consecutive delimiters\n *if first char is delim, return delim\n */\n if (str[0]==delim[0]) {\n static_str = (str + 1);\n return (char *)delim;\n }\n\n /* terminate the string\n * this assignmetn requires char[], so str has to\n * be char[] rather than *char\n */\n str[index] = '\\0';\n\n /* save the rest of the string */\n if ((str + index + 1)!=0)\n static_str = (str + index + 1);\n else\n static_str = 0;\n\n return str;\n}\n</code></pre>\n\n<p>As mentioned in previous posts, since <code>strtok()</code>, or the one I implmented above, relies on a <code>static *char</code> variable to preserve the location of last delimiter between consecutive calls, extra care should be taken while dealing with multi-threaded aplications.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've got a DB table where we store a lot of MD5 hashes (and yes I know that they aren't 100% unique...) where we have a lot of comparison queries against those strings. This table can become quite large with over 5M rows. My question is this: Is it wise to keep the data as hexadecimal strings or should I convert the hex to binary or decimals for better querying?
Do it like this: ``` char s[256]; strcpy(s, "one two three"); char* token = strtok(s, " "); while (token) { printf("token: %s\n", token); token = strtok(NULL, " "); } ``` Note: `strtok` modifies the string its tokenising, so it cannot be a `const char*`.
266,371
<p>In VIM in command line mode a "%" denotes the current file, "cword" denotes the current word under the cursor. I want to create a shortcut where I need the current line number. What is the symbol which denotes this?</p>
[ { "answer_id": 266386, "author": "WMR", "author_id": 2844, "author_profile": "https://Stackoverflow.com/users/2844", "pm_score": 4, "selected": false, "text": "<p>. (dot) stands for the current line.</p>\n\n<p>To clarify:\nThis is meant for stuff like <code>:1,.s/foo/bar/g</code> which will transform every <code>foo</code> to <code>bar</code> from the beginning of the file up to the current line. </p>\n\n<p>I don't know know of a way to get the current line number expanded for a shell command, which is what you are trying to do by doing <code>:!echo .</code></p>\n\n<p>You can find out about the expansions that are done (like <code>%</code> and <code>#</code> for example) in <code>:he cmdline-special</code>. </p>\n" }, { "answer_id": 267827, "author": "Oli", "author_id": 22035, "author_profile": "https://Stackoverflow.com/users/22035", "pm_score": 1, "selected": false, "text": "<p>Commands in vim works on the current line so:</p>\n\n<pre><code>:s/foo/bar/g\n</code></pre>\n\n<p>will transform every <em>foo</em> in <em>bar</em> on the line you are currently on.</p>\n" }, { "answer_id": 267870, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": false, "text": "<p>To return the line number of current line at bottom of screen, use:</p>\n\n<pre><code>:.= \n</code></pre>\n" }, { "answer_id": 273678, "author": "Brian Carper", "author_id": 23070, "author_profile": "https://Stackoverflow.com/users/23070", "pm_score": 5, "selected": true, "text": "<p>If you want to pass the current line number to a shell command, you could do</p>\n\n<pre><code>:exe \"!echo \" . line(\".\")\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29653/" ]
In VIM in command line mode a "%" denotes the current file, "cword" denotes the current word under the cursor. I want to create a shortcut where I need the current line number. What is the symbol which denotes this?
If you want to pass the current line number to a shell command, you could do ``` :exe "!echo " . line(".") ```
266,389
<p>What's the easiest programmatic way to restart a service on a remote Windows system? Language or method doesn't matter as long as it doesn't require human interaction.</p>
[ { "answer_id": 266419, "author": "Raz", "author_id": 5661, "author_profile": "https://Stackoverflow.com/users/5661", "pm_score": 1, "selected": false, "text": "<p>look at <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb897542.aspx\" rel=\"nofollow noreferrer\">sysinternals</a> for a variety of tools to help you achieve that goal. psService for example would restart a service on a remote machine. </p>\n" }, { "answer_id": 266423, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 8, "selected": true, "text": "<p>As of Windows XP, you can use <code>sc.exe</code> to interact with local and remote services. Schedule a task to run a batch file similar to this:</p>\n\n<pre>\nsc \\\\server stop service\nsc \\\\server start service\n</pre>\n\n<p>Make sure the task runs under a user account privileged on the target server.</p>\n\n<p><code>psservice.exe</code> from the <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896649.aspx\" rel=\"noreferrer\">Sysinternals PSTools</a> would also be doing the job:</p>\n\n<pre>\npsservice \\\\server restart service\n</pre>\n" }, { "answer_id": 266434, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 4, "selected": false, "text": "<p>DESCRIPTION:\n SC is a command line program used for communicating with the\n NT Service Controller and services.\nUSAGE:\n sc [command] [service name] ...</p>\n\n<pre><code> The option &lt;server&gt; has the form \"\\\\ServerName\"\n Further help on commands can be obtained by typing: \"sc [command]\"\n Commands:\n query-----------Queries the status for a service, or\n enumerates the status for types of services.\n queryex---------Queries the extended status for a service, or\n enumerates the status for types of services.\n start-----------Starts a service.\n pause-----------Sends a PAUSE control request to a service.\n interrogate-----Sends an INTERROGATE control request to a service.\n continue--------Sends a CONTINUE control request to a service.\n stop------------Sends a STOP request to a service.\n config----------Changes the configuration of a service (persistant).\n description-----Changes the description of a service.\n failure---------Changes the actions taken by a service upon failure.\n qc--------------Queries the configuration information for a service.\n qdescription----Queries the description for a service.\n qfailure--------Queries the actions taken by a service upon failure.\n delete----------Deletes a service (from the registry).\n create----------Creates a service. (adds it to the registry).\n control---------Sends a control to a service.\n sdshow----------Displays a service's security descriptor.\n sdset-----------Sets a service's security descriptor.\n GetDisplayName--Gets the DisplayName for a service.\n GetKeyName------Gets the ServiceKeyName for a service.\n EnumDepend------Enumerates Service Dependencies.\n\n The following commands don't require a service name:\n sc &lt;server&gt; &lt;command&gt; &lt;option&gt;\n boot------------(ok | bad) Indicates whether the last boot should\n be saved as the last-known-good boot configuration\n Lock------------Locks the Service Database\n QueryLock-------Queries the LockStatus for the SCManager Database\n</code></pre>\n\n<p>EXAMPLE:\n sc start MyService</p>\n" }, { "answer_id": 266463, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 1, "selected": false, "text": "<p>I recommend the method given by doofledorfer.</p>\n\n<p>If you really want to do it via a direct API call, then look at the <a href=\"http://msdn.microsoft.com/en-us/library/ms684323(VS.85).aspx\" rel=\"nofollow noreferrer\">OpenSCManager function</a>. Below are sample functions to take a machine name and service, and stop or start them.</p>\n\n<pre><code>function ServiceStart(sMachine, sService : string) : boolean; //start service, return TRUE if successful\nvar schm, schs : SC_Handle;\n ss : TServiceStatus;\n psTemp : PChar;\n dwChkP : DWord;\nbegin\n ss.dwCurrentState := 0;\n schm := OpenSCManager(PChar(sMachine),Nil,SC_MANAGER_CONNECT); //connect to the service control manager\n\n if(schm &gt; 0)then begin // if successful...\n schs := OpenService( schm,PChar(sService),SERVICE_START or SERVICE_QUERY_STATUS); // open service handle, start and query status\n if(schs &gt; 0)then begin // if successful...\n psTemp := nil;\n if (StartService(schs,0,psTemp)) and (QueryServiceStatus(schs,ss)) then\n while(SERVICE_RUNNING &lt;&gt; ss.dwCurrentState)do begin\n dwChkP := ss.dwCheckPoint; //dwCheckPoint contains a value incremented periodically to report progress of a long operation. Store it.\n Sleep(ss.dwWaitHint); //Sleep for recommended time before checking status again\n if(not QueryServiceStatus(schs,ss))then\n break; //couldn't check status\n if(ss.dwCheckPoint &lt; dwChkP)then\n Break; //if QueryServiceStatus didn't work for some reason, avoid infinite loop\n end; //while not running\n CloseServiceHandle(schs);\n end; //if able to get service handle\n CloseServiceHandle(schm);\n end; //if able to get svc mgr handle\n Result := SERVICE_RUNNING = ss.dwCurrentState; //if we were able to start it, return true\nend;\n\nfunction ServiceStop(sMachine, sService : string) : boolean; //stop service, return TRUE if successful\nvar schm, schs : SC_Handle;\n ss : TServiceStatus;\n dwChkP : DWord;\nbegin\n schm := OpenSCManager(PChar(sMachine),nil,SC_MANAGER_CONNECT);\n\n if(schm &gt; 0)then begin\n schs := OpenService(schm,PChar(sService),SERVICE_STOP or SERVICE_QUERY_STATUS);\n if(schs &gt; 0)then begin\n if (ControlService(schs,SERVICE_CONTROL_STOP,ss)) and (QueryServiceStatus(schs,ss)) then\n while(SERVICE_STOPPED &lt;&gt; ss.dwCurrentState) do begin\n dwChkP := ss.dwCheckPoint;\n Sleep(ss.dwWaitHint);\n if(not QueryServiceStatus(schs,ss))then\n Break;\n\n if(ss.dwCheckPoint &lt; dwChkP)then\n Break;\n end; //while\n CloseServiceHandle(schs);\n end; //if able to get svc handle\n CloseServiceHandle(schm);\n end; //if able to get svc mgr handle\n Result := SERVICE_STOPPED = ss.dwCurrentState;\nend;\n</code></pre>\n" }, { "answer_id": 266471, "author": "Ta01", "author_id": 7280, "author_profile": "https://Stackoverflow.com/users/7280", "pm_score": 2, "selected": false, "text": "<p>If it doesn't require human interaction which means there will be no UI that invokes this operation and I assume it would restart at some set interval? If you have access to machine, you could just set a scheduled task to execute a batch file using good old NET STOP and NET START</p>\n\n<pre><code>net stop \"DNS Client\"\nnet start \"DNS client\"\n</code></pre>\n\n<p>or if you want to get a little more sophisticated, you could try <a href=\"http://thepowershellguy.com/blogs/posh/archive/2007/01/03/powershell-using-net-to-manage-remote-services.aspx\" rel=\"nofollow noreferrer\">Powershell</a></p>\n" }, { "answer_id": 330296, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<ol>\n<li>open service control manager database using openscmanager</li>\n<li>get dependent service using EnumDependService()</li>\n<li>Stop all dependent services using ChangeConfig() sending STOP signal to this function if they are started</li>\n<li>stop actual service</li>\n<li>Get all Services dependencies of a service</li>\n<li>Start all services dependencies using StartService() if they are stopped</li>\n<li>Start actual service</li>\n</ol>\n\n<p>Thus your service is restarted taking care all dependencies.</p>\n" }, { "answer_id": 30847542, "author": "ambassallo", "author_id": 2616446, "author_profile": "https://Stackoverflow.com/users/2616446", "pm_score": 2, "selected": false, "text": "<p>There will be so many instances where the service will go in to \"stop pending\".The Operating system will complain that it was \"Not able to stop the service xyz.\" In case you want to make absolutely sure the service is restarted you should kill the process instead. You can do that by doing the following in a bat file</p>\n\n<pre><code>taskkill /F /IM processname.exe\ntimeout 20\nsc start servicename\n</code></pre>\n\n<p>To find out which process is associated with your service, go to task manager--> Services tab-->Right Click on your Service--> Go to process.</p>\n\n<p>Note that this should be a work around until you figure out why your service had to be restarted in the first place. You should look for memory leaks, infinite loops and other such conditions for your service to have become unresponsive.</p>\n" }, { "answer_id": 32522511, "author": "ShaneC", "author_id": 2191599, "author_profile": "https://Stackoverflow.com/users/2191599", "pm_score": 2, "selected": false, "text": "<p>As of Powershell v3, PSsessions allow for any native cmdlet to be run on a remote machine</p>\n\n<pre><code>$session = New-PSsession -Computername \"YourServerName\"\nInvoke-Command -Session $Session -ScriptBlock {Restart-Service \"YourServiceName\"}\nRemove-PSSession $Session\n</code></pre>\n\n<p>See <a href=\"https://technet.microsoft.com/en-us/library/hh849717.aspx\" rel=\"nofollow\">here</a> for more information</p>\n" }, { "answer_id": 38340439, "author": "Medos", "author_id": 675440, "author_profile": "https://Stackoverflow.com/users/675440", "pm_score": 0, "selected": false, "text": "<p>I believe PowerShell now trumps the \"sc\" command in terms of simplicity:</p>\n\n<pre><code>Restart-Service \"servicename\"\n</code></pre>\n" }, { "answer_id": 59226500, "author": "Kishore Kumar", "author_id": 823369, "author_profile": "https://Stackoverflow.com/users/823369", "pm_score": 0, "selected": false, "text": "<p>This is what I do when I have restart a service remotely with different account</p>\n\n<p>Open a CMD with different login</p>\n\n<pre><code>runas /noprofile /user:DOMAIN\\USERNAME cmd\n</code></pre>\n\n<p>Use SC to stop and start</p>\n\n<pre><code>sc \\\\SERVERNAME query Tomcat8\nsc \\\\SERVERNAME stop Tomcat8\nsc \\\\SERVERNAME start Tomcat8\n</code></pre>\n" }, { "answer_id": 64269737, "author": "David Rogers", "author_id": 2912011, "author_profile": "https://Stackoverflow.com/users/2912011", "pm_score": 0, "selected": false, "text": "<p>If you attempting to do this on a server on <strong>different domain</strong> you will need to a little bit more than what has been suggested by most answers so far, this is what I use to accomplish this:</p>\n<pre><code>#Configuration\n$servername = &quot;ABC&quot;,\n$serviceAccountUsername = &quot;XYZ&quot;,\n$serviceAccountPassword = &quot;XXX&quot;\n\n#Establish connection\ntry {\n if (-not ([System.IO.Directory]::Exists('\\\\' + $servername))) {\n net use \\\\$servername /user:$serviceAccountUsername $serviceAccountPassword\n }\n}\ncatch {\n #May already exists, if so just continue\n Write-Output $_.Exception.Message\n}\n\n#Restart Service\nsc.exe \\\\$servername stop &quot;ServiceNameHere&quot;\nsc.exe \\\\$servername start &quot;ServiceNameHere&quot;\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What's the easiest programmatic way to restart a service on a remote Windows system? Language or method doesn't matter as long as it doesn't require human interaction.
As of Windows XP, you can use `sc.exe` to interact with local and remote services. Schedule a task to run a batch file similar to this: ``` sc \\server stop service sc \\server start service ``` Make sure the task runs under a user account privileged on the target server. `psservice.exe` from the [Sysinternals PSTools](http://technet.microsoft.com/en-us/sysinternals/bb896649.aspx) would also be doing the job: ``` psservice \\server restart service ```
266,395
<p>I have a git repository which tracks an svn repository. I cloned it using <code>--stdlayout</code>.</p> <p>I created a new local branch via <code>git checkout -b foobar</code></p> <p>Now I want this branch to end up in <code>…/branches/foobar</code> in the svn repository.</p> <p>How do I go about that?</p> <p>(snipped lots of investigative text. see question history if you care)</p>
[ { "answer_id": 266561, "author": "kch", "author_id": 13989, "author_profile": "https://Stackoverflow.com/users/13989", "pm_score": 7, "selected": true, "text": "<p>as of git v1.6.1, <code>git svn branch</code> is available.</p>\n\n<p>From the git docs:</p>\n\n<pre>\n branch\n Create a branch in the SVN repository.\n\n -m, --message\n Allows to specify the commit message.\n\n -t, --tag\n Create a tag by using the tags_subdir instead of the branches_subdir\n specified during git svn init.\n</pre>\n\n<p>Previous versions of git do not provide a way to create an svn branch.</p>\n" }, { "answer_id": 348448, "author": "Bryan J Swift", "author_id": 1357024, "author_profile": "https://Stackoverflow.com/users/1357024", "pm_score": 2, "selected": false, "text": "<p>@kch I just (7 December 2008) compiled the v1.6.1-rc1 tag of git and it does contain the git svn branch command and the documentation for it. So the v1.6.1 release of git should (hopefully) contain this command.</p>\n" }, { "answer_id": 1911069, "author": "Jesper Rønn-Jensen", "author_id": 109305, "author_profile": "https://Stackoverflow.com/users/109305", "pm_score": 8, "selected": false, "text": "<p>I know this question has been answered a while ago, but after reading it, I it might help adding examples of the specific git svn branch command and relate it to a typical workflow.</p>\n\n<p>Like kch answered, use <code>git svn branch</code>. Here is a full example, (note the <code>-n</code> for dry-run to test):</p>\n\n<pre><code>git svn branch -n -m \"Branch for authentication bug\" auth_bug\n</code></pre>\n\n<p>If this goes well, server replies with answer like this:</p>\n\n<blockquote>\n <p>Copying <a href=\"https://scm-server.com/svn/portal/trunk\" rel=\"noreferrer\">https://scm-server.com/svn/portal/trunk</a> at r8914 to <a href=\"https://scm-server.com/svn/portal/branches/auth_bug\" rel=\"noreferrer\">https://scm-server.com/svn/portal/branches/auth_bug</a>...</p>\n</blockquote>\n\n<p>And without the <code>-n</code> switch the server probably adds something like:</p>\n\n<blockquote>\n <p>Found possible branch point: <a href=\"https://scm-server.com/svn/portal/trunk\" rel=\"noreferrer\">https://scm-server.com/svn/portal/trunk</a> => <a href=\"https://scm-server.com/portal/branches/auth_bug\" rel=\"noreferrer\">https://scm-server.com/portal/branches/auth_bug</a>, 8914</p>\n \n <p>Found branch parent:\n (refs/remotes/auth_bug)</p>\n \n <p>d731b1fa028d30d685fe260f5bb912cbf59e1971</p>\n \n <p>Following parent with do_switch</p>\n \n <p>Successfully followed parent r8915 = 6ed10c57afcec62e9077fbeed74a326eaa4863b8</p>\n \n <p>(refs/remotes/auth_bug)</p>\n</blockquote>\n\n<p>The best part of it, now you can create a local branch based on your remote branch like so:</p>\n\n<pre><code>git checkout -b local/auth_bug auth_bug\n</code></pre>\n\n<p>Which means \"check out and create local branch named <code>auth_bug</code> and make it follow the remote branch (last parameter) <code>auth_bug</code></p>\n\n<p>Test that your local branch works on that remote branch by using <code>dcommit</code> with <code>--dry-run</code> (<code>-n</code>):</p>\n\n<pre><code>git svn dcommit -n\n</code></pre>\n\n<p>And SVN server should reply with the new branch name:</p>\n\n<blockquote>\n <p>Committing to <a href=\"https://scm-server.com/svn/portal/branches/auth_bug\" rel=\"noreferrer\">https://scm-server.com/svn/portal/branches/auth_bug</a> ...</p>\n</blockquote>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13989/" ]
I have a git repository which tracks an svn repository. I cloned it using `--stdlayout`. I created a new local branch via `git checkout -b foobar` Now I want this branch to end up in `…/branches/foobar` in the svn repository. How do I go about that? (snipped lots of investigative text. see question history if you care)
as of git v1.6.1, `git svn branch` is available. From the git docs: ``` branch Create a branch in the SVN repository. -m, --message Allows to specify the commit message. -t, --tag Create a tag by using the tags_subdir instead of the branches_subdir specified during git svn init. ``` Previous versions of git do not provide a way to create an svn branch.
266,409
<p>I've got a WAR file that I need to add two files to. Currently, I'm doing this:</p> <pre><code>File war = new File(DIRECTORY, "server.war"); JarOutputStream zos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(war))); //Add file 1 File file = new File(DIRECTORY, "file1.jar"); InputStream is = new BufferedInputStream(new FileInputStream(file)); ZipEntry e = new ZipEntry("file1.jar"); zos.putNextEntry(e); byte[] buf = new byte[1024]; int len; while ((len = is.read(buf, 0, buf.length)) != -1) { zos.write(buf, 0, len); } is.close(); zos.closeEntry(); //repeat for file 2 zos.close(); </code></pre> <p>The result is that the previous contents get clobbered: the WAR has only the 2 files I just added in it. Is there some sort of append mode that I'm not using or what?</p>
[ { "answer_id": 266469, "author": "hark", "author_id": 34826, "author_profile": "https://Stackoverflow.com/users/34826", "pm_score": 3, "selected": false, "text": "<p>Yeah, there's an extra boolean argument to the <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.io.File,%20boolean)\" rel=\"noreferrer\">FileOutputStream constructor</a> which lets you force it to append to the file rather than overwrite it. Change your code to </p>\n\n<pre><code>JarOutputStream zos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(war, True)));\n</code></pre>\n\n<p>and it should work the way you want.</p>\n" }, { "answer_id": 269790, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 3, "selected": true, "text": "<p>It seems this can't be done. I thought it was for a while, but it seems that it wasn't quite having the effect I wanted. Doing it this way resulted in the equivalent of two separate jar files concatinated together. The weird part was that the tools were making some sense of it. JAR found the first, original jar file and read me that. Glassfish's classloader was finding the later, new part, resulting in it loading only the added files as if they were all of the app. Weird.</p>\n\n<p>So I've resurted to creating a new war, adding the contents of the old, adding the new files, closing, and copying the new over the old.</p>\n" }, { "answer_id": 3295117, "author": "Steve K", "author_id": 278800, "author_profile": "https://Stackoverflow.com/users/278800", "pm_score": 0, "selected": false, "text": "<p>I have the same problem; I'm looking for an easy way to update a file in an existing jar file. If it's so easy to do a \"jar uf foo.jar ...\" command, how come there isn't a way to use Java API's to do the same?</p>\n\n<p>Anyway, here is the RFE to add this functionality to Java; it also suggests some work-arounds:</p>\n\n<p><a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4129445\" rel=\"nofollow noreferrer\">http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4129445</a></p>\n\n<p>And here is a library that purports to make this a lot easier, by treating JARs/ZIPs like virtual directories:</p>\n\n<p>https:// truezip.dev.java.net</p>\n\n<p>I haven't figured out yet which approach I'm going to use for my current problem.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4893/" ]
I've got a WAR file that I need to add two files to. Currently, I'm doing this: ``` File war = new File(DIRECTORY, "server.war"); JarOutputStream zos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(war))); //Add file 1 File file = new File(DIRECTORY, "file1.jar"); InputStream is = new BufferedInputStream(new FileInputStream(file)); ZipEntry e = new ZipEntry("file1.jar"); zos.putNextEntry(e); byte[] buf = new byte[1024]; int len; while ((len = is.read(buf, 0, buf.length)) != -1) { zos.write(buf, 0, len); } is.close(); zos.closeEntry(); //repeat for file 2 zos.close(); ``` The result is that the previous contents get clobbered: the WAR has only the 2 files I just added in it. Is there some sort of append mode that I'm not using or what?
It seems this can't be done. I thought it was for a while, but it seems that it wasn't quite having the effect I wanted. Doing it this way resulted in the equivalent of two separate jar files concatinated together. The weird part was that the tools were making some sense of it. JAR found the first, original jar file and read me that. Glassfish's classloader was finding the later, new part, resulting in it loading only the added files as if they were all of the app. Weird. So I've resurted to creating a new war, adding the contents of the old, adding the new files, closing, and copying the new over the old.
266,417
<p>We are in a Windows environment and looking to automate this process for non-company machines. If a vendor comes on site, we'd like to be able to have him/her hit a website that can perform a quick scan of the workstation to determine if they have the proper MS KB patches and if their virus scanner dats are up to date.</p> <p>I can scan for the KB updates relatively easy, what I'm having a hard time finding is a way to check the virus dat status and since there are so many different engines out there, it seemed to make sense to use the (built into XP at least) proprietary MS security center stuff.</p> <p>Eventually we'd like to have our routers redirect non-company machines to a website that will force validation, but until that point it will be a manual process.</p> <p>Any thoughts?</p>
[ { "answer_id": 392605, "author": "Hernán", "author_id": 48026, "author_profile": "https://Stackoverflow.com/users/48026", "pm_score": 3, "selected": true, "text": "<p>In Windows Vista there are some new APIs to interface with the Security Center component status: <a href=\"http://msdn2.microsoft.com/en-us/library/bb963845(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn2.microsoft.com/en-us/library/bb963845(VS.85).aspx</a></p>\n\n<p>Through WMI, here's a VBS code snippet I checked out on <a href=\"http://social.msdn.microsoft.com/forums/en-US/windowssecurity/thread/bd97d9e6-75c1-4f58-9573-9009df5de19b/\" rel=\"nofollow noreferrer\">http://social.msdn.microsoft.com/forums/en-US/windowssecurity/thread/bd97d9e6-75c1-4f58-9573-9009df5de19b/</a> to dump Antivirus product information:</p>\n\n<pre><code> Set oWMI = GetObject\n(\"winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\SecurityCenter\") \n Set colItems = oWMI.ExecQuery(\"Select * from AntiVirusProduct\") \n\n For Each objAntiVirusProduct In colItems \n msg = msg &amp; \"companyName: \" &amp; objAntiVirusProduct.companyName &amp; vbCrLf \n msg = msg &amp; \"displayName: \" &amp; objAntiVirusProduct.displayName &amp; vbCrLf \n msg = msg &amp; \"instanceGuid: \" &amp; objAntiVirusProduct.instanceGuid &amp; vbCrLf \n msg = msg &amp; \"onAccessScanningEnabled: \"\n &amp; objAntiVirusProduct.onAccessScanningEnabled &amp; vbCrLf \n msg = msg &amp; \"productUptoDate: \" &amp; objAntiVirusProduct.productUptoDate &amp; vbCrLf \n msg = msg &amp; \"versionNumber: \" &amp; objAntiVirusProduct.versionNumber &amp; vbCrLf \n msg = msg &amp; vbCrLf \n\n Next\n\n WScript.Echo msg\n</code></pre>\n" }, { "answer_id": 12267850, "author": "Desiree", "author_id": 1639569, "author_profile": "https://Stackoverflow.com/users/1639569", "pm_score": 1, "selected": false, "text": "<p>For AVs that don’t report to WMI or for AVs which WMI retains state info after the AV is uninstalled (there are instances of both cases) you may wish to consider the OPSWAT library.\nYou will need to write and deploy a light client from your website to utilize the library to machines to be interrogated.\nThe library utilizes WMI for security apps that correctly support WMI and proprietary methods to detect AVs and their dat status for those that don’t.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11130/" ]
We are in a Windows environment and looking to automate this process for non-company machines. If a vendor comes on site, we'd like to be able to have him/her hit a website that can perform a quick scan of the workstation to determine if they have the proper MS KB patches and if their virus scanner dats are up to date. I can scan for the KB updates relatively easy, what I'm having a hard time finding is a way to check the virus dat status and since there are so many different engines out there, it seemed to make sense to use the (built into XP at least) proprietary MS security center stuff. Eventually we'd like to have our routers redirect non-company machines to a website that will force validation, but until that point it will be a manual process. Any thoughts?
In Windows Vista there are some new APIs to interface with the Security Center component status: <http://msdn2.microsoft.com/en-us/library/bb963845(VS.85).aspx> Through WMI, here's a VBS code snippet I checked out on <http://social.msdn.microsoft.com/forums/en-US/windowssecurity/thread/bd97d9e6-75c1-4f58-9573-9009df5de19b/> to dump Antivirus product information: ``` Set oWMI = GetObject ("winmgmts:{impersonationLevel=impersonate}!\\.\root\SecurityCenter") Set colItems = oWMI.ExecQuery("Select * from AntiVirusProduct") For Each objAntiVirusProduct In colItems msg = msg & "companyName: " & objAntiVirusProduct.companyName & vbCrLf msg = msg & "displayName: " & objAntiVirusProduct.displayName & vbCrLf msg = msg & "instanceGuid: " & objAntiVirusProduct.instanceGuid & vbCrLf msg = msg & "onAccessScanningEnabled: " & objAntiVirusProduct.onAccessScanningEnabled & vbCrLf msg = msg & "productUptoDate: " & objAntiVirusProduct.productUptoDate & vbCrLf msg = msg & "versionNumber: " & objAntiVirusProduct.versionNumber & vbCrLf msg = msg & vbCrLf Next WScript.Echo msg ```
266,431
<p>I used to use the standard mysql_connect(), mysql_query(), etc statements for doing MySQL stuff from PHP. Lately I've been switching over to using the wonderful MDB2 class. Along with it, I'm using prepared statements, so I don't have to worry about escaping my input and SQL injection attacks.</p> <p>However, there's one problem I'm running into. I have a table with a few VARCHAR columns, that are specified as not-null (that is, do not allow NULL values). Using the old MySQL PHP commands, I could do things like this without any problem:</p> <pre class="lang-sql prettyprint-override"><code>INSERT INTO mytable SET somevarchar = ''; </code></pre> <p>Now, however, if I have a query like:</p> <pre class="lang-sql prettyprint-override"><code>INSERT INTO mytable SET somevarchar = ?; </code></pre> <p>And then in PHP I have:</p> <pre><code>$value = ""; $prepared = $db-&gt;prepare($query, array('text')); $result = $prepared-&gt;execute($value); </code></pre> <p>This will throw the error "<code>null value violates not-null constraint</code>"</p> <p>As a temporary workaround, I check if <code>$value</code> is empty, and change it to <code>" "</code> (a single space), but that's a horrible hack and might cause other issues.</p> <p>How am I supposed to insert empty strings with prepared statements, without it trying to instead insert a NULL?</p> <p><strong>EDIT:</strong> It's too big of a project to go through my entire codebase, find everywhere that uses an empty string "" and change it to use NULL instead. What I need to know is why standard MySQL queries treat "" and NULL as two separate things (as I think is correct), but prepared statements converts "" into NULL. </p> <p>Note that "" and NULL are <strong>not</strong> the same thing. For Example, <code>SELECT NULL = "";</code> returns <code>NULL</code> instead of <code>1</code> as you'd expect. </p>
[ { "answer_id": 266464, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 0, "selected": false, "text": "<p>Doesn't an empty set of quotes, <code>\"\"</code> do that?</p>\n" }, { "answer_id": 266512, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": -1, "selected": false, "text": "<p>I'm confused. It looks like you're using mysqli OO (from the tags and style), but the syntax is different than the <a href=\"http://us.php.net/manual/en/mysqli.prepare.php\" rel=\"nofollow noreferrer\">manual</a> on php.net, which says to do this instead:</p>\n\n<pre><code>$query = \"INSERT INTO mytable SET somevarchar = ?\";\n$value = \"\";\n$prepared = $db-&gt;prepare($query);\n$prepared-&gt;bind_param(\"s\", $value);\n$result = $prepared-&gt;execute();\n</code></pre>\n" }, { "answer_id": 266518, "author": "hark", "author_id": 34826, "author_profile": "https://Stackoverflow.com/users/34826", "pm_score": 5, "selected": true, "text": "<p>This sounds like a problem with the MDB2 API fumbling PHP's duck typing semantics. Because the empty string in PHP is equivalent to NULL, MDB2 is probably mis-treating it as such. The ideal solution would be to find a workaround for it within it's API, but I'm not overly familiar with it.</p>\n\n<p>One thing that you should consider, though, is that an empty string in SQL is not a NULL value. You can insert them into rows declared 'NOT NULL' just fine:</p>\n\n<pre><code>mysql&gt; CREATE TABLE tbl( row CHAR(128) NOT NULL );\nQuery OK, 0 rows affected (0.05 sec)\n\nmysql&gt; INSERT INTO tbl VALUES( 'not empty' ), ( '' );\nQuery OK, 2 rows affected (0.02 sec)\nRecords: 2 Duplicates: 0 Warnings: 0\n\nmysql&gt; SELECT row, row IS NULL FROM tbl;\n+-----------+-------------+\n| row | row IS NULL |\n+-----------+-------------+\n| not empty | 0 | \n| | 0 | \n+-----------+-------------+\n2 rows in set (0.00 sec)\n\nmysql&gt; INSERT INTO tbl VALUES( NULL );\nERROR 1048 (23000): Column 'row' cannot be null\n</code></pre>\n\n<p>If you're unable to find (or implement) a workaround in the MDB2 API, one hackish solution (though slightly better than the one you're currently using) might be to define a <a href=\"http://dev.mysql.com/doc/refman/5.0/en/user-variables.html\" rel=\"noreferrer\">user variable</a> for the empty string --</p>\n\n<pre><code>SET @EMPTY_STRING = \"\";\nUPDATE tbl SET row=@EMPTY_STRING;\n</code></pre>\n\n<p>Finally, if you need to use the empty string in an INSERT statement but find yourself unable to, the default value for string types in MySQL is an empty string. So you could simply omit the column from INSERT statement and it would automatically get set to the empty string (provided the column has a NOT NULL constraint).</p>\n" }, { "answer_id": 266545, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 4, "selected": false, "text": "<p>Thanks to some of the answers, I realized that the problem may be in the MDB2 API, and not in the PHP or MYSQL commands themselves. Sure enough, I found this in the MDB2 FAQ:</p>\n\n<blockquote>\n <ul>\n <li>Why do empty strings end up as NULL in the database? Why do I get an NULL\n not allowed in NOT NULL text fields\n eventhough the default value is \"\"?\n \n <ul>\n <li>The problem is that for some RDBMS (most noteably Oracle) an empty\n string is NULL. Therefore MDB2\n provides a portability option to\n enforce the same behaviour on all\n RDBMS.</li>\n <li>Since all portability options are enabled by default you will have\n to disable the feature if you dont\n want to have this behaviour:\n $mdb2->setOption('portability',\n MDB2_PORTABILITY_ALL ^\n MDB2_PORTABILITY_EMPTY_TO_NULL);</li>\n </ul></li>\n </ul>\n</blockquote>\n\n<p>Thanks to everyone who provided thoughtful answers.</p>\n" }, { "answer_id": 1016007, "author": "Anthony", "author_id": 49478, "author_profile": "https://Stackoverflow.com/users/49478", "pm_score": 1, "selected": false, "text": "<p>I realize this question is pretty much answered and retired, but I found it while looking for answers to a similar situation and I can't resist throwing my hat in the ring.</p>\n\n<p>Without knowing what the NULL/\"\" column relates to, I can't know how the true significance of an empty string. Does empty string mean something unto itself (like, if I convinced a judge to let me change my name to simply nothing, I would be really irritated if my name showed up on my Driver's License as NULL. My name would be !</p>\n\n<p>However, the empty string (or blank, or the nothingness that is SOMETHING, not simply the lack of anything (like NULL)) could also simply just mean \"NOT NULL\" or \"Nothing, but still not Null\". You could even go the other direction and suggest that the absence of the value NULL makes it even LESS something than Null, cuz at least Null has a name you can say aloud!</p>\n\n<p>My point is, that if the empty string is a direct representation of some data (like a name, or what I prefer be inserted between the numbers in my phone number, etc), then your options are either to argue until you're sore for the legitimate use of empty string or to use something that represents an empty string that isn't NULL (Like an ASCII control character or some unicode equivalent, a regex value of some kind, or, even worse, an arbitrary yet totally unused token, like: ◘</p>\n\n<p>If the empty cell really just means NOT NULL, then you could think of some other way of expressing it. One silly and obvious way is the phrase \"Not NULL\". But I have a hunch that NULL means something like \"Not part of this group at all\" while the empty string means something like \"this guy is cool, he just hasn't gotten his gang tattoos yet\". In which case I would come up with a term/name/idea for this situation, like \"default\" or \"rookie\" or \"Pending\".</p>\n\n<p>Now, if by some crazy chance you actually want empty string to represent that which is not even worthy of NULL, again, come up with a more significant symbol for that, such as \"-1\" or \"SUPERNULL\" or \"UGLIES\".</p>\n\n<p>In the Indian Caste System, the lowest Caste are Shudra: Farmers and Laborers. Beneath this caste are the Dalit: \"The Untouchables\". They are not considered a lower caste, because setting them as the lowest caste would be considered a contamination of the entire system.</p>\n\n<p>So don't call me crazy for thinking empty strings may be WORSE than NULL!</p>\n\n<p>'Til next time.</p>\n" }, { "answer_id": 2294611, "author": "ahhon", "author_id": 276755, "author_profile": "https://Stackoverflow.com/users/276755", "pm_score": 1, "selected": false, "text": "<p>I found the solution!</p>\n\n<p>MDB2 converts empty strings to NULL because portability option MDB2_PORTABILITY_EMPTY_TO_NULL is on by default (thanks to Oracle which considers empty strings to be null).</p>\n\n<p>Switch this options off when you connect to the database:</p>\n\n<pre><code>$options = array(\n 'portability' =&gt; MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_EMPTY_TO_NULL\n);\n$res= &amp; MDB2::connect(\"mysql://user:password@server/dbase\", $options);\n</code></pre>\n" }, { "answer_id": 6193501, "author": "Lisa Simpson", "author_id": 673748, "author_profile": "https://Stackoverflow.com/users/673748", "pm_score": 1, "selected": false, "text": "<p>While 0 and empty strings are variables NULL is the absence of data. And trust me, it's a lot easier to write a query to </p>\n\n<p><code>SELECT * from table where mything IS NULL</code> than to try to query for empty strings :/ </p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14569/" ]
I used to use the standard mysql\_connect(), mysql\_query(), etc statements for doing MySQL stuff from PHP. Lately I've been switching over to using the wonderful MDB2 class. Along with it, I'm using prepared statements, so I don't have to worry about escaping my input and SQL injection attacks. However, there's one problem I'm running into. I have a table with a few VARCHAR columns, that are specified as not-null (that is, do not allow NULL values). Using the old MySQL PHP commands, I could do things like this without any problem: ```sql INSERT INTO mytable SET somevarchar = ''; ``` Now, however, if I have a query like: ```sql INSERT INTO mytable SET somevarchar = ?; ``` And then in PHP I have: ``` $value = ""; $prepared = $db->prepare($query, array('text')); $result = $prepared->execute($value); ``` This will throw the error "`null value violates not-null constraint`" As a temporary workaround, I check if `$value` is empty, and change it to `" "` (a single space), but that's a horrible hack and might cause other issues. How am I supposed to insert empty strings with prepared statements, without it trying to instead insert a NULL? **EDIT:** It's too big of a project to go through my entire codebase, find everywhere that uses an empty string "" and change it to use NULL instead. What I need to know is why standard MySQL queries treat "" and NULL as two separate things (as I think is correct), but prepared statements converts "" into NULL. Note that "" and NULL are **not** the same thing. For Example, `SELECT NULL = "";` returns `NULL` instead of `1` as you'd expect.
This sounds like a problem with the MDB2 API fumbling PHP's duck typing semantics. Because the empty string in PHP is equivalent to NULL, MDB2 is probably mis-treating it as such. The ideal solution would be to find a workaround for it within it's API, but I'm not overly familiar with it. One thing that you should consider, though, is that an empty string in SQL is not a NULL value. You can insert them into rows declared 'NOT NULL' just fine: ``` mysql> CREATE TABLE tbl( row CHAR(128) NOT NULL ); Query OK, 0 rows affected (0.05 sec) mysql> INSERT INTO tbl VALUES( 'not empty' ), ( '' ); Query OK, 2 rows affected (0.02 sec) Records: 2 Duplicates: 0 Warnings: 0 mysql> SELECT row, row IS NULL FROM tbl; +-----------+-------------+ | row | row IS NULL | +-----------+-------------+ | not empty | 0 | | | 0 | +-----------+-------------+ 2 rows in set (0.00 sec) mysql> INSERT INTO tbl VALUES( NULL ); ERROR 1048 (23000): Column 'row' cannot be null ``` If you're unable to find (or implement) a workaround in the MDB2 API, one hackish solution (though slightly better than the one you're currently using) might be to define a [user variable](http://dev.mysql.com/doc/refman/5.0/en/user-variables.html) for the empty string -- ``` SET @EMPTY_STRING = ""; UPDATE tbl SET row=@EMPTY_STRING; ``` Finally, if you need to use the empty string in an INSERT statement but find yourself unable to, the default value for string types in MySQL is an empty string. So you could simply omit the column from INSERT statement and it would automatically get set to the empty string (provided the column has a NOT NULL constraint).
266,433
<p>So... I used to think that when you accessed a file but specified the name without a path (CAISLog.csv in my case) that .NET would expect the file to reside at the same path as the running .exe. </p> <p>This works when I'm stepping through a solution (C# .NET2.* VS2K5) but when I run the app in normal mode (Started by a Websphere MQ Trigger monitor &amp; running in the background as a network service) instead of accessing the file at the path where the .exe is it's being looked for at C:\WINDOWS\system32. If it matters The parent task's .exe is in almost the same folder structure/path as my app</p> <p>I get a matching error: "<em>System.UnauthorizedAccessException: Access to the path 'C:\WINDOWS\system32\CAISLog.csv' is denied.</em>"</p> <p>My workaround is to just fully qualify the location of my file. What I want to understand, however is <strong>"What is the .NET rule that governs how a path is resolved when only the file name is specified during IO?"</strong> I feel I'm missing some basic concept and it's bugging me bad.</p> <p>edit - I'm not sure it's a.NET rule per se but Schmuli seems to be explaining the concept a little clearer. I will definitely try Rob Prouse's suggestions in the future so +1 on that too.</p> <p>If anyone has some re-wording suggestions that emphasize I don't <em>really</em> care about finding the path to my .exe - rather just didn't understand what was going on with relative path resolution (and I may still have my terminlogy screwed up)...</p>
[ { "answer_id": 266456, "author": "tomasr", "author_id": 10292, "author_profile": "https://Stackoverflow.com/users/10292", "pm_score": 2, "selected": false, "text": "<p>Relative Path resolution <em>never</em> works against the path of the launching executable. It always works against the process' Current Directory, and you can't really expect that to always be set to the directory the .exe lives in.</p>\n\n<p>If you need that behavior, then take care to find out the right path on your own and provide a fully qualified path to the file operations.</p>\n" }, { "answer_id": 266473, "author": "Rob Prouse", "author_id": 30827, "author_profile": "https://Stackoverflow.com/users/30827", "pm_score": 3, "selected": false, "text": "<p>It is based on the current working directory which may or may not be the same as where your application resides, especially if started from a different program or a shortcut with a different working directory.</p>\n\n<p>Rather than hard code the path, get the path to your program and use it. You can do this with something like this</p>\n\n<pre><code>Assembly ass = Assembly.GetEntryAssembly();\nstring dir = Path.GetDirectoryName(ass.Location);\nstring filename = Path.Combine( dir, \"CAISLog.csv\" );\n</code></pre>\n\n<p>This assumes that the entry assembly is where your file is. If not, you can change up getting the assembly for something like;</p>\n\n<pre><code>Assembly ass = Assembly.GetAssembly( typeof( AClassInYourAssembly ) );\n</code></pre>\n" }, { "answer_id": 266522, "author": "RWendi", "author_id": 15152, "author_profile": "https://Stackoverflow.com/users/15152", "pm_score": -1, "selected": false, "text": "<p>You can use this to specify a path that resides at the same path of your exe @\"..\\CAISLog.csv\". Please note that the double dots refer to the parent directory of where ever your .exe lies.</p>\n\n<p>RWendi</p>\n" }, { "answer_id": 266871, "author": "Schmuli", "author_id": 8363, "author_profile": "https://Stackoverflow.com/users/8363", "pm_score": 5, "selected": true, "text": "<p>When an application (WinForms) starts up, the <code>Environment.CurrentDirectory</code> contains the path to the application folder (i.e. the folder that contains the .exe assembly). Using any of the File Dialogs, ex. <code>OpenFileDialog</code>, <code>SaveFileDialog</code>, etc. will cause the current directory to change (if a different folder was selected).</p>\n\n<p>When running a Windows Service, its containing folder is C:\\Windows\\System32, as that is the System folder and it is the System (i.e. the Operation System) that is actually running your Windows Service.</p>\n\n<p>Note that specifying a relative path in most of the <code>System.IO</code> objects, will fall back to using the <code>Environment.CurrentDirectory</code> property.</p>\n\n<p>As mentioned, there are several ways to obtain the path of the service executable, using <code>Assembly.GetEntryAssembly()</code> or <code>Assembly.GetExecutingAssembly()</code> and then using either the <code>Location</code> property or the <code>CodeBase</code> property (be aware that this is the file path, not directory, of the executable).</p>\n\n<p>Another option is to use:</p>\n\n<pre><code>`System.IO.Directory.SetCurrentDirectory( System.AppDomain.CurrentDomain.BaseDirectory );`\n</code></pre>\n\n<p>Make the call in the Service's <code>OnStart</code> method, applying it to the whole application.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30901/" ]
So... I used to think that when you accessed a file but specified the name without a path (CAISLog.csv in my case) that .NET would expect the file to reside at the same path as the running .exe. This works when I'm stepping through a solution (C# .NET2.\* VS2K5) but when I run the app in normal mode (Started by a Websphere MQ Trigger monitor & running in the background as a network service) instead of accessing the file at the path where the .exe is it's being looked for at C:\WINDOWS\system32. If it matters The parent task's .exe is in almost the same folder structure/path as my app I get a matching error: "*System.UnauthorizedAccessException: Access to the path 'C:\WINDOWS\system32\CAISLog.csv' is denied.*" My workaround is to just fully qualify the location of my file. What I want to understand, however is **"What is the .NET rule that governs how a path is resolved when only the file name is specified during IO?"** I feel I'm missing some basic concept and it's bugging me bad. edit - I'm not sure it's a.NET rule per se but Schmuli seems to be explaining the concept a little clearer. I will definitely try Rob Prouse's suggestions in the future so +1 on that too. If anyone has some re-wording suggestions that emphasize I don't *really* care about finding the path to my .exe - rather just didn't understand what was going on with relative path resolution (and I may still have my terminlogy screwed up)...
When an application (WinForms) starts up, the `Environment.CurrentDirectory` contains the path to the application folder (i.e. the folder that contains the .exe assembly). Using any of the File Dialogs, ex. `OpenFileDialog`, `SaveFileDialog`, etc. will cause the current directory to change (if a different folder was selected). When running a Windows Service, its containing folder is C:\Windows\System32, as that is the System folder and it is the System (i.e. the Operation System) that is actually running your Windows Service. Note that specifying a relative path in most of the `System.IO` objects, will fall back to using the `Environment.CurrentDirectory` property. As mentioned, there are several ways to obtain the path of the service executable, using `Assembly.GetEntryAssembly()` or `Assembly.GetExecutingAssembly()` and then using either the `Location` property or the `CodeBase` property (be aware that this is the file path, not directory, of the executable). Another option is to use: ``` `System.IO.Directory.SetCurrentDirectory( System.AppDomain.CurrentDomain.BaseDirectory );` ``` Make the call in the Service's `OnStart` method, applying it to the whole application.
266,448
<p>How would I format the standard RSS pubDate string as something closer to ASP.NET's DateTime?</p> <p>So, from this:</p> <p>Wed, 29 Oct 2008 14:14:48 +0000</p> <p>to this:</p> <p>10/29/2008 2:14 PM</p>
[ { "answer_id": 266470, "author": "AaronS", "author_id": 26932, "author_profile": "https://Stackoverflow.com/users/26932", "pm_score": 3, "selected": true, "text": "<p>Something close to this should work:</p>\n\n<pre><code>string orig = \"Wed, 29 Oct 2008 14:14:48 +0000\";\nstring newstring = String.Format(\"{0:MM/dd/yyyy hh:mm tt}\", DateTime.Parse(orig.Remove(orig.IndexOf(\" +\"))));\n</code></pre>\n\n<p>Taken from <a href=\"http://blog.stevex.net/index.php/string-formatting-in-csharp/\" rel=\"nofollow noreferrer\">http://blog.stevex.net/index.php/string-formatting-in-csharp/</a></p>\n" }, { "answer_id": 266508, "author": "Moose", "author_id": 19032, "author_profile": "https://Stackoverflow.com/users/19032", "pm_score": 2, "selected": false, "text": "<p>Getting it into a DateTime will work with this, I think:</p>\n\n<pre><code>string d = \"Wed, 29 Oct 2008 14:14:48 +0000\";\n\nstring RFC822 = \"ddd, dd MMM yyyy HH:mm:ss zzz\";\nDateTime dt = DateTime.ParseExact( d, RFC822,\n DateTimeFormatInfo.InvariantInfo,\n DateTimeStyles.None);\n</code></pre>\n\n<p>You might have to tinker with the Time zone info (zzz) at the end of the RFC822 format string.</p>\n" }, { "answer_id": 285550, "author": "Oppositional", "author_id": 2029, "author_profile": "https://Stackoverflow.com/users/2029", "pm_score": 4, "selected": false, "text": "<p>I have an implementation of the RSS 822 DateTime format as a an answer to the question \"<a href=\"https://stackoverflow.com/questions/284775/how-do-i-parse-and-convert-datetimes-to-the-rfc-822-date-time-format\">How do I parse and convert DateTime’s to the RFC-822 date-time format</a> that should solve your problem.</p>\n\n<p>This is an implementation in C# of how to parse and convert a DateTime to and from its RFC-822 representation. The only restriction it has is that the DateTime is in Coordinated Universal Time (UTC).</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Provides methods for converting &lt;see cref=\"DateTime\"/&gt; structures \n/// to and from the equivalent &lt;a href=\"http://www.w3.org/Protocols/rfc822/#z28\"&gt;RFC 822&lt;/a&gt; \n/// string representation.\n/// &lt;/summary&gt;\npublic class Rfc822DateTime\n{\n //============================================================\n // Private members\n //============================================================\n #region Private Members\n /// &lt;summary&gt;\n /// Private member to hold array of formats that RFC 822 date-time representations conform to.\n /// &lt;/summary&gt;\n private static string[] formats = new string[0];\n /// &lt;summary&gt;\n /// Private member to hold the DateTime format string for representing a DateTime in the RFC 822 format.\n /// &lt;/summary&gt;\n private const string format = \"ddd, dd MMM yyyy HH:mm:ss K\";\n #endregion\n\n //============================================================\n // Public Properties\n //============================================================\n #region Rfc822DateTimeFormat\n /// &lt;summary&gt;\n /// Gets the custom format specifier that may be used to represent a &lt;see cref=\"DateTime\"/&gt; in the RFC 822 format.\n /// &lt;/summary&gt;\n /// &lt;value&gt;A &lt;i&gt;DateTime format string&lt;/i&gt; that may be used to represent a &lt;see cref=\"DateTime\"/&gt; in the RFC 822 format.&lt;/value&gt;\n /// &lt;remarks&gt;\n /// &lt;para&gt;\n /// This method returns a string representation of a &lt;see cref=\"DateTime\"/&gt; that utilizes the time zone \n /// offset (local differential) to represent the offset from Greenwich mean time in hours and minutes. \n /// The &lt;see cref=\"Rfc822DateTimeFormat\"/&gt; is a valid date-time format string for use \n /// in the &lt;see cref=\"DateTime.ToString(String, IFormatProvider)\"/&gt; method.\n /// &lt;/para&gt;\n /// &lt;para&gt;\n /// The &lt;a href=\"http://www.w3.org/Protocols/rfc822/#z28\"&gt;RFC 822&lt;/a&gt; Date and Time specification \n /// specifies that the year will be represented as a two-digit value, but the \n /// &lt;a href=\"http://www.rssboard.org/rss-profile#data-types-datetime\"&gt;RSS Profile&lt;/a&gt; recommends that \n /// all date-time values should use a four-digit year. The &lt;see cref=\"Rfc822DateTime\"/&gt; class \n /// follows the RSS Profile recommendation when converting a &lt;see cref=\"DateTime\"/&gt; to the equivalent \n /// RFC 822 string representation.\n /// &lt;/para&gt;\n /// &lt;/remarks&gt;\n public static string Rfc822DateTimeFormat\n {\n get\n {\n return format;\n }\n }\n #endregion\n\n #region Rfc822DateTimePatterns\n /// &lt;summary&gt;\n /// Gets an array of the expected formats for RFC 822 date-time string representations.\n /// &lt;/summary&gt;\n /// &lt;value&gt;\n /// An array of the expected formats for RFC 822 date-time string representations \n /// that may used in the &lt;see cref=\"DateTime.TryParseExact(String, string[], IFormatProvider, DateTimeStyles, out DateTime)\"/&gt; method.\n /// &lt;/value&gt;\n /// &lt;remarks&gt;\n /// The array of the expected formats that is returned assumes that the RFC 822 time zone \n /// is represented as or converted to a local differential representation.\n /// &lt;/remarks&gt;\n /// &lt;seealso cref=\"ConvertZoneToLocalDifferential(String)\"/&gt;\n public static string[] Rfc822DateTimePatterns\n {\n get\n {\n if (formats.Length &gt; 0)\n {\n return formats;\n }\n else\n {\n formats = new string[35];\n\n // two-digit day, four-digit year patterns\n formats[0] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'fffffff zzzz\";\n formats[1] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'ffffff zzzz\";\n formats[2] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'fffff zzzz\";\n formats[3] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'ffff zzzz\";\n formats[4] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'fff zzzz\";\n formats[5] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'ff zzzz\";\n formats[6] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'f zzzz\";\n formats[7] = \"ddd',' dd MMM yyyy HH':'mm':'ss zzzz\";\n\n // two-digit day, two-digit year patterns\n formats[8] = \"ddd',' dd MMM yy HH':'mm':'ss'.'fffffff zzzz\";\n formats[9] = \"ddd',' dd MMM yy HH':'mm':'ss'.'ffffff zzzz\";\n formats[10] = \"ddd',' dd MMM yy HH':'mm':'ss'.'fffff zzzz\";\n formats[11] = \"ddd',' dd MMM yy HH':'mm':'ss'.'ffff zzzz\";\n formats[12] = \"ddd',' dd MMM yy HH':'mm':'ss'.'fff zzzz\";\n formats[13] = \"ddd',' dd MMM yy HH':'mm':'ss'.'ff zzzz\";\n formats[14] = \"ddd',' dd MMM yy HH':'mm':'ss'.'f zzzz\";\n formats[15] = \"ddd',' dd MMM yy HH':'mm':'ss zzzz\";\n\n // one-digit day, four-digit year patterns\n formats[16] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'fffffff zzzz\";\n formats[17] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'ffffff zzzz\";\n formats[18] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'fffff zzzz\";\n formats[19] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'ffff zzzz\";\n formats[20] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'fff zzzz\";\n formats[21] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'ff zzzz\";\n formats[22] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'f zzzz\";\n formats[23] = \"ddd',' d MMM yyyy HH':'mm':'ss zzzz\";\n\n // two-digit day, two-digit year patterns\n formats[24] = \"ddd',' d MMM yy HH':'mm':'ss'.'fffffff zzzz\";\n formats[25] = \"ddd',' d MMM yy HH':'mm':'ss'.'ffffff zzzz\";\n formats[26] = \"ddd',' d MMM yy HH':'mm':'ss'.'fffff zzzz\";\n formats[27] = \"ddd',' d MMM yy HH':'mm':'ss'.'ffff zzzz\";\n formats[28] = \"ddd',' d MMM yy HH':'mm':'ss'.'fff zzzz\";\n formats[29] = \"ddd',' d MMM yy HH':'mm':'ss'.'ff zzzz\";\n formats[30] = \"ddd',' d MMM yy HH':'mm':'ss'.'f zzzz\";\n formats[31] = \"ddd',' d MMM yy HH':'mm':'ss zzzz\";\n\n // Fall back patterns\n formats[32] = \"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK\"; // RoundtripDateTimePattern\n formats[33] = DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern;\n formats[34] = DateTimeFormatInfo.InvariantInfo.SortableDateTimePattern;\n\n return formats;\n }\n }\n }\n #endregion\n\n //============================================================\n // Public Methods\n //============================================================\n #region Parse(string s)\n /// &lt;summary&gt;\n /// Converts the specified string representation of a date and time to its &lt;see cref=\"DateTime\"/&gt; equivalent.\n /// &lt;/summary&gt;\n /// &lt;param name=\"s\"&gt;A string containing a date and time to convert.&lt;/param&gt;\n /// &lt;returns&gt;\n /// A &lt;see cref=\"DateTime\"/&gt; equivalent to the date and time contained in &lt;paramref name=\"s\"/&gt;, \n /// expressed as &lt;i&gt;Coordinated Universal Time (UTC)&lt;/i&gt;.\n /// &lt;/returns&gt;\n /// &lt;remarks&gt;\n /// The string &lt;paramref name=\"s\"/&gt; is parsed using formatting information in the &lt;see cref=\"DateTimeFormatInfo.InvariantInfo\"/&gt; object.\n /// &lt;/remarks&gt;\n /// &lt;exception cref=\"ArgumentNullException\"&gt;&lt;paramref name=\"s\"/&gt; is a &lt;b&gt;null&lt;/b&gt; reference (Nothing in Visual Basic).&lt;/exception&gt;\n /// &lt;exception cref=\"ArgumentNullException\"&gt;&lt;paramref name=\"s\"/&gt; is an empty string.&lt;/exception&gt;\n /// &lt;exception cref=\"FormatException\"&gt;&lt;paramref name=\"s\"/&gt; does not contain a valid RFC 822 string representation of a date and time.&lt;/exception&gt;\n public static DateTime Parse(string s)\n {\n //------------------------------------------------------------\n // Validate parameter\n //------------------------------------------------------------\n Guard.ArgumentNotNullOrEmptyString(s, \"s\");\n\n DateTime result;\n if (Rfc822DateTime.TryParse(s, out result))\n {\n return result;\n }\n else\n {\n throw new FormatException(String.Format(null, \"{0} is not a valid RFC 822 string representation of a date and time.\", s));\n }\n }\n #endregion\n\n #region ConvertZoneToLocalDifferential(string s)\n /// &lt;summary&gt;\n /// Converts the time zone component of an RFC 822 date and time string representation to its local differential (time zone offset).\n /// &lt;/summary&gt;\n /// &lt;param name=\"s\"&gt;A string containing an RFC 822 date and time to convert.&lt;/param&gt;\n /// &lt;returns&gt;A date and time string that uses local differential to describe the time zone equivalent to the date and time contained in &lt;paramref name=\"s\"/&gt;.&lt;/returns&gt;\n /// &lt;exception cref=\"ArgumentNullException\"&gt;&lt;paramref name=\"s\"/&gt; is a &lt;b&gt;null&lt;/b&gt; reference (Nothing in Visual Basic).&lt;/exception&gt;\n /// &lt;exception cref=\"ArgumentNullException\"&gt;&lt;paramref name=\"s\"/&gt; is an empty string.&lt;/exception&gt;\n public static string ConvertZoneToLocalDifferential(string s)\n {\n string zoneRepresentedAsLocalDifferential = String.Empty;\n\n //------------------------------------------------------------\n // Validate parameter\n //------------------------------------------------------------\n Guard.ArgumentNotNullOrEmptyString(s, \"s\");\n\n if(s.EndsWith(\" UT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" UT\") + 1) ), \"+00:00\");\n }\n else if (s.EndsWith(\" GMT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" GMT\") + 1 ) ), \"+00:00\");\n }\n else if (s.EndsWith(\" EST\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" EST\") + 1)), \"-05:00\");\n }\n else if (s.EndsWith(\" EDT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" EDT\") + 1)), \"-04:00\");\n }\n else if (s.EndsWith(\" CST\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" CST\") + 1)), \"-06:00\");\n }\n else if (s.EndsWith(\" CDT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" CDT\") + 1)), \"-05:00\");\n }\n else if (s.EndsWith(\" MST\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" MST\") + 1)), \"-07:00\");\n }\n else if (s.EndsWith(\" MDT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" MDT\") + 1)), \"-06:00\");\n }\n else if (s.EndsWith(\" PST\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" PST\") + 1)), \"-08:00\");\n }\n else if (s.EndsWith(\" PDT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" PDT\") + 1)), \"-07:00\");\n }\n else if (s.EndsWith(\" Z\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" Z\") + 1)), \"+00:00\");\n }\n else if (s.EndsWith(\" A\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" A\") + 1)), \"-01:00\");\n }\n else if (s.EndsWith(\" M\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" M\") + 1)), \"-12:00\");\n }\n else if (s.EndsWith(\" N\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" N\") + 1)), \"+01:00\");\n }\n else if (s.EndsWith(\" Y\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" Y\") + 1)), \"+12:00\");\n }\n else\n {\n zoneRepresentedAsLocalDifferential = s;\n }\n\n return zoneRepresentedAsLocalDifferential;\n }\n #endregion\n\n #region ToString(DateTime utcDateTime)\n /// &lt;summary&gt;\n /// Converts the value of the specified &lt;see cref=\"DateTime\"/&gt; object to its equivalent string representation.\n /// &lt;/summary&gt;\n /// &lt;param name=\"utcDateTime\"&gt;The Coordinated Universal Time (UTC) &lt;see cref=\"DateTime\"/&gt; to convert.&lt;/param&gt;\n /// &lt;returns&gt;A RFC 822 string representation of the value of the &lt;paramref name=\"utcDateTime\"/&gt;.&lt;/returns&gt;\n /// &lt;exception cref=\"ArgumentException\"&gt;The specified &lt;paramref name=\"utcDateTime\"/&gt; object does not represent a &lt;see cref=\"DateTimeKind.Utc\"&gt;Coordinated Universal Time (UTC)&lt;/see&gt; value.&lt;/exception&gt;\n public static string ToString(DateTime utcDateTime)\n {\n if (utcDateTime.Kind != DateTimeKind.Utc)\n {\n throw new ArgumentException(\"utcDateTime\");\n }\n\n return utcDateTime.ToString(Rfc822DateTime.Rfc822DateTimeFormat, DateTimeFormatInfo.InvariantInfo);\n }\n #endregion\n\n #region TryParse(string s, out DateTime result)\n /// &lt;summary&gt;\n /// Converts the specified string representation of a date and time to its &lt;see cref=\"DateTime\"/&gt; equivalent.\n /// &lt;/summary&gt;\n /// &lt;param name=\"s\"&gt;A string containing a date and time to convert.&lt;/param&gt;\n /// &lt;param name=\"result\"&gt;\n /// When this method returns, contains the &lt;see cref=\"DateTime\"/&gt; value equivalent to the date and time \n /// contained in &lt;paramref name=\"s\"/&gt;, expressed as &lt;i&gt;Coordinated Universal Time (UTC)&lt;/i&gt;, \n /// if the conversion succeeded, or &lt;see cref=\"DateTime.MinValue\"&gt;MinValue&lt;/see&gt; if the conversion failed. \n /// The conversion fails if the s parameter is a &lt;b&gt;null&lt;/b&gt; reference (Nothing in Visual Basic), \n /// or does not contain a valid string representation of a date and time. \n /// This parameter is passed uninitialized.\n /// &lt;/param&gt;\n /// &lt;returns&gt;&lt;b&gt;true&lt;/b&gt; if the &lt;paramref name=\"s\"/&gt; parameter was converted successfully; otherwise, &lt;b&gt;false&lt;/b&gt;.&lt;/returns&gt;\n /// &lt;remarks&gt;\n /// The string &lt;paramref name=\"s\"/&gt; is parsed using formatting information in the &lt;see cref=\"DateTimeFormatInfo.InvariantInfo\"/&gt; object. \n /// &lt;/remarks&gt;\n public static bool TryParse(string s, out DateTime result)\n {\n //------------------------------------------------------------\n // Attempt to convert string representation\n //------------------------------------------------------------\n bool wasConverted = false;\n result = DateTime.MinValue;\n\n if (!String.IsNullOrEmpty(s))\n {\n DateTime parseResult;\n if (DateTime.TryParseExact(Rfc822DateTime.ConvertZoneToLocalDifferential(s), Rfc822DateTime.Rfc822DateTimePatterns, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out parseResult))\n {\n result = DateTime.SpecifyKind(parseResult, DateTimeKind.Utc);\n wasConverted = true;\n }\n }\n\n return wasConverted;\n }\n #endregion \n}\n</code></pre>\n" }, { "answer_id": 1086698, "author": "Edwin Tai", "author_id": 133653, "author_profile": "https://Stackoverflow.com/users/133653", "pm_score": 3, "selected": false, "text": "<p>it is better to use\nDateTime.Now.Tostring(\"r\") instead</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4241/" ]
How would I format the standard RSS pubDate string as something closer to ASP.NET's DateTime? So, from this: Wed, 29 Oct 2008 14:14:48 +0000 to this: 10/29/2008 2:14 PM
Something close to this should work: ``` string orig = "Wed, 29 Oct 2008 14:14:48 +0000"; string newstring = String.Format("{0:MM/dd/yyyy hh:mm tt}", DateTime.Parse(orig.Remove(orig.IndexOf(" +")))); ``` Taken from <http://blog.stevex.net/index.php/string-formatting-in-csharp/>
266,457
<p>I have a linq query and I am trying to put that in to a serializable object for a distributed caching (Velocity) but its failing due to a LINQ-to-SQL lazy list</p> <p>like so</p> <pre><code> return from b in _datacontext.MemberBlogs let cats = GetBlogCategories(b.MemberBlogID) select new MemberBlogs { MemberBlogID = b.MemberBlogID, MemberID = b.MemberID, BlogTitle = b.BlogTitle, BlogURL = b.BlogURL, BlogUsername = b.BlogUsername, BlogPassword = b.BlogPassword, Categories = new LazyList&lt;MemberBlogCategories&gt;(cats) }; </code></pre> <p>LazyList is the same class Rob Conery uses in his MVC storefront...</p> <p>all three classes are marked serializable (MemberBlogs,MemberBlogCategories,LazyList... any ideas?</p>
[ { "answer_id": 266537, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 2, "selected": false, "text": "<p>If you're caching it why are you using a lazy list? Don't use a lazy list, use caching, and the problem goes away.</p>\n" }, { "answer_id": 266541, "author": "Duncan", "author_id": 25035, "author_profile": "https://Stackoverflow.com/users/25035", "pm_score": 4, "selected": true, "text": "<p>If you are putting it in a distributed cache you will need to avoid the LazyList altogether. You can then call .ToList() around the whole LINQ statement as in:</p>\n\n<pre><code>(from x select new MemberBlogs).ToList()\n</code></pre>\n\n<p>This should then be cachable because it forces the queries to be evaluated.</p>\n" }, { "answer_id": 266547, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": 2, "selected": false, "text": "<p>I'm just guessing, but I'd say the problem is that it is serializing the query instead of the results; I don't know what the implementation of the LazyList looks like, but you can probably add an OnSerializing method that actually executes the query prior to serializing it; Something like:</p>\n\n<pre><code>[OnSerializing]\nprivate void ExecuteLinqQuery(StreamingContext context)\n{\n if (!SomethingThatIndicatesThisLinqQueryHasNotBeenExecuted)\n LinqVariable.ToList()\n}\n</code></pre>\n\n<p>This way you get to keep the Lazy Load (for anything that doesn't go into your cache), but then also if it does hit the cache, it'll execute the linq query and cache the results.</p>\n" }, { "answer_id": 19234021, "author": "Jonathan", "author_id": 62686, "author_profile": "https://Stackoverflow.com/users/62686", "pm_score": 0, "selected": false, "text": "<p>I know this is an old post but I had the same issue as I wanted to execute my LazyList and put them into the AppFabric Cache. I ended up putting some custom serialization logic into the LazyList type.</p>\n\n<p>The first part now looks like this:</p>\n\n<pre><code> public class LazyList&lt;T&gt; : IList&lt;T&gt;, ISerializable\n{\n\n public LazyList()\n {\n this.query = new List&lt;T&gt;().AsQueryable();\n }\n\n public LazyList(SerializationInfo info, StreamingContext context)\n {\n try {\n this.inner = (List&lt;T&gt;)info.GetValue(\"InnerList\", typeof(List&lt;T&gt;));\n }\n catch (Exception ex)\n {\n this.inner = null;\n }\n }\n\n public void GetObjectData(SerializationInfo info, StreamingContext context)\n {\n if (this.inner != null)\n info.AddValue(\"InnerList\", this.inner.ToList());\n }\n\n public LazyList(IQueryable&lt;T&gt; query)\n {\n this.query = query;\n }\n\n public LazyList(List&lt;T&gt; l)\n {\n inner = l;\n }\n}\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22093/" ]
I have a linq query and I am trying to put that in to a serializable object for a distributed caching (Velocity) but its failing due to a LINQ-to-SQL lazy list like so ``` return from b in _datacontext.MemberBlogs let cats = GetBlogCategories(b.MemberBlogID) select new MemberBlogs { MemberBlogID = b.MemberBlogID, MemberID = b.MemberID, BlogTitle = b.BlogTitle, BlogURL = b.BlogURL, BlogUsername = b.BlogUsername, BlogPassword = b.BlogPassword, Categories = new LazyList<MemberBlogCategories>(cats) }; ``` LazyList is the same class Rob Conery uses in his MVC storefront... all three classes are marked serializable (MemberBlogs,MemberBlogCategories,LazyList... any ideas?
If you are putting it in a distributed cache you will need to avoid the LazyList altogether. You can then call .ToList() around the whole LINQ statement as in: ``` (from x select new MemberBlogs).ToList() ``` This should then be cachable because it forces the queries to be evaluated.
266,486
<p>I am trying to write out a png file from a java.awt.image.BufferedImage. Everything works fine but the resulting png is a 32-bit file.</p> <p>Is there a way to make the png file be 8-bit? The image is grayscale, but I do need transparency as this is an overlay image. I am using java 6, and I would prefer to return an OutputStream so that I can have the calling class deal with writing out the file to disk/db.</p> <p>Here is the relevant portion of the code:</p> <pre><code> public static ByteArrayOutputStream createImage(InputStream originalStream) throws IOException { ByteArrayOutputStream oStream = null; java.awt.Image newImg = javax.imageio.ImageIO.read(originalStream); int imgWidth = newImg.getWidth(null); int imgHeight = newImg.getHeight(null); java.awt.image.BufferedImage bim = new java.awt.image.BufferedImage(imgWidth, imgHeight, java.awt.image.BufferedImage.TYPE_INT_ARGB); Color bckgrndColor = new Color(0x80, 0x80, 0x80); Graphics2D gf = (Graphics2D)bim.getGraphics(); // set transparency for fill image gf.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f)); gf.setColor(bckgrndColor); gf.fillRect(0, 0, imgWidth, imgHeight); oStream = new ByteArrayOutputStream(); javax.imageio.ImageIO.write(bim, "png", oStream); oStream.close(); return oStream; } </code></pre>
[ { "answer_id": 267316, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "<p>It is an interesting question... It is late, I will experiment tomorrow. I will first try and use a BufferedImage.TYPE_BYTE_INDEXED (perhaps after drawing) to see if Java is smart enough to generate an 8bit PNG.<br>\nOr perhaps some image library can allow that.</p>\n\n<p>[EDIT] Some years later... Actually, I made the code at the time, but forgot to update this thread... I used <a href=\"http://gman.eichberger.de/2007/07/transparent-gifs-in-java.html\" rel=\"nofollow noreferrer\">the code pointed at by Kat</a>, with a little refinement on the handling of transparency, and saving in PNG format instead of Gif format. It works in making a 8-bit PNG file with all-or-nothing transparency.</p>\n\n<p>You can find a working test file at <a href=\"http://bazaar.launchpad.net/~philho/+junk/Java/view/head:/Tests/src/org/philhosoft/tests/image/AddTransparency.java\" rel=\"nofollow noreferrer\">http://bazaar.launchpad.net/~philho/+junk/Java/view/head:/Tests/src/org/philhosoft/tests/image/AddTransparency.java</a>\nusing my <a href=\"http://bazaar.launchpad.net/~philho/+junk/Java/view/head:/Utilities/src/org/philhosoft/util/ImageUtil.java\" rel=\"nofollow noreferrer\">ImageUtil</a> class.</p>\n\n<p>Since the code isn't that big, for posterity sake, I post it here, without the JavaDoc to save some lines.</p>\n\n<pre><code>public class ImageUtil\n{\n public static int ALPHA_BIT_MASK = 0xFF000000;\n\n public static BufferedImage imageToBufferedImage(Image image, int width, int height)\n {\n return imageToBufferedImage(image, width, height, BufferedImage.TYPE_INT_ARGB);\n }\n\n public static BufferedImage imageToBufferedImage(Image image, int width, int height, int type)\n {\n BufferedImage dest = new BufferedImage(width, height, type);\n Graphics2D g2 = dest.createGraphics();\n g2.drawImage(image, 0, 0, null);\n g2.dispose();\n return dest;\n }\n\n public static BufferedImage convertRGBAToIndexed(BufferedImage srcImage)\n {\n // Create a non-transparent palletized image\n Image flattenedImage = transformTransparencyToMagenta(srcImage);\n BufferedImage flatImage = imageToBufferedImage(flattenedImage,\n srcImage.getWidth(), srcImage.getHeight(), BufferedImage.TYPE_BYTE_INDEXED);\n BufferedImage destImage = makeColorTransparent(flatImage, 0, 0);\n return destImage;\n }\n\n private static Image transformTransparencyToMagenta(BufferedImage image)\n {\n ImageFilter filter = new RGBImageFilter()\n {\n @Override\n public final int filterRGB(int x, int y, int rgb)\n {\n int pixelValue = 0;\n int opacity = (rgb &amp; ALPHA_BIT_MASK) &gt;&gt;&gt; 24;\n if (opacity &lt; 128)\n {\n // Quite transparent: replace color with transparent magenta\n // (traditional color for binary transparency)\n pixelValue = 0x00FF00FF;\n }\n else\n {\n // Quite opaque: get pure color\n pixelValue = (rgb &amp; 0xFFFFFF) | ALPHA_BIT_MASK;\n }\n return pixelValue;\n }\n };\n\n ImageProducer ip = new FilteredImageSource(image.getSource(), filter);\n return Toolkit.getDefaultToolkit().createImage(ip);\n }\n\n public static BufferedImage makeColorTransparent(BufferedImage image, int x, int y)\n {\n ColorModel cm = image.getColorModel();\n if (!(cm instanceof IndexColorModel))\n return image; // No transparency added as we don't have an indexed image\n\n IndexColorModel originalICM = (IndexColorModel) cm;\n WritableRaster raster = image.getRaster();\n int colorIndex = raster.getSample(x, y, 0); // colorIndex is an offset in the palette of the ICM'\n // Number of indexed colors\n int size = originalICM.getMapSize();\n byte[] reds = new byte[size];\n byte[] greens = new byte[size];\n byte[] blues = new byte[size];\n originalICM.getReds(reds);\n originalICM.getGreens(greens);\n originalICM.getBlues(blues);\n IndexColorModel newICM = new IndexColorModel(8, size, reds, greens, blues, colorIndex);\n return new BufferedImage(newICM, raster, image.isAlphaPremultiplied(), null);\n }\n}\n</code></pre>\n" }, { "answer_id": 269742, "author": "kasperjj", "author_id": 34240, "author_profile": "https://Stackoverflow.com/users/34240", "pm_score": 2, "selected": false, "text": "<p>The build in imageio png writer will write 32bit png files on all the platforms I have used it on, no matter what the source image is. You should also be aware that many people have complained that the resulting compression is much lower than what is possible with the png format. There are several independent <a href=\"http://www.catcode.com/pngencoder/\" rel=\"nofollow noreferrer\">png libraries</a> available that allow you to specify the exact format, but I don't actually have any experience with any of them.</p>\n" }, { "answer_id": 270075, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Thanks for responding, I was going to try an <code>TYPE_BYTE_INDEXED</code> with an IndexColorModel and may still but if ImageIO writes out 32-bit regardless it appears that I may be wasting my time there. </p>\n\n<p>The image I am trying to write out can be very large (up to 8000x4000) but is just a simple mask for the image underneath, so will only have a ~30% transparent gray and a 100% transparent cutout. I would use a GIF but IE6 seems to have trouble with displaying one that large. </p>\n\n<p>It only gets generated once and in an internal set-up type screen, so performance isn't an issue either, but it does have to be done within the java code and not by an offline utility.</p>\n\n<p>The libraries that you specified might be used to transform it while writing... I am going to go check that out.</p>\n\n<p>If anyone has a better way, please let me know!! </p>\n\n<p>Thanks!</p>\n" }, { "answer_id": 270348, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I found the answer as to how to convert RGBA to Indexed here: <a href=\"http://www.eichberger.de/2007/07/transparent-gifs-in-java.html\" rel=\"nofollow noreferrer\">http://www.eichberger.de/2007/07/transparent-gifs-in-java.html</a></p>\n\n<p>However, the resulting 8-bit png file only has 100% or 0% transparency. You could probably tweak the IndexColorModel arrays, but we have decided to make the generated file (what was an overlay mask) into an underlay jpg and use what was the static base as the transparent overlay. </p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to write out a png file from a java.awt.image.BufferedImage. Everything works fine but the resulting png is a 32-bit file. Is there a way to make the png file be 8-bit? The image is grayscale, but I do need transparency as this is an overlay image. I am using java 6, and I would prefer to return an OutputStream so that I can have the calling class deal with writing out the file to disk/db. Here is the relevant portion of the code: ``` public static ByteArrayOutputStream createImage(InputStream originalStream) throws IOException { ByteArrayOutputStream oStream = null; java.awt.Image newImg = javax.imageio.ImageIO.read(originalStream); int imgWidth = newImg.getWidth(null); int imgHeight = newImg.getHeight(null); java.awt.image.BufferedImage bim = new java.awt.image.BufferedImage(imgWidth, imgHeight, java.awt.image.BufferedImage.TYPE_INT_ARGB); Color bckgrndColor = new Color(0x80, 0x80, 0x80); Graphics2D gf = (Graphics2D)bim.getGraphics(); // set transparency for fill image gf.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f)); gf.setColor(bckgrndColor); gf.fillRect(0, 0, imgWidth, imgHeight); oStream = new ByteArrayOutputStream(); javax.imageio.ImageIO.write(bim, "png", oStream); oStream.close(); return oStream; } ```
The build in imageio png writer will write 32bit png files on all the platforms I have used it on, no matter what the source image is. You should also be aware that many people have complained that the resulting compression is much lower than what is possible with the png format. There are several independent [png libraries](http://www.catcode.com/pngencoder/) available that allow you to specify the exact format, but I don't actually have any experience with any of them.
266,491
<p>I have a lot of buttons and by clicking on different button, different image and text would appear. I can achieve what I want, but the code is just so long and it seems very repetitive. For example:</p> <pre><code> var aaClick = false; $("aa").observe('click', function() { unclick(); $('characterPic').writeAttribute('src',"aa.jpg"); $('characterBio').update("aatext"); $('aa').setStyle({ color: '#FFFFFF' }); aaClick = true; }); $("aa").observe('mouseover', function() { if (!aaClick) $('aa').setStyle({ color: '#FFFFFF' }); }); $("aa").observe('mouseout', function() { if (!aaClick) $('aa').setStyle({ color: '#666666' }); }); function unclick() { aaClick = false; $('aa').setStyle({ color: '#666666' }); } </code></pre> <p>same thing with bb, cc, etc. and every time I add a new button, I need to add it to unclick function as well. This is pretty annoying and I tried to google it, and I only found observe click on all listed items, so I still couldn't figure out since what I want involves button up when other buttons are clicked. </p> <p>Is there any way to just have a generic function that takes different id but do the exact same thing? Because from what I can see, if I can just replace aa with other id, I can reduce a lot of code. Thanks!!!</p>
[ { "answer_id": 266515, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<p>Do the buttons share a common container? Then the following code works:</p>\n\n<pre><code>$(container).childElements().each(function(element) {\n $(element).observe('click', function () { … });\n …\n});\n</code></pre>\n\n<p>Alternatively, you can also do this:</p>\n\n<pre><code>[\"aa\", \"bb\", \"cc\"].each(function(element) { … same code … });\n</code></pre>\n" }, { "answer_id": 266533, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 3, "selected": true, "text": "<p>Build it all into a function where you can simply pass it the names of the DIVs you want to register. As long are you are consistent with your .jpg names, it should work.</p>\n\n<pre><code>var clicks = []\nfunction regEvents(divName) {\n $(divName).observe('click', function() {\n unclick(divName);\n $('characterPic').writeAttribute('src',divName+\".jpg\");\n $('characterBio').update(divName\"text\");\n $(divName).setStyle({ color: '#FFFFFF' });\n clicks[divName] = true\n\n });\n\n $(divName).observe('mouseover', function() {\n if (!clicks[divName]) $(divName).setStyle({ color: '#FFFFFF' });\n });\n\n $(divName).observe('mouseout', function() {\n if (!clicks[divName]) $(divName).setStyle({ color: '#666666' });\n });\n}\nfunction unclick(divName) {\n clicks[divName] = false;\n $(clicks[divName]).setStyle({ color: '#666666' });\n}\n</code></pre>\n" }, { "answer_id": 266550, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "<p>The event handlers can have an argument that will be set to the event target. Then you could reuse the same function:</p>\n\n<pre><code>var clickedHandler = function(element) { \n $(element).addClass(\"selected\");\n};\n$(\"aa\").observe('click', clickedHandler);\n$(\"bb\").observe('click', clickedHandler);\n</code></pre>\n\n<p>You're also in desperate need to CSS styling. Please see my <a href=\"https://stackoverflow.com/questions/266199/prototype-click-mouseover-and-mouseout-cant-work-together#266228\">answer</a> to your previous question, but you could just reuse the pattern for the other events.</p>\n" }, { "answer_id": 266558, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 1, "selected": false, "text": "<p>Event delegation. Give all your buttons a class (eg <code>yourButtonClass</code>), then...</p>\n\n<pre><code>var clicks = [];\n$$('.yourButtonClass').each(function(button) {\n clicks.push(button.id);\n});\n$(document).observe('click', function(e) {\n // If your click registered on an element contained by the button, this comes in handy...\n var clicked = e.element().up('.yourButtonClass') || e.element();\n\n if(clicked.hasClassName('.yourButtonClass')) {\n unclick();\n $('characterPic').writeAttribute('src', clicked.id + '.jpg');\n $('characterBio').update(clicked.id + 'text');\n $(clicked).setStyle({ color: '#FFFFFF' });\n clicks[clicked.id] = true;\n }\n});\n</code></pre>\n\n<p>And so on...</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34797/" ]
I have a lot of buttons and by clicking on different button, different image and text would appear. I can achieve what I want, but the code is just so long and it seems very repetitive. For example: ``` var aaClick = false; $("aa").observe('click', function() { unclick(); $('characterPic').writeAttribute('src',"aa.jpg"); $('characterBio').update("aatext"); $('aa').setStyle({ color: '#FFFFFF' }); aaClick = true; }); $("aa").observe('mouseover', function() { if (!aaClick) $('aa').setStyle({ color: '#FFFFFF' }); }); $("aa").observe('mouseout', function() { if (!aaClick) $('aa').setStyle({ color: '#666666' }); }); function unclick() { aaClick = false; $('aa').setStyle({ color: '#666666' }); } ``` same thing with bb, cc, etc. and every time I add a new button, I need to add it to unclick function as well. This is pretty annoying and I tried to google it, and I only found observe click on all listed items, so I still couldn't figure out since what I want involves button up when other buttons are clicked. Is there any way to just have a generic function that takes different id but do the exact same thing? Because from what I can see, if I can just replace aa with other id, I can reduce a lot of code. Thanks!!!
Build it all into a function where you can simply pass it the names of the DIVs you want to register. As long are you are consistent with your .jpg names, it should work. ``` var clicks = [] function regEvents(divName) { $(divName).observe('click', function() { unclick(divName); $('characterPic').writeAttribute('src',divName+".jpg"); $('characterBio').update(divName"text"); $(divName).setStyle({ color: '#FFFFFF' }); clicks[divName] = true }); $(divName).observe('mouseover', function() { if (!clicks[divName]) $(divName).setStyle({ color: '#FFFFFF' }); }); $(divName).observe('mouseout', function() { if (!clicks[divName]) $(divName).setStyle({ color: '#666666' }); }); } function unclick(divName) { clicks[divName] = false; $(clicks[divName]).setStyle({ color: '#666666' }); } ```
266,501
<p>Is there a way to define a macro that contains a <code>#include</code> directive in its body?</p> <p>If I just put the "<code>#include</code>", it gives the error</p> <pre><code>C2162: "expected macro formal parameter" </code></pre> <p>since here I am not using <code>#</code> to concatenate strings.<br> If I use "<code>\# include</code>", then I receive the following two errors:</p> <pre><code>error C2017: illegal escape sequence error C2121: '#' : invalid character : possibly the result of a macro expansion </code></pre> <p>Any help?</p>
[ { "answer_id": 266529, "author": "helloandre", "author_id": 50, "author_profile": "https://Stackoverflow.com/users/50", "pm_score": 0, "selected": false, "text": "<p>Why would the macro need to have an #include? if you're #include'ing whatever file the macro is in, you could just put the #include above the macro with all the rest of the #include statements, and everything should be nice and dandy. </p>\n\n<p>I see no reason to have the macro include anything that couldn't just be included in the file.</p>\n" }, { "answer_id": 266534, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 3, "selected": false, "text": "<p>I believe the C/C++ preprocessor only does a single pass over the code, so I don't think that would work. You might be able to get a \"#include\" to be placed in the code by the macro, but the compiler would choke on it, since it doesn't know what to do with that. For what you're trying to do to work the preprocessor would have to do a second pass over the file in order to pick up the #include.</p>\n" }, { "answer_id": 266580, "author": "HanClinto", "author_id": 26933, "author_profile": "https://Stackoverflow.com/users/26933", "pm_score": -1, "selected": false, "text": "<p>Contagious is right -- if you're doing:</p>\n\n<p>myFile.c:</p>\n\n<pre><code>#include \"standardAppDefs.h\"\n#myStandardIncludeMacro\n</code></pre>\n\n<p>standardAppDefs.h:</p>\n\n<pre><code>#define myStandardIncludeMacro #include &lt;foo.h&gt;\n</code></pre>\n\n<p>Why not just say:</p>\n\n<p>myFile.c:</p>\n\n<pre><code>#include \"standardAppDefs.h\"\n</code></pre>\n\n<p>standardAppDefs.h:</p>\n\n<pre><code>#include &lt;foo.h&gt;\n</code></pre>\n\n<p>And forget the macros?</p>\n" }, { "answer_id": 266647, "author": "Bing Jian", "author_id": 34829, "author_profile": "https://Stackoverflow.com/users/34829", "pm_score": 2, "selected": false, "text": "<p>I think you are all right in that this task seems impossible as I also got from</p>\n\n<p><a href=\"http://groups.google.com/group/comp.lang.c++/browse_thread/thread/03d20d234539a85c#\" rel=\"nofollow noreferrer\">http://groups.google.com/group/comp.lang.c++/browse_thread/thread/03d20d234539a85c#</a></p>\n\n<blockquote>\n <p>No, preprocessor directives in C++\n (and C) are not reflective.</p>\n \n <p>Pawel Dziepak</p>\n</blockquote>\n\n<p>Anyway, the reason behind this attempt is that I am trying to make the following\nrepeatedly used code snippet as a macro:</p>\n\n<pre><code>void foo(AbstractClass object)\n{\n switch (object.data_type())\n {\n case AbstractClass::TYPE_UCHAR :\n {\n typedef unsigned char PixelType;\n #include \"snippets/foo.cpp\"\n }\n break;\n case AbstractClass::TYPE_UINT:\n {\n typedef unsigned int PixelType;\n #include \"snippets/foo.cpp\"\n }\n break;\n default:\n break;\n }\n}\n</code></pre>\n\n<p>For another task, I need to have a similar function</p>\n\n<pre><code>void bar(AbstractClass object)\n</code></pre>\n\n<p>where I will place</p>\n\n<pre><code>#include \"snippets/bar.cpp\"\n</code></pre>\n\n<p>and of course it is in \"snippets/foo.cpp\" and \"snippets/bar.cpp\" that the task-specific code is written. </p>\n" }, { "answer_id": 266679, "author": "Dan Hewett", "author_id": 17975, "author_profile": "https://Stackoverflow.com/users/17975", "pm_score": 4, "selected": false, "text": "<p>I will not argue the merits for it, but freetype (www.freetype.org) does the following:</p>\n\n<pre><code>#include FT_FREETYPE_H\n</code></pre>\n\n<p>where they define FT_FREETYPE_H elsewhere</p>\n" }, { "answer_id": 266723, "author": "user21714", "author_id": 21714, "author_profile": "https://Stackoverflow.com/users/21714", "pm_score": 0, "selected": false, "text": "<p>I have no idea what you are actually trying to do but it looks like what you might want is a templated function. </p>\n\n<p>That way the PixelType is just a template parameter to the block of code.</p>\n" }, { "answer_id": 3613287, "author": "Lutorm", "author_id": 307175, "author_profile": "https://Stackoverflow.com/users/307175", "pm_score": 2, "selected": false, "text": "<p>I also wanted to do this, and here's the reason:</p>\n\n<p>Some header files (notably mpi.h in OpenMPI) work differently if you are compiling in C or C++. I'm linking to a C MPI code from my C++ program. To include the header, I do the usual:</p>\n\n<pre><code>extern \"C\" {\n#include \"blah.h\"\n}\n</code></pre>\n\n<p>But this doesn't work because <code>__cplusplus</code> is still defined even in C linkage. That means mpi.h, which is included by blah.h, starts defining templates and the compiler dies saying you can't use templates with C linkage.</p>\n\n<p>Hence, what I have to do in blah.h is to replace</p>\n\n<pre><code>#include &lt;mpi.h&gt;\n</code></pre>\n\n<p>with </p>\n\n<pre><code>#ifdef __cplusplus\n#undef __cplusplus\n#include &lt;mpi.h&gt;\n#define __cplusplus\n#else\n#include &lt;mpi.h&gt;\n#endif\n</code></pre>\n\n<p>Remarkably it's not just mpi.h that does this pathological thing. Hence, I want to define a macro <code>INCLUDE_AS_C</code> which does the above for the specified file. But I guess that doesn't work.</p>\n\n<p>If anyone can figure out another way of accomplishing this, please let me know.</p>\n" }, { "answer_id": 3613346, "author": "AnT stands with Russia", "author_id": 187690, "author_profile": "https://Stackoverflow.com/users/187690", "pm_score": 3, "selected": false, "text": "<p>C and C++ languages explicitly prohibit forming preprocessor directives as the result of macro expansion. This means that you can't include a preprocessor directive into a macro replacement list. And if you try to trick the preprocessor by \"building\" a new preprocessor directive through concatenation (and tricks like that), the behavior is undefined.</p>\n" }, { "answer_id": 27830271, "author": "Ben Farmer", "author_id": 1447953, "author_profile": "https://Stackoverflow.com/users/1447953", "pm_score": 5, "selected": false, "text": "<p>So like the others say, no, you can't have #include statements inside a macro, since the preprocessor only does one pass. However, you can make the preprocessor do basically the same thing with a gnarly trick I found myself using recently.</p>\n\n<p>Realise that preprocessor directives won't do anything inside a macro, however they WILL do something in a file. So, you can stick a block of code you want to mutate into a file, thinking of it like a macro definition (with pieces that can be altered by other macros), and then #include this pseudo-macro file in various places (make sure it has no include guards!). It doesn't behave exactly like a macro would, but it can achieve some pretty macro-like results, since #include basically just dumps the contents of one file into another.</p>\n\n<p>For example, consider including lots of similarly named headers that come in groups. It is tedious to write them all out, or perhaps even they are auto-generated. You can partially automate their inclusion by doing something like this:</p>\n\n<p>Helper macros header:</p>\n\n<pre><code>/* tools.hpp */\n\n#ifndef __TOOLS_HPP__\n#def __TOOLS_HPP__\n\n// Macro for adding quotes\n#define STRINGIFY(X) STRINGIFY2(X) \n#define STRINGIFY2(X) #X\n\n// Macros for concatenating tokens\n#define CAT(X,Y) CAT2(X,Y)\n#define CAT2(X,Y) X##Y\n#define CAT_2 CAT\n#define CAT_3(X,Y,Z) CAT(X,CAT(Y,Z))\n#define CAT_4(A,X,Y,Z) CAT(A,CAT_3(X,Y,Z))\n// etc...\n\n#endif\n</code></pre>\n\n<p>Pseudo-macro file</p>\n\n<pre><code>/* pseudomacro.hpp */\n\n#include \"tools.hpp\"\n// NO INCLUDE GUARD ON PURPOSE\n// Note especially FOO, which we can #define before #include-ing this file,\n// in order to alter which files it will in turn #include.\n// FOO fulfils the role of \"parameter\" in this pseudo-macro.\n\n#define INCLUDE_FILE(HEAD,TAIL) STRINGIFY( CAT_3(HEAD,FOO,TAIL) )\n\n#include INCLUDE_FILE(head1,tail1.hpp) // expands to #head1FOOtail1.hpp\n#include INCLUDE_FILE(head2,tail2.hpp)\n#include INCLUDE_FILE(head3,tail3.hpp)\n#include INCLUDE_FILE(head4,tail4.hpp)\n// etc..\n\n#undef INCLUDE_FILE\n</code></pre>\n\n<p>Source file</p>\n\n<pre><code>/* mainfile.cpp */\n\n// Here we automate the including of groups of similarly named files\n\n#define FOO _groupA_\n#include \"pseudomacro.hpp\"\n// \"expands\" to: \n// #include \"head1_groupA_tail1.hpp\"\n// #include \"head2_groupA_tail2.hpp\"\n// #include \"head3_groupA_tail3.hpp\"\n// #include \"head4_groupA_tail4.hpp\"\n#undef FOO\n\n#define FOO _groupB_\n#include \"pseudomacro.hpp\"\n// \"expands\" to: \n// #include \"head1_groupB_tail1.hpp\"\n// #include \"head2_groupB_tail2.hpp\"\n// #include \"head3_groupB_tail3.hpp\"\n// #include \"head4_groupB_tail4.hpp\"\n#undef FOO\n\n#define FOO _groupC_\n#include \"pseudomacro.hpp\"\n#undef FOO\n\n// etc.\n</code></pre>\n\n<p>These includes could even be in the middle of codes blocks you want to repeat (with FOO altered), as the answer by Bing Jian requests: <a href=\"https://stackoverflow.com/questions/266501/macro-definition-containing-include-directive/266647#266647\">macro definition containing #include directive</a></p>\n\n<p>I haven't used this trick extensively, but it gets my job done. It can obviously be extended to have as many \"parameters\" as needed, and you can run whatever preprocessor commands you like in there, plus generate actual code. You just can't use the stuff it creates as the input into another macro, like you can with normal macros, since you can't stick the include inside a macro. But it can go inside another pseudo-macro :).</p>\n\n<p>Others might have some comments on other limitations, and what could go wrong :). </p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34829/" ]
Is there a way to define a macro that contains a `#include` directive in its body? If I just put the "`#include`", it gives the error ``` C2162: "expected macro formal parameter" ``` since here I am not using `#` to concatenate strings. If I use "`\# include`", then I receive the following two errors: ``` error C2017: illegal escape sequence error C2121: '#' : invalid character : possibly the result of a macro expansion ``` Any help?
So like the others say, no, you can't have #include statements inside a macro, since the preprocessor only does one pass. However, you can make the preprocessor do basically the same thing with a gnarly trick I found myself using recently. Realise that preprocessor directives won't do anything inside a macro, however they WILL do something in a file. So, you can stick a block of code you want to mutate into a file, thinking of it like a macro definition (with pieces that can be altered by other macros), and then #include this pseudo-macro file in various places (make sure it has no include guards!). It doesn't behave exactly like a macro would, but it can achieve some pretty macro-like results, since #include basically just dumps the contents of one file into another. For example, consider including lots of similarly named headers that come in groups. It is tedious to write them all out, or perhaps even they are auto-generated. You can partially automate their inclusion by doing something like this: Helper macros header: ``` /* tools.hpp */ #ifndef __TOOLS_HPP__ #def __TOOLS_HPP__ // Macro for adding quotes #define STRINGIFY(X) STRINGIFY2(X) #define STRINGIFY2(X) #X // Macros for concatenating tokens #define CAT(X,Y) CAT2(X,Y) #define CAT2(X,Y) X##Y #define CAT_2 CAT #define CAT_3(X,Y,Z) CAT(X,CAT(Y,Z)) #define CAT_4(A,X,Y,Z) CAT(A,CAT_3(X,Y,Z)) // etc... #endif ``` Pseudo-macro file ``` /* pseudomacro.hpp */ #include "tools.hpp" // NO INCLUDE GUARD ON PURPOSE // Note especially FOO, which we can #define before #include-ing this file, // in order to alter which files it will in turn #include. // FOO fulfils the role of "parameter" in this pseudo-macro. #define INCLUDE_FILE(HEAD,TAIL) STRINGIFY( CAT_3(HEAD,FOO,TAIL) ) #include INCLUDE_FILE(head1,tail1.hpp) // expands to #head1FOOtail1.hpp #include INCLUDE_FILE(head2,tail2.hpp) #include INCLUDE_FILE(head3,tail3.hpp) #include INCLUDE_FILE(head4,tail4.hpp) // etc.. #undef INCLUDE_FILE ``` Source file ``` /* mainfile.cpp */ // Here we automate the including of groups of similarly named files #define FOO _groupA_ #include "pseudomacro.hpp" // "expands" to: // #include "head1_groupA_tail1.hpp" // #include "head2_groupA_tail2.hpp" // #include "head3_groupA_tail3.hpp" // #include "head4_groupA_tail4.hpp" #undef FOO #define FOO _groupB_ #include "pseudomacro.hpp" // "expands" to: // #include "head1_groupB_tail1.hpp" // #include "head2_groupB_tail2.hpp" // #include "head3_groupB_tail3.hpp" // #include "head4_groupB_tail4.hpp" #undef FOO #define FOO _groupC_ #include "pseudomacro.hpp" #undef FOO // etc. ``` These includes could even be in the middle of codes blocks you want to repeat (with FOO altered), as the answer by Bing Jian requests: [macro definition containing #include directive](https://stackoverflow.com/questions/266501/macro-definition-containing-include-directive/266647#266647) I haven't used this trick extensively, but it gets my job done. It can obviously be extended to have as many "parameters" as needed, and you can run whatever preprocessor commands you like in there, plus generate actual code. You just can't use the stuff it creates as the input into another macro, like you can with normal macros, since you can't stick the include inside a macro. But it can go inside another pseudo-macro :). Others might have some comments on other limitations, and what could go wrong :).
266,506
<p>Using a standard ASP.NET ListView with a LinqDataSource and pagination enabled (with a DataPager), what would be the best way to default to displaying the last page of results?</p>
[ { "answer_id": 266529, "author": "helloandre", "author_id": 50, "author_profile": "https://Stackoverflow.com/users/50", "pm_score": 0, "selected": false, "text": "<p>Why would the macro need to have an #include? if you're #include'ing whatever file the macro is in, you could just put the #include above the macro with all the rest of the #include statements, and everything should be nice and dandy. </p>\n\n<p>I see no reason to have the macro include anything that couldn't just be included in the file.</p>\n" }, { "answer_id": 266534, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 3, "selected": false, "text": "<p>I believe the C/C++ preprocessor only does a single pass over the code, so I don't think that would work. You might be able to get a \"#include\" to be placed in the code by the macro, but the compiler would choke on it, since it doesn't know what to do with that. For what you're trying to do to work the preprocessor would have to do a second pass over the file in order to pick up the #include.</p>\n" }, { "answer_id": 266580, "author": "HanClinto", "author_id": 26933, "author_profile": "https://Stackoverflow.com/users/26933", "pm_score": -1, "selected": false, "text": "<p>Contagious is right -- if you're doing:</p>\n\n<p>myFile.c:</p>\n\n<pre><code>#include \"standardAppDefs.h\"\n#myStandardIncludeMacro\n</code></pre>\n\n<p>standardAppDefs.h:</p>\n\n<pre><code>#define myStandardIncludeMacro #include &lt;foo.h&gt;\n</code></pre>\n\n<p>Why not just say:</p>\n\n<p>myFile.c:</p>\n\n<pre><code>#include \"standardAppDefs.h\"\n</code></pre>\n\n<p>standardAppDefs.h:</p>\n\n<pre><code>#include &lt;foo.h&gt;\n</code></pre>\n\n<p>And forget the macros?</p>\n" }, { "answer_id": 266647, "author": "Bing Jian", "author_id": 34829, "author_profile": "https://Stackoverflow.com/users/34829", "pm_score": 2, "selected": false, "text": "<p>I think you are all right in that this task seems impossible as I also got from</p>\n\n<p><a href=\"http://groups.google.com/group/comp.lang.c++/browse_thread/thread/03d20d234539a85c#\" rel=\"nofollow noreferrer\">http://groups.google.com/group/comp.lang.c++/browse_thread/thread/03d20d234539a85c#</a></p>\n\n<blockquote>\n <p>No, preprocessor directives in C++\n (and C) are not reflective.</p>\n \n <p>Pawel Dziepak</p>\n</blockquote>\n\n<p>Anyway, the reason behind this attempt is that I am trying to make the following\nrepeatedly used code snippet as a macro:</p>\n\n<pre><code>void foo(AbstractClass object)\n{\n switch (object.data_type())\n {\n case AbstractClass::TYPE_UCHAR :\n {\n typedef unsigned char PixelType;\n #include \"snippets/foo.cpp\"\n }\n break;\n case AbstractClass::TYPE_UINT:\n {\n typedef unsigned int PixelType;\n #include \"snippets/foo.cpp\"\n }\n break;\n default:\n break;\n }\n}\n</code></pre>\n\n<p>For another task, I need to have a similar function</p>\n\n<pre><code>void bar(AbstractClass object)\n</code></pre>\n\n<p>where I will place</p>\n\n<pre><code>#include \"snippets/bar.cpp\"\n</code></pre>\n\n<p>and of course it is in \"snippets/foo.cpp\" and \"snippets/bar.cpp\" that the task-specific code is written. </p>\n" }, { "answer_id": 266679, "author": "Dan Hewett", "author_id": 17975, "author_profile": "https://Stackoverflow.com/users/17975", "pm_score": 4, "selected": false, "text": "<p>I will not argue the merits for it, but freetype (www.freetype.org) does the following:</p>\n\n<pre><code>#include FT_FREETYPE_H\n</code></pre>\n\n<p>where they define FT_FREETYPE_H elsewhere</p>\n" }, { "answer_id": 266723, "author": "user21714", "author_id": 21714, "author_profile": "https://Stackoverflow.com/users/21714", "pm_score": 0, "selected": false, "text": "<p>I have no idea what you are actually trying to do but it looks like what you might want is a templated function. </p>\n\n<p>That way the PixelType is just a template parameter to the block of code.</p>\n" }, { "answer_id": 3613287, "author": "Lutorm", "author_id": 307175, "author_profile": "https://Stackoverflow.com/users/307175", "pm_score": 2, "selected": false, "text": "<p>I also wanted to do this, and here's the reason:</p>\n\n<p>Some header files (notably mpi.h in OpenMPI) work differently if you are compiling in C or C++. I'm linking to a C MPI code from my C++ program. To include the header, I do the usual:</p>\n\n<pre><code>extern \"C\" {\n#include \"blah.h\"\n}\n</code></pre>\n\n<p>But this doesn't work because <code>__cplusplus</code> is still defined even in C linkage. That means mpi.h, which is included by blah.h, starts defining templates and the compiler dies saying you can't use templates with C linkage.</p>\n\n<p>Hence, what I have to do in blah.h is to replace</p>\n\n<pre><code>#include &lt;mpi.h&gt;\n</code></pre>\n\n<p>with </p>\n\n<pre><code>#ifdef __cplusplus\n#undef __cplusplus\n#include &lt;mpi.h&gt;\n#define __cplusplus\n#else\n#include &lt;mpi.h&gt;\n#endif\n</code></pre>\n\n<p>Remarkably it's not just mpi.h that does this pathological thing. Hence, I want to define a macro <code>INCLUDE_AS_C</code> which does the above for the specified file. But I guess that doesn't work.</p>\n\n<p>If anyone can figure out another way of accomplishing this, please let me know.</p>\n" }, { "answer_id": 3613346, "author": "AnT stands with Russia", "author_id": 187690, "author_profile": "https://Stackoverflow.com/users/187690", "pm_score": 3, "selected": false, "text": "<p>C and C++ languages explicitly prohibit forming preprocessor directives as the result of macro expansion. This means that you can't include a preprocessor directive into a macro replacement list. And if you try to trick the preprocessor by \"building\" a new preprocessor directive through concatenation (and tricks like that), the behavior is undefined.</p>\n" }, { "answer_id": 27830271, "author": "Ben Farmer", "author_id": 1447953, "author_profile": "https://Stackoverflow.com/users/1447953", "pm_score": 5, "selected": false, "text": "<p>So like the others say, no, you can't have #include statements inside a macro, since the preprocessor only does one pass. However, you can make the preprocessor do basically the same thing with a gnarly trick I found myself using recently.</p>\n\n<p>Realise that preprocessor directives won't do anything inside a macro, however they WILL do something in a file. So, you can stick a block of code you want to mutate into a file, thinking of it like a macro definition (with pieces that can be altered by other macros), and then #include this pseudo-macro file in various places (make sure it has no include guards!). It doesn't behave exactly like a macro would, but it can achieve some pretty macro-like results, since #include basically just dumps the contents of one file into another.</p>\n\n<p>For example, consider including lots of similarly named headers that come in groups. It is tedious to write them all out, or perhaps even they are auto-generated. You can partially automate their inclusion by doing something like this:</p>\n\n<p>Helper macros header:</p>\n\n<pre><code>/* tools.hpp */\n\n#ifndef __TOOLS_HPP__\n#def __TOOLS_HPP__\n\n// Macro for adding quotes\n#define STRINGIFY(X) STRINGIFY2(X) \n#define STRINGIFY2(X) #X\n\n// Macros for concatenating tokens\n#define CAT(X,Y) CAT2(X,Y)\n#define CAT2(X,Y) X##Y\n#define CAT_2 CAT\n#define CAT_3(X,Y,Z) CAT(X,CAT(Y,Z))\n#define CAT_4(A,X,Y,Z) CAT(A,CAT_3(X,Y,Z))\n// etc...\n\n#endif\n</code></pre>\n\n<p>Pseudo-macro file</p>\n\n<pre><code>/* pseudomacro.hpp */\n\n#include \"tools.hpp\"\n// NO INCLUDE GUARD ON PURPOSE\n// Note especially FOO, which we can #define before #include-ing this file,\n// in order to alter which files it will in turn #include.\n// FOO fulfils the role of \"parameter\" in this pseudo-macro.\n\n#define INCLUDE_FILE(HEAD,TAIL) STRINGIFY( CAT_3(HEAD,FOO,TAIL) )\n\n#include INCLUDE_FILE(head1,tail1.hpp) // expands to #head1FOOtail1.hpp\n#include INCLUDE_FILE(head2,tail2.hpp)\n#include INCLUDE_FILE(head3,tail3.hpp)\n#include INCLUDE_FILE(head4,tail4.hpp)\n// etc..\n\n#undef INCLUDE_FILE\n</code></pre>\n\n<p>Source file</p>\n\n<pre><code>/* mainfile.cpp */\n\n// Here we automate the including of groups of similarly named files\n\n#define FOO _groupA_\n#include \"pseudomacro.hpp\"\n// \"expands\" to: \n// #include \"head1_groupA_tail1.hpp\"\n// #include \"head2_groupA_tail2.hpp\"\n// #include \"head3_groupA_tail3.hpp\"\n// #include \"head4_groupA_tail4.hpp\"\n#undef FOO\n\n#define FOO _groupB_\n#include \"pseudomacro.hpp\"\n// \"expands\" to: \n// #include \"head1_groupB_tail1.hpp\"\n// #include \"head2_groupB_tail2.hpp\"\n// #include \"head3_groupB_tail3.hpp\"\n// #include \"head4_groupB_tail4.hpp\"\n#undef FOO\n\n#define FOO _groupC_\n#include \"pseudomacro.hpp\"\n#undef FOO\n\n// etc.\n</code></pre>\n\n<p>These includes could even be in the middle of codes blocks you want to repeat (with FOO altered), as the answer by Bing Jian requests: <a href=\"https://stackoverflow.com/questions/266501/macro-definition-containing-include-directive/266647#266647\">macro definition containing #include directive</a></p>\n\n<p>I haven't used this trick extensively, but it gets my job done. It can obviously be extended to have as many \"parameters\" as needed, and you can run whatever preprocessor commands you like in there, plus generate actual code. You just can't use the stuff it creates as the input into another macro, like you can with normal macros, since you can't stick the include inside a macro. But it can go inside another pseudo-macro :).</p>\n\n<p>Others might have some comments on other limitations, and what could go wrong :). </p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9433/" ]
Using a standard ASP.NET ListView with a LinqDataSource and pagination enabled (with a DataPager), what would be the best way to default to displaying the last page of results?
So like the others say, no, you can't have #include statements inside a macro, since the preprocessor only does one pass. However, you can make the preprocessor do basically the same thing with a gnarly trick I found myself using recently. Realise that preprocessor directives won't do anything inside a macro, however they WILL do something in a file. So, you can stick a block of code you want to mutate into a file, thinking of it like a macro definition (with pieces that can be altered by other macros), and then #include this pseudo-macro file in various places (make sure it has no include guards!). It doesn't behave exactly like a macro would, but it can achieve some pretty macro-like results, since #include basically just dumps the contents of one file into another. For example, consider including lots of similarly named headers that come in groups. It is tedious to write them all out, or perhaps even they are auto-generated. You can partially automate their inclusion by doing something like this: Helper macros header: ``` /* tools.hpp */ #ifndef __TOOLS_HPP__ #def __TOOLS_HPP__ // Macro for adding quotes #define STRINGIFY(X) STRINGIFY2(X) #define STRINGIFY2(X) #X // Macros for concatenating tokens #define CAT(X,Y) CAT2(X,Y) #define CAT2(X,Y) X##Y #define CAT_2 CAT #define CAT_3(X,Y,Z) CAT(X,CAT(Y,Z)) #define CAT_4(A,X,Y,Z) CAT(A,CAT_3(X,Y,Z)) // etc... #endif ``` Pseudo-macro file ``` /* pseudomacro.hpp */ #include "tools.hpp" // NO INCLUDE GUARD ON PURPOSE // Note especially FOO, which we can #define before #include-ing this file, // in order to alter which files it will in turn #include. // FOO fulfils the role of "parameter" in this pseudo-macro. #define INCLUDE_FILE(HEAD,TAIL) STRINGIFY( CAT_3(HEAD,FOO,TAIL) ) #include INCLUDE_FILE(head1,tail1.hpp) // expands to #head1FOOtail1.hpp #include INCLUDE_FILE(head2,tail2.hpp) #include INCLUDE_FILE(head3,tail3.hpp) #include INCLUDE_FILE(head4,tail4.hpp) // etc.. #undef INCLUDE_FILE ``` Source file ``` /* mainfile.cpp */ // Here we automate the including of groups of similarly named files #define FOO _groupA_ #include "pseudomacro.hpp" // "expands" to: // #include "head1_groupA_tail1.hpp" // #include "head2_groupA_tail2.hpp" // #include "head3_groupA_tail3.hpp" // #include "head4_groupA_tail4.hpp" #undef FOO #define FOO _groupB_ #include "pseudomacro.hpp" // "expands" to: // #include "head1_groupB_tail1.hpp" // #include "head2_groupB_tail2.hpp" // #include "head3_groupB_tail3.hpp" // #include "head4_groupB_tail4.hpp" #undef FOO #define FOO _groupC_ #include "pseudomacro.hpp" #undef FOO // etc. ``` These includes could even be in the middle of codes blocks you want to repeat (with FOO altered), as the answer by Bing Jian requests: [macro definition containing #include directive](https://stackoverflow.com/questions/266501/macro-definition-containing-include-directive/266647#266647) I haven't used this trick extensively, but it gets my job done. It can obviously be extended to have as many "parameters" as needed, and you can run whatever preprocessor commands you like in there, plus generate actual code. You just can't use the stuff it creates as the input into another macro, like you can with normal macros, since you can't stick the include inside a macro. But it can go inside another pseudo-macro :). Others might have some comments on other limitations, and what could go wrong :).
266,549
<p>Using MEF I want to do the following.</p> <p>I have a WPF Shell. To the shell I want to Import from another DLL a UserControl that is also a View of my MVP triad. The way the MVP triad works, is that in presenter I have a constructor that takes both IModel and IView and wires them up. So, in order for this to work, I need MEF to do the following:</p> <ol> <li>Create IView implementation</li> <li>Create IModel implementation</li> <li>Create Presenter and pass IModel and IView to its constructor</li> <li>Import IView implementation into my shell when it gets displayed</li> </ol> <p>Instead what it does, is it only creates the type Exporting IView and passes it to the shell, basically skipping steps 2 and 3. Its pretty logical, when you think about it, but how can I tell MEF to also create the whole triad when I ask for a IView. I don't need to reference Presenter nor model anywhere else in my Shell .dll so puting it as an Import as well is not an option (and it would be quite ugly anyway :).</p> <p>I'm using the latest drop of MEF (Preview 2 Refresh). Anyone?</p> <p><strong>==Update==</strong></p> <p>I have found a solution and I blogged about it here:<br> <a href="http://kozmic.pl/archive/2008/11/06/creating-tree-of-dependencies-with-mef/" rel="nofollow noreferrer" title="here">Krzysztof Koźmic's blog - Creating tree of dependencies with MEF</a></p> <p>However, I'd be more than happy if someone came up with a better solution.**</p>
[ { "answer_id": 285531, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>The way you outlined in your blog post is the perfectly valid way for utilizing MEF. This is nested composition, and while designing it is always good to keep in mind that Container is the decider, so as a plug-in / extender vendor you will focus on your services that you are \"exporting\" and as an important, you shouldn't worry about what you need to be serviced, or \"importing\" (this point has some issues in the last drop, but I hear good enough to be optimistic about it). </p>\n\n<p>So in nested composition, you may need some external services but at the time you can also be providing some. When you do a compose, it will plug everything together. </p>\n\n<p>I have a blog post containing 2 examples illustrating this way of thinking : </p>\n\n<p><a href=\"http://www.sidarok.com/web/blog/content/2008/09/26/what-is-this-managed-extensibility-framework-thing-all-about.html\" rel=\"nofollow noreferrer\">http://www.sidarok.com/web/blog/content/2008/09/26/what-is-this-managed-extensibility-framework-thing-all-about.html</a> </p>\n\n<p>Also, to drop the dll and watch the types in it, you can use DirectoryPartCatalog to watch that folder. </p>\n\n<p>You will also need to watch out the scenarios where there are multiple exports for the same contract, and determine the right one from metadata provided. </p>\n" }, { "answer_id": 285744, "author": "Glenn Block", "author_id": 18419, "author_profile": "https://Stackoverflow.com/users/18419", "pm_score": 3, "selected": true, "text": "<p>Check my answer here.</p>\n\n<p><a href=\"http://codebetter.com/blogs/glenn.block/archive/2008/11/12/mvp-with-mef.aspx\" rel=\"nofollow noreferrer\">http://codebetter.com/blogs/glenn.block/archive/2008/11/12/mvp-with-mef.aspx</a> </p>\n\n<p>EDIT: (<em>Added from the link, to prevent not being flagged as low quality / LOA</em>)</p>\n\n<pre><code> 1: using System.ComponentModel.Composition;\n 2: using System.Reflection;\n 3: using Microsoft.VisualStudio.TestTools.UnitTesting;\n 4: \n 5: namespace MVPwithMEF\n 6: {\n 7: /// &lt;summary&gt;\n 8: /// Summary description for MVPTriadFixture\n 9: /// &lt;/summary&gt;\n 10: [TestClass]\n 11: public class MVPTriadFixture\n 12: {\n 13: [TestMethod]\n 14: public void MVPTriadShouldBeProperlyBuilt()\n 15: {\n 16: var catalog = new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly());\n 17: var container = new CompositionContainer(catalog.CreateResolver());\n 18: var shell = container.GetExportedObject&lt;Shell&gt;();\n 19: Assert.IsNotNull(shell);\n 20: Assert.IsNotNull(shell.Presenter);\n 21: Assert.IsNotNull(shell.Presenter.View);\n 22: Assert.IsNotNull(shell.Presenter.Model);\n 23: }\n 24: }\n 25: \n 26: [Export]\n 27: public class Shell\n 28: {\n 29: private IPresenter _presenter = null;\n 30: \n 31: public IPresenter Presenter\n 32: {\n 33: get { return _presenter; }\n 34: }\n 35: \n 36: [ImportingConstructor]\n 37: public Shell(IPresenter presenter)\n 38: {\n 39: _presenter = presenter;\n 40: }\n 41: }\n 42: \n 43: public interface IModel\n 44: {\n 45: }\n 46: \n 47: [Export(typeof(IModel))]\n 48: public class Model : IModel\n 49: {\n 50: \n 51: }\n 52: \n 53: public interface IView\n 54: {\n 55: }\n 56: \n 57: [Export(typeof(IView))]\n 58: public class View : IView\n 59: {\n 60: }\n 61: \n 62: public interface IPresenter\n 63: {\n 64: IView View { get;}\n 65: IModel Model { get; }\n 66: }\n 67: \n 68: [Export(typeof(IPresenter))]\n 69: public class Presenter : IPresenter\n 70: {\n 71: \n 72: private IView _view;\n 73: private IModel _model;\n 74: \n 75: [ImportingConstructor]\n 76: public Presenter(IView view, IModel model)\n 77: {\n 78: _view = view;\n 79: _model = model;\n 80: }\n 81: \n 82: public IView View\n 83: {\n 84: get { return _view; }\n 85: }\n 86: \n 87: public IModel Model\n 88: {\n 89: get { return _model; }\n 90: }\n 91: \n 92: }\n 93: }\n</code></pre>\n\n<p>So what’s going on here?</p>\n\n<p>Shell gets injected with Presenter. Presenter gets injected with View and Model. Everything here is singletons, but doesn’t have to be.</p>\n\n<p>The difference between our two examples is that the Presenter is getting injected into the shell rather than the View. If the Presenter is creating the View then you can’t just grab the View first (as he was doing), or the Presenter will not get created. Well you can do it, but you end up hacking it to bits. Cleaner is to just inject the Presenter and have it expose an IView. We did this in Prism and it worked quite well.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13163/" ]
Using MEF I want to do the following. I have a WPF Shell. To the shell I want to Import from another DLL a UserControl that is also a View of my MVP triad. The way the MVP triad works, is that in presenter I have a constructor that takes both IModel and IView and wires them up. So, in order for this to work, I need MEF to do the following: 1. Create IView implementation 2. Create IModel implementation 3. Create Presenter and pass IModel and IView to its constructor 4. Import IView implementation into my shell when it gets displayed Instead what it does, is it only creates the type Exporting IView and passes it to the shell, basically skipping steps 2 and 3. Its pretty logical, when you think about it, but how can I tell MEF to also create the whole triad when I ask for a IView. I don't need to reference Presenter nor model anywhere else in my Shell .dll so puting it as an Import as well is not an option (and it would be quite ugly anyway :). I'm using the latest drop of MEF (Preview 2 Refresh). Anyone? **==Update==** I have found a solution and I blogged about it here: [Krzysztof Koźmic's blog - Creating tree of dependencies with MEF](http://kozmic.pl/archive/2008/11/06/creating-tree-of-dependencies-with-mef/ "here") However, I'd be more than happy if someone came up with a better solution.\*\*
Check my answer here. <http://codebetter.com/blogs/glenn.block/archive/2008/11/12/mvp-with-mef.aspx> EDIT: (*Added from the link, to prevent not being flagged as low quality / LOA*) ``` 1: using System.ComponentModel.Composition; 2: using System.Reflection; 3: using Microsoft.VisualStudio.TestTools.UnitTesting; 4: 5: namespace MVPwithMEF 6: { 7: /// <summary> 8: /// Summary description for MVPTriadFixture 9: /// </summary> 10: [TestClass] 11: public class MVPTriadFixture 12: { 13: [TestMethod] 14: public void MVPTriadShouldBeProperlyBuilt() 15: { 16: var catalog = new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly()); 17: var container = new CompositionContainer(catalog.CreateResolver()); 18: var shell = container.GetExportedObject<Shell>(); 19: Assert.IsNotNull(shell); 20: Assert.IsNotNull(shell.Presenter); 21: Assert.IsNotNull(shell.Presenter.View); 22: Assert.IsNotNull(shell.Presenter.Model); 23: } 24: } 25: 26: [Export] 27: public class Shell 28: { 29: private IPresenter _presenter = null; 30: 31: public IPresenter Presenter 32: { 33: get { return _presenter; } 34: } 35: 36: [ImportingConstructor] 37: public Shell(IPresenter presenter) 38: { 39: _presenter = presenter; 40: } 41: } 42: 43: public interface IModel 44: { 45: } 46: 47: [Export(typeof(IModel))] 48: public class Model : IModel 49: { 50: 51: } 52: 53: public interface IView 54: { 55: } 56: 57: [Export(typeof(IView))] 58: public class View : IView 59: { 60: } 61: 62: public interface IPresenter 63: { 64: IView View { get;} 65: IModel Model { get; } 66: } 67: 68: [Export(typeof(IPresenter))] 69: public class Presenter : IPresenter 70: { 71: 72: private IView _view; 73: private IModel _model; 74: 75: [ImportingConstructor] 76: public Presenter(IView view, IModel model) 77: { 78: _view = view; 79: _model = model; 80: } 81: 82: public IView View 83: { 84: get { return _view; } 85: } 86: 87: public IModel Model 88: { 89: get { return _model; } 90: } 91: 92: } 93: } ``` So what’s going on here? Shell gets injected with Presenter. Presenter gets injected with View and Model. Everything here is singletons, but doesn’t have to be. The difference between our two examples is that the Presenter is getting injected into the shell rather than the View. If the Presenter is creating the View then you can’t just grab the View first (as he was doing), or the Presenter will not get created. Well you can do it, but you end up hacking it to bits. Cleaner is to just inject the Presenter and have it expose an IView. We did this in Prism and it worked quite well.
266,570
<p>Is there any performance difference between the for loops on a primitive array? </p> <p>Assume:</p> <pre><code>double[] doubleArray = new double[300000]; for (double var: doubleArray) someComplexCalculation(var); </code></pre> <p>or :</p> <pre><code>for ( int i = 0, y = doubleArray.length; i &lt; y; i++) someComplexCalculation(doubleArray[i]); </code></pre> <p><strong>Test result</strong></p> <p>I actually profiled it:</p> <pre><code>Total timeused for modern loop= 13269ms Total timeused for old loop = 15370ms </code></pre> <p>So the modern loop actually runs faster, at least on my Mac OSX JVM 1.5. </p>
[ { "answer_id": 266572, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 2, "selected": false, "text": "<p>Why not measure it yourself?</p>\n\n<p>This sounds a bit harsh, but this kind of questions are very easy to verify yourself.</p>\n\n<p>Just create the array and execute each loop 1000 or more times, and measure the amount of time. Repeat several times to eliminate glitches.</p>\n" }, { "answer_id": 266591, "author": "Paulo Guedes", "author_id": 33857, "author_profile": "https://Stackoverflow.com/users/33857", "pm_score": 2, "selected": false, "text": "<p>There is no difference. Java will transform the enhanced for into the normal for loop. The enhanced for is just a \"syntax sugar\". The bytecode generated is the same for both loops.</p>\n" }, { "answer_id": 266662, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 3, "selected": false, "text": "<p>My opinion is that you don't know and shouldn't guess. Trying to outsmart compilers these days is fruitless. </p>\n\n<p>There have been times people learned \"Patterns\" that seemed to optimize some operation, but in the next version of Java those patterns were actually slower.</p>\n\n<p>Always write it as clear as you possibly can and don't worry about optimization until you actually have some user spec in your hand and are failing to meet some requirement, and even then be very careful to run before and after tests to ensure that your \"fix\" actually improved it enough to make that requirement pass.</p>\n\n<p>The compiler can do some amazing things that would really blow your socks off, and even if you make some test that iterates over some large range, it may perform completely differently if you have a smaller range or change what happens inside the loop.</p>\n\n<p>Just in time compiling means it can occasionally outperform C, and there is no reason it can't outperform static assembly language in some cases (assembly can't determine beforehand that a call isn't required, Java can at times do just that.</p>\n\n<p>To sum it up: the most value you can put into your code is to write it to be readable.</p>\n" }, { "answer_id": 266727, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 4, "selected": true, "text": "<p>Your hand-written, \"old\" form executes fewer instructions, and may be faster, although you'd have to profile it under a given JIT compiler to know for sure. The \"new\" form is definitely <strong>not</strong> faster.</p>\n\n<p>If you look at the disassembled code (compiled by Sun's JDK 1.5), you'll see that the \"new\" form is equivalent to the following code:</p>\n\n<pre><code>1: double[] tmp = doubleArray;\n2: for (int i = 0, y = tmp.length; i &lt; y; i++) {\n3: double var = tmp[i];\n4: someComplexCalculation(var);\n5: }\n</code></pre>\n\n<p>So, you can see that more local variables are used. The assignment of <code>doubleArray</code> to <code>tmp</code> at line 1 is \"extra\", but it doesn't occur in the loop, and probably can't be measured. The assignment to <code>var</code> at line 3 is also extra. If there is a difference in performance, this would be responsible.</p>\n\n<p>Line 1 might seem unnecessary, but it's boilerplate to cache the result if the array is computed by a method before entering the loop.</p>\n\n<p>That said, I would use the new form, unless you need to do something with the index variable. Any performance difference is likely to be optimized away by the JIT compiler at runtime, and the new form is more clear. If you continue to do it \"by hand\", you may miss out on future optimizations. Generally, a good compiler can optimize \"stupid\" code well, but stumbles on \"smart\" code.</p>\n" }, { "answer_id": 269296, "author": "Paulo Guedes", "author_id": 33857, "author_profile": "https://Stackoverflow.com/users/33857", "pm_score": 1, "selected": false, "text": "<p>I got very curious about your question, even after my previous answer. So I decided to check it myself too. I wrote this small piece of code (please ignore math correctness about checking if a number is prime ;-)):</p>\n\n<pre><code>public class TestEnhancedFor {\n\n public static void main(String args[]){\n new TestEnhancedFor();\n }\n\n public TestEnhancedFor(){\n int numberOfItems = 100000;\n double[] items = getArrayOfItems(numberOfItems);\n int repetitions = 0;\n long start, end;\n\n do {\n start = System.currentTimeMillis();\n doNormalFor(items);\n end = System.currentTimeMillis();\n System.out.printf(\"Normal For. Repetition %d: %d\\n\", \n repetitions, end-start);\n\n start = System.currentTimeMillis();\n doEnhancedFor(items);\n end = System.currentTimeMillis();\n System.out.printf(\"Enhanced For. Repetition %d: %d\\n\\n\", \n repetitions, end-start);\n\n } while (++repetitions &lt; 5);\n }\n\n private double[] getArrayOfItems(int numberOfItems){\n double[] items = new double[numberOfItems];\n for (int i=0; i &lt; numberOfItems; i++)\n items[i] = i;\n return items;\n }\n\n private void doSomeComplexCalculation(double item){\n // check if item is prime number\n for (int i = 3; i &lt; item / 2; i+=2){\n if ((item / i) == (int) (item / i)) break;\n }\n }\n\n private void doNormalFor(double[] items){\n for (int i = 0; i &lt; items.length; i++)\n doSomeComplexCalculation(items[i]);\n }\n\n private void doEnhancedFor(double[] items){\n for (double item : items)\n doSomeComplexCalculation(item);\n }\n\n}\n</code></pre>\n\n<p>Running the app gave the following results for me:</p>\n\n<blockquote>\n <p>Normal For. Repetition 0: 5594\n Enhanced For. Repetition 0: 5594</p>\n \n <p>Normal For. Repetition 1: 5531\n Enhanced For. Repetition 1: 5547</p>\n \n <p>Normal For. Repetition 2: 5532\n Enhanced For. Repetition 2: 5578</p>\n \n <p>Normal For. Repetition 3: 5531\n Enhanced For. Repetition 3: 5531</p>\n \n <p>Normal For. Repetition 4: 5547\n Enhanced For. Repetition 4: 5532</p>\n</blockquote>\n\n<p>As we can see, the variation among the results is very small, and sometimes the normal loop runs faster, sometimes the enhanced loop is faster. Since there are other apps open in my computer, I find it normal. Also, only the first execution is slower than the others -- I believe this has to do with JIT optimizations.</p>\n\n<p>Average times (excluding the first repetition) are 5535,25ms for the normal loop and 5547ms for the enhanced loop. But we can see that the best running times for both loops is the same (5531ms), so I think we can come to the conclusion that both loops have the same performance -- and the variations of time elapsed are due to other applications (even the OS) of the machine.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9774/" ]
Is there any performance difference between the for loops on a primitive array? Assume: ``` double[] doubleArray = new double[300000]; for (double var: doubleArray) someComplexCalculation(var); ``` or : ``` for ( int i = 0, y = doubleArray.length; i < y; i++) someComplexCalculation(doubleArray[i]); ``` **Test result** I actually profiled it: ``` Total timeused for modern loop= 13269ms Total timeused for old loop = 15370ms ``` So the modern loop actually runs faster, at least on my Mac OSX JVM 1.5.
Your hand-written, "old" form executes fewer instructions, and may be faster, although you'd have to profile it under a given JIT compiler to know for sure. The "new" form is definitely **not** faster. If you look at the disassembled code (compiled by Sun's JDK 1.5), you'll see that the "new" form is equivalent to the following code: ``` 1: double[] tmp = doubleArray; 2: for (int i = 0, y = tmp.length; i < y; i++) { 3: double var = tmp[i]; 4: someComplexCalculation(var); 5: } ``` So, you can see that more local variables are used. The assignment of `doubleArray` to `tmp` at line 1 is "extra", but it doesn't occur in the loop, and probably can't be measured. The assignment to `var` at line 3 is also extra. If there is a difference in performance, this would be responsible. Line 1 might seem unnecessary, but it's boilerplate to cache the result if the array is computed by a method before entering the loop. That said, I would use the new form, unless you need to do something with the index variable. Any performance difference is likely to be optimized away by the JIT compiler at runtime, and the new form is more clear. If you continue to do it "by hand", you may miss out on future optimizations. Generally, a good compiler can optimize "stupid" code well, but stumbles on "smart" code.
266,586
<p>I am coding in ColdFusion, but trying to stay in cfscript, so I have a function that allows me to pass in a query to run it with <code> &lt;cfquery blah > #query# &lt;/cfquery> </code></p> <p>Somehow though, when I construct my queries with <code>sql = "SELECT * FROM a WHERE b='#c#'"</code> and pass it in, ColdFusion has replaced the single quotes with 2 single quotes. so it becomes <code> WHERE b=''c''</code> in the final query.</p> <p>I have tried creating the strings a lot of different ways, but I cannot get it to leave just one quote. Even doing a string replace has no effect. </p> <p>Any idea why this is happening? It is ruining my hopes of living in cfscript for the duration of this project</p>
[ { "answer_id": 266680, "author": "ale", "author_id": 21960, "author_profile": "https://Stackoverflow.com/users/21960", "pm_score": 4, "selected": false, "text": "<p>ColdFusion, by design, escapes single quotes when interpolating variables within <code>&lt;cfquery&gt;</code> tags.</p>\n\n<p>To do what you want, you need to use the <a href=\"http://livedocs.adobe.com/coldfusion/8/htmldocs/functions_m-r_14.html\" rel=\"noreferrer\"><code>PreserveSingleQuotes()</code></a> function.</p>\n\n<pre><code>&lt;cfquery ...&gt;#PreserveSingleQuotes(query)#&lt;/cfquery&gt;\n</code></pre>\n\n<p>This doesn't address, however, the danger of SQL injection to which you are exposing yourself.</p>\n\n<p>Using <a href=\"http://livedocs.adobe.com/coldfusion/8/htmldocs/Tags_p-q_18.html\" rel=\"noreferrer\"><code>&lt;cfqueryparam&gt;</code></a> also allows your database to cache the query, which in most cases will improve performance.</p>\n\n<p>It might be helpful to read <a href=\"http://www.adobe.com/devnet/coldfusion/articles/ben_forta_faster.html\" rel=\"noreferrer\">an old Ben Forta column</a> and <a href=\"http://www.codersrevolution.com/index.cfm/2008/7/26/cfqueryparam-its-not-just-for-security-also-when-NOT-to-use-it\" rel=\"noreferrer\">a recent post by Brad Wood</a> for more information about the benefits of using <code>&lt;cfqueryparam&gt;</code>.</p>\n" }, { "answer_id": 266787, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": false, "text": "<p>ColdFusion automatically escapes single quotes quotes in <code>&lt;cfquery&gt;</code> tags when you use the following syntax:</p>\n\n<pre><code>SELECT * FROM TABLE WHERE Foo='#Foo#'\n</code></pre>\n\n<p>In case you would want to preserve single quotes in <code>#Foo#</code> you must call <code>#PreserveSingleQuotes(Foo)#</code>.</p>\n\n<p>Be aware the the automatic escaping works only for variable values, not for function results.</p>\n\n<pre><code>SELECT * FROM TABLE WHERE Foo='#LCase(Foo)#' /* Single quotes are retained! */\n</code></pre>\n\n<p>In that light, the function <code>PreserveSingleQuotes()</code> (see <a href=\"http://livedocs.adobe.com/coldfusion/6.1/htmldocs/functa53.htm\" rel=\"nofollow noreferrer\">Adobe LiveDocs</a>) is not much more than a \"null operation\" on the value - turning it into a function result to bypass auto-escaping.</p>\n" }, { "answer_id": 267093, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 3, "selected": false, "text": "<p>The answer to your question, as others have said, is using <code>preserveSingleQuotes(...)</code></p>\n\n<p>However, the <em>solution</em> you actually want, is <em>not</em> to dynamically build your queries in this fashion. It's Bad Bad Bad.</p>\n\n<p>Put your SQL inside the cfquery tags, with any ifs/switches/etc as appropriate, and ensure <strong>all</strong> CF variables use the <code>cfqueryparam</code> tag.</p>\n\n<p>(Note, if you use variables in the ORDER BY clause, you'll need to manually escape any variables; cfqueryparam can't be used in ORDER BY clauses)</p>\n" }, { "answer_id": 411959, "author": "Isaac Dealey", "author_id": 50355, "author_profile": "https://Stackoverflow.com/users/50355", "pm_score": 0, "selected": false, "text": "<p>I voted up Dave's answer since I thought he did a good job. </p>\n\n<p>I'd like to add however that there are also several different tools designed for ColdFusion that can simplify a lot of the common SQL tasks you're likely to perform. There's a very light-weight tool called <a href=\"http://datamgr.riaforge.org/\" rel=\"nofollow noreferrer\">DataMgr</a> written by Steve Bryant, as well as <a href=\"http://www.transfer-orm.com\" rel=\"nofollow noreferrer\">Transfer</a> from Mark Mandel, <a href=\"http://www.reactorframework.com\" rel=\"nofollow noreferrer\">Reactor</a> which was originally created by Doug Hughes and one I developed called <a href=\"http://www.datafaucet.com\" rel=\"nofollow noreferrer\">DataFaucet</a>. Each of these has its own strengths and weaknesses. Personally I think you're apt to consider DataFaucet to be the one that will give you the best ability to stay in cfscript, with a variety of syntaxes for building different kinds of queries. </p>\n\n<p>Here are a few examples: </p>\n\n<pre><code>qry = datasource.select_avg_price_as_avgprice_from_products(); //(requires CF8)\n\nqry = datasource.select(\"avg(price) as avgprice\",\"products\"); \n\nqry = datasource.getSelect(\"avg(price) as avgprice\",\"products\").filter(\"categoryid\",url.categoryid).execute();\n\nqry = datasource.getSelect(table=\"products\",orderby=\"productname\").filter(\"categoryid\",url.categoryid).execute();\n</code></pre>\n\n<p><br>\nThe framework ensures that cfqueryparam is always used with these filter statements to prevent sql-injection attacks, and there are similar syntaxes for insert, update and delete statements. (There are a couple of <a href=\"http://datafaucet.wikispaces.com/SQL+Injection\" rel=\"nofollow noreferrer\">simple rules to avoid sql-injection</a>.) </p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am coding in ColdFusion, but trying to stay in cfscript, so I have a function that allows me to pass in a query to run it with `<cfquery blah > #query# </cfquery>` Somehow though, when I construct my queries with `sql = "SELECT * FROM a WHERE b='#c#'"` and pass it in, ColdFusion has replaced the single quotes with 2 single quotes. so it becomes `WHERE b=''c''` in the final query. I have tried creating the strings a lot of different ways, but I cannot get it to leave just one quote. Even doing a string replace has no effect. Any idea why this is happening? It is ruining my hopes of living in cfscript for the duration of this project
ColdFusion, by design, escapes single quotes when interpolating variables within `<cfquery>` tags. To do what you want, you need to use the [`PreserveSingleQuotes()`](http://livedocs.adobe.com/coldfusion/8/htmldocs/functions_m-r_14.html) function. ``` <cfquery ...>#PreserveSingleQuotes(query)#</cfquery> ``` This doesn't address, however, the danger of SQL injection to which you are exposing yourself. Using [`<cfqueryparam>`](http://livedocs.adobe.com/coldfusion/8/htmldocs/Tags_p-q_18.html) also allows your database to cache the query, which in most cases will improve performance. It might be helpful to read [an old Ben Forta column](http://www.adobe.com/devnet/coldfusion/articles/ben_forta_faster.html) and [a recent post by Brad Wood](http://www.codersrevolution.com/index.cfm/2008/7/26/cfqueryparam-its-not-just-for-security-also-when-NOT-to-use-it) for more information about the benefits of using `<cfqueryparam>`.
266,601
<p>My spring-context file is shown below.</p> <pre><code>&lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"&gt; &lt;bean id="cfaBeanFactory" class="org.springframework.context.support.ClassPathXmlApplicationContext"&gt; &lt;constructor-arg value="classpath:cfa-spring-core.xml" /&gt; &lt;/bean&gt; &lt;/beans&gt; </code></pre> <p>When I try to run my application, I get the following error:</p> <pre><code>Caused by: org.springframework.beans.factory.access.BootstrapException: Unable to initialize group definition. Group resource name [classpath*:cfa-spring-context.xml], factory key [cfaBeanFactory]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Line 16 in XML document from URL [file:/C:/.../cfa-spring-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException: Document root element "beans", must match DOCTYPE root "null". at org.springframework.beans.factory.access.SingletonBeanFactoryLocator.useBeanFactory(SingletonBeanFactoryLocator.java:389) ... 56 more Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Line 16 in XML document from URL [file:/C:/.../cfa-spring-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException: Document root element "beans", must match DOCTYPE root "null". at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:169) ... 59 more Caused by: org.xml.sax.SAXParseException: Document root element "beans", must match DOCTYPE root "null". at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source) at org.apache.xerces.util.ErrorHandlerWrapper.error(Unknown Source) </code></pre> <p>Can someone tell me what I'm doing wrong?</p>
[ { "answer_id": 266627, "author": "Mike Pone", "author_id": 16404, "author_profile": "https://Stackoverflow.com/users/16404", "pm_score": 0, "selected": false, "text": "<p>you are not closing the <code>&lt;beans&gt;</code> tag. Add <code>&lt;/beans&gt;</code> to the end of your config file.</p>\n" }, { "answer_id": 266628, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 0, "selected": false, "text": "<p>Looking at your stacktrace:</p>\n\n<pre>\n Line 16 in XML document from URL <b>[file:/C:/.../cfa-spring-context.xml]</b> is invalid;\n nested exception is org.xml.sax.SAXParseException: Document root element \"beans\", \n must match DOCTYPE root \"null\".\n</pre>\n\n<p>You appear to have an error in the <strong>cfa-spring-core.xml</strong> file, rather than the spring file you included in your posting.</p>\n" }, { "answer_id": 266675, "author": "Elie", "author_id": 23249, "author_profile": "https://Stackoverflow.com/users/23249", "pm_score": 4, "selected": true, "text": "<p>Turns out this is because I'm using Hibernate 3 with Spring 1.x which means the DTDs are wrong. Updated the Spring JAR file in the project and that fixed the problem.</p>\n" }, { "answer_id": 1982444, "author": "Simion", "author_id": 241179, "author_profile": "https://Stackoverflow.com/users/241179", "pm_score": 1, "selected": false, "text": "<p>You may be using old version of spring.jar. I got this and it got solved when I used the latest spring.jar</p>\n" }, { "answer_id": 3171021, "author": "joy", "author_id": 382620, "author_profile": "https://Stackoverflow.com/users/382620", "pm_score": 1, "selected": false, "text": "<p>Update your spring.jar with latest version</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23249/" ]
My spring-context file is shown below. ``` <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> <bean id="cfaBeanFactory" class="org.springframework.context.support.ClassPathXmlApplicationContext"> <constructor-arg value="classpath:cfa-spring-core.xml" /> </bean> </beans> ``` When I try to run my application, I get the following error: ``` Caused by: org.springframework.beans.factory.access.BootstrapException: Unable to initialize group definition. Group resource name [classpath*:cfa-spring-context.xml], factory key [cfaBeanFactory]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Line 16 in XML document from URL [file:/C:/.../cfa-spring-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException: Document root element "beans", must match DOCTYPE root "null". at org.springframework.beans.factory.access.SingletonBeanFactoryLocator.useBeanFactory(SingletonBeanFactoryLocator.java:389) ... 56 more Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Line 16 in XML document from URL [file:/C:/.../cfa-spring-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException: Document root element "beans", must match DOCTYPE root "null". at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:169) ... 59 more Caused by: org.xml.sax.SAXParseException: Document root element "beans", must match DOCTYPE root "null". at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source) at org.apache.xerces.util.ErrorHandlerWrapper.error(Unknown Source) ``` Can someone tell me what I'm doing wrong?
Turns out this is because I'm using Hibernate 3 with Spring 1.x which means the DTDs are wrong. Updated the Spring JAR file in the project and that fixed the problem.
266,639
<p>What is the best tool / practice to enable browser history for Flash (or AJAX) websites? I guess the established practice is to set and read a hash-addition to the URL like</p> <pre><code>http://example.com/#id=1 </code></pre> <p>I am aware of the Flex History Manager, but was wondering if there are any good alternatives to consider. Would also be interested in a general AJAX solution or best practice.</p>
[ { "answer_id": 266654, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 2, "selected": false, "text": "<p>For AJAX, something like <a href=\"http://code.google.com/p/reallysimplehistory/\" rel=\"nofollow noreferrer\">Really Simple History</a> is great.</p>\n" }, { "answer_id": 266742, "author": "grapefrukt", "author_id": 914, "author_profile": "https://Stackoverflow.com/users/914", "pm_score": 3, "selected": true, "text": "<p>I've used <a href=\"http://www.asual.com/swfaddress/\" rel=\"nofollow noreferrer\">swfadress</a> for some small stuff.</p>\n" }, { "answer_id": 267329, "author": "Glenn", "author_id": 11814, "author_profile": "https://Stackoverflow.com/users/11814", "pm_score": 0, "selected": false, "text": "<p>This will seem a bit roundabout, but I'm currently using the dojo framework for that. There's a dojo.back that was very useful when my UI was mostly JS/HTML. Now that I've gone to flex for more power, fluid animations, and browser stability, the only thing I've need to keep using has been the back URL. </p>\n\n<p>FlexBuilder seemed to have it's own browser history in default projects. </p>\n\n<p>Also, the Flex 3 Cookbook has a recipe for using mx.managers.HistoryManager to create your own custom history management. I have plans to give this a try someday to remove our dependence on the dojo.back, but haven't had time yet. </p>\n" }, { "answer_id": 268983, "author": "RickDT", "author_id": 5421, "author_profile": "https://Stackoverflow.com/users/5421", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.asual.com/swfaddress/\" rel=\"nofollow noreferrer\">SWFAddress</a> has been widely used and tested. It makes it almost trivial (given you plan ahead) to handle deeplinking in Flash. It provides a JS and AS library that work together and make the whole process pretty foolproof. You'd want to look at something like RSH for AJAX.</p>\n" }, { "answer_id": 405704, "author": "nakajima", "author_id": 39589, "author_profile": "https://Stackoverflow.com/users/39589", "pm_score": 0, "selected": false, "text": "<p>I've rolled my own solutions that were ultra-simple like this:</p>\n\n<pre><code>(function() {\n var oldHash, newHash;\n\n function checkHash() {\n // Grab the hash\n newHash = document.location.hash;\n\n // Check to see if it changed\n if (oldHash != newHash) {\n\n // Trigger a custom event if it changed,\n // passing the old and new values as\n // metadata on the event.\n $(document).trigger('hash.changed', {\n old: oldHash,\n new: newHash\n });\n\n // Update the oldHash for the next check\n oldHash = newHash;\n }\n }\n\n // Poll the hash every 10 milliseconds.\n // You might need to alter this time based\n // on performance\n window.setInterval(checkHash, 10);\n\n})(jQuery);\n</code></pre>\n\n<p>Then you just need to have event handlers for the 'hash.changed' event to respond accordingly based on what the new value is. The approach works will in super simple cases.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23069/" ]
What is the best tool / practice to enable browser history for Flash (or AJAX) websites? I guess the established practice is to set and read a hash-addition to the URL like ``` http://example.com/#id=1 ``` I am aware of the Flex History Manager, but was wondering if there are any good alternatives to consider. Would also be interested in a general AJAX solution or best practice.
I've used [swfadress](http://www.asual.com/swfaddress/) for some small stuff.
266,648
<p>How can I check if a file uploaded by a user is a real jpg file in Python (Google App Engine)?</p> <p>This is how far I got by now:</p> <p>Script receives image via HTML Form Post and is processed by the following code</p> <pre><code>... incomming_image = self.request.get("img") image = db.Blob(incomming_image) ... </code></pre> <p>I found mimetypes.guess_type, but it does not work for me.</p>
[ { "answer_id": 266731, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 6, "selected": true, "text": "<p>If you need more than looking at extension, one way would be to read the JPEG header, and check that it matches valid data. The format for this is:</p>\n\n<pre><code>Start Marker | JFIF Marker | Header Length | Identifier\n0xff, 0xd8 | 0xff, 0xe0 | 2-bytes | \"JFIF\\0\"\n</code></pre>\n\n<p>so a quick recogniser would be:</p>\n\n<pre><code>def is_jpg(filename):\n data = open(filename,'rb').read(11)\n if data[:4] != '\\xff\\xd8\\xff\\xe0': return False\n if data[6:] != 'JFIF\\0': return False\n return True\n</code></pre>\n\n<p>However this won't catch any bad data in the body. If you want a more robust check, you could try loading it with <a href=\"http://www.pythonware.com/products/pil/\" rel=\"noreferrer\">PIL</a>. eg:</p>\n\n<pre><code>from PIL import Image\ndef is_jpg(filename):\n try:\n i=Image.open(filename)\n return i.format =='JPEG'\n except IOError:\n return False\n</code></pre>\n" }, { "answer_id": 266774, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 0, "selected": false, "text": "<p>Use <a href=\"http://www.pythonware.com/products/pil/\" rel=\"nofollow noreferrer\">PIL</a>. If it can open the file, it's an image.</p>\n\n<p>From the tutorial...</p>\n\n<pre><code>&gt;&gt;&gt; import Image\n&gt;&gt;&gt; im = Image.open(\"lena.ppm\")\n&gt;&gt;&gt; print im.format, im.size, im.mode\n</code></pre>\n" }, { "answer_id": 1040027, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>No need to use and install the PIL lybrary for this, there is the imghdr standard module exactly fited for this sort of usage.</p>\n\n<p>See <a href=\"http://docs.python.org/library/imghdr.html\" rel=\"noreferrer\">http://docs.python.org/library/imghdr.html</a></p>\n\n<pre><code>import imghdr\n\nimage_type = imghdr.what(filename)\nif not image_type:\n print \"error\"\nelse:\n print image_type\n</code></pre>\n\n<p>As you have an image from a stream you may use the stream option probably like this :</p>\n\n<pre><code>image_type = imghdr.what(filename, incomming_image)\n</code></pre>\n\n<hr>\n\n<p>Actualy this works for me in Pylons (even if i have not finished everything) :\nin the Mako template :</p>\n\n<pre><code>${h.form(h.url_for(action=\"save_image\"), multipart=True)}\nUpload file: ${h.file(\"upload_file\")} &lt;br /&gt;\n${h.submit(\"Submit\", \"Submit\")}\n${h.end_form()}\n</code></pre>\n\n<p>in the upload controler :</p>\n\n<pre><code>def save_image(self):\n upload_file = request.POST[\"upload_file\"]\n image_type = imghdr.what(upload_file.filename, upload_file.value)\n if not image_type:\n return \"error\"\n else:\n return image_type\n</code></pre>\n" }, { "answer_id": 5717194, "author": "Jabba", "author_id": 232485, "author_profile": "https://Stackoverflow.com/users/232485", "pm_score": 1, "selected": false, "text": "<p>A more general solution is to use the Python binding to the Unix \"file\" command. For this, install the package python-magic. Example:</p>\n\n<pre><code>import magic\n\nms = magic.open(magic.MAGIC_NONE)\nms.load()\ntype = ms.file(\"/path/to/some/file\")\nprint type\n\nf = file(\"/path/to/some/file\", \"r\")\nbuffer = f.read(4096)\nf.close()\n\ntype = ms.buffer(buffer)\nprint type\n\nms.close()\n</code></pre>\n" }, { "answer_id": 28907255, "author": "Christian Papathanasiou", "author_id": 4642505, "author_profile": "https://Stackoverflow.com/users/4642505", "pm_score": 0, "selected": false, "text": "<p>The last byte of the JPEG file specification seems to vary beyond just e0. Capturing the first three is 'good enough' of a heuristic signature to reliably identify whether the file is a jpeg. Please see below modified proposal: </p>\n\n<pre><code>def is_jpg(filename):\n data = open(\"uploads/\" + filename,'rb').read(11)\n if (data[:3] == \"\\xff\\xd8\\xff\"):\n return True\n elif (data[6:] == 'JFIF\\0'): \n return True\n else:\n return False\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26763/" ]
How can I check if a file uploaded by a user is a real jpg file in Python (Google App Engine)? This is how far I got by now: Script receives image via HTML Form Post and is processed by the following code ``` ... incomming_image = self.request.get("img") image = db.Blob(incomming_image) ... ``` I found mimetypes.guess\_type, but it does not work for me.
If you need more than looking at extension, one way would be to read the JPEG header, and check that it matches valid data. The format for this is: ``` Start Marker | JFIF Marker | Header Length | Identifier 0xff, 0xd8 | 0xff, 0xe0 | 2-bytes | "JFIF\0" ``` so a quick recogniser would be: ``` def is_jpg(filename): data = open(filename,'rb').read(11) if data[:4] != '\xff\xd8\xff\xe0': return False if data[6:] != 'JFIF\0': return False return True ``` However this won't catch any bad data in the body. If you want a more robust check, you could try loading it with [PIL](http://www.pythonware.com/products/pil/). eg: ``` from PIL import Image def is_jpg(filename): try: i=Image.open(filename) return i.format =='JPEG' except IOError: return False ```
266,652
<p>We are trying to build a Crystal Report that sends control characters directly to the printer, without going through the (buggy) Windows driver for that printer. Does anyone know a way to do this from within a Crystal Report? </p> <p>The specific control character we are trying to send is CHR(2). However when we put that in a Crystal Report, and print to a Generic Text Only printer, it is converting the character to a period on output. The character appears as a box in Crystal's preview, so I suspect it is the Windows driver, rather than Crystal, that is the problem.</p> <p>The device is a Datamax printer. We do have drivers for it, but are encountering various problems - the infrastructure group knows more about the problems than I do, I don't feel I have enough information to try and ask about the specific problem. It is some combination of the interplay of Crystal Reports, Citrix, our market-specific ERP package, and automatically selecting label printers for the appropriate label size based on user at the time the report is run.</p>
[ { "answer_id": 266731, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 6, "selected": true, "text": "<p>If you need more than looking at extension, one way would be to read the JPEG header, and check that it matches valid data. The format for this is:</p>\n\n<pre><code>Start Marker | JFIF Marker | Header Length | Identifier\n0xff, 0xd8 | 0xff, 0xe0 | 2-bytes | \"JFIF\\0\"\n</code></pre>\n\n<p>so a quick recogniser would be:</p>\n\n<pre><code>def is_jpg(filename):\n data = open(filename,'rb').read(11)\n if data[:4] != '\\xff\\xd8\\xff\\xe0': return False\n if data[6:] != 'JFIF\\0': return False\n return True\n</code></pre>\n\n<p>However this won't catch any bad data in the body. If you want a more robust check, you could try loading it with <a href=\"http://www.pythonware.com/products/pil/\" rel=\"noreferrer\">PIL</a>. eg:</p>\n\n<pre><code>from PIL import Image\ndef is_jpg(filename):\n try:\n i=Image.open(filename)\n return i.format =='JPEG'\n except IOError:\n return False\n</code></pre>\n" }, { "answer_id": 266774, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 0, "selected": false, "text": "<p>Use <a href=\"http://www.pythonware.com/products/pil/\" rel=\"nofollow noreferrer\">PIL</a>. If it can open the file, it's an image.</p>\n\n<p>From the tutorial...</p>\n\n<pre><code>&gt;&gt;&gt; import Image\n&gt;&gt;&gt; im = Image.open(\"lena.ppm\")\n&gt;&gt;&gt; print im.format, im.size, im.mode\n</code></pre>\n" }, { "answer_id": 1040027, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>No need to use and install the PIL lybrary for this, there is the imghdr standard module exactly fited for this sort of usage.</p>\n\n<p>See <a href=\"http://docs.python.org/library/imghdr.html\" rel=\"noreferrer\">http://docs.python.org/library/imghdr.html</a></p>\n\n<pre><code>import imghdr\n\nimage_type = imghdr.what(filename)\nif not image_type:\n print \"error\"\nelse:\n print image_type\n</code></pre>\n\n<p>As you have an image from a stream you may use the stream option probably like this :</p>\n\n<pre><code>image_type = imghdr.what(filename, incomming_image)\n</code></pre>\n\n<hr>\n\n<p>Actualy this works for me in Pylons (even if i have not finished everything) :\nin the Mako template :</p>\n\n<pre><code>${h.form(h.url_for(action=\"save_image\"), multipart=True)}\nUpload file: ${h.file(\"upload_file\")} &lt;br /&gt;\n${h.submit(\"Submit\", \"Submit\")}\n${h.end_form()}\n</code></pre>\n\n<p>in the upload controler :</p>\n\n<pre><code>def save_image(self):\n upload_file = request.POST[\"upload_file\"]\n image_type = imghdr.what(upload_file.filename, upload_file.value)\n if not image_type:\n return \"error\"\n else:\n return image_type\n</code></pre>\n" }, { "answer_id": 5717194, "author": "Jabba", "author_id": 232485, "author_profile": "https://Stackoverflow.com/users/232485", "pm_score": 1, "selected": false, "text": "<p>A more general solution is to use the Python binding to the Unix \"file\" command. For this, install the package python-magic. Example:</p>\n\n<pre><code>import magic\n\nms = magic.open(magic.MAGIC_NONE)\nms.load()\ntype = ms.file(\"/path/to/some/file\")\nprint type\n\nf = file(\"/path/to/some/file\", \"r\")\nbuffer = f.read(4096)\nf.close()\n\ntype = ms.buffer(buffer)\nprint type\n\nms.close()\n</code></pre>\n" }, { "answer_id": 28907255, "author": "Christian Papathanasiou", "author_id": 4642505, "author_profile": "https://Stackoverflow.com/users/4642505", "pm_score": 0, "selected": false, "text": "<p>The last byte of the JPEG file specification seems to vary beyond just e0. Capturing the first three is 'good enough' of a heuristic signature to reliably identify whether the file is a jpeg. Please see below modified proposal: </p>\n\n<pre><code>def is_jpg(filename):\n data = open(\"uploads/\" + filename,'rb').read(11)\n if (data[:3] == \"\\xff\\xd8\\xff\"):\n return True\n elif (data[6:] == 'JFIF\\0'): \n return True\n else:\n return False\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20068/" ]
We are trying to build a Crystal Report that sends control characters directly to the printer, without going through the (buggy) Windows driver for that printer. Does anyone know a way to do this from within a Crystal Report? The specific control character we are trying to send is CHR(2). However when we put that in a Crystal Report, and print to a Generic Text Only printer, it is converting the character to a period on output. The character appears as a box in Crystal's preview, so I suspect it is the Windows driver, rather than Crystal, that is the problem. The device is a Datamax printer. We do have drivers for it, but are encountering various problems - the infrastructure group knows more about the problems than I do, I don't feel I have enough information to try and ask about the specific problem. It is some combination of the interplay of Crystal Reports, Citrix, our market-specific ERP package, and automatically selecting label printers for the appropriate label size based on user at the time the report is run.
If you need more than looking at extension, one way would be to read the JPEG header, and check that it matches valid data. The format for this is: ``` Start Marker | JFIF Marker | Header Length | Identifier 0xff, 0xd8 | 0xff, 0xe0 | 2-bytes | "JFIF\0" ``` so a quick recogniser would be: ``` def is_jpg(filename): data = open(filename,'rb').read(11) if data[:4] != '\xff\xd8\xff\xe0': return False if data[6:] != 'JFIF\0': return False return True ``` However this won't catch any bad data in the body. If you want a more robust check, you could try loading it with [PIL](http://www.pythonware.com/products/pil/). eg: ``` from PIL import Image def is_jpg(filename): try: i=Image.open(filename) return i.format =='JPEG' except IOError: return False ```
266,664
<p>What's the easiest method people have found to monitor memcached on Windows? One method I've tried, which works decently:</p> <p>telnet into the memcached port (11211) and enter the "stats" command. You'll get back a listing like this:</p> <pre><code>stats STAT pid 2816 STAT uptime 791 STAT time 1225918895 STAT version 1.2.1 STAT pointer_size 32 STAT curr_items 10 STAT total_items 10 STAT bytes 122931 STAT curr_connections 1 STAT total_connections 5 STAT connection_structures 4 STAT cmd_get 20 STAT cmd_set 10 STAT get_hits 0 STAT get_misses 20 STAT bytes_read 122986 STAT bytes_written 187 STAT limit_maxbytes 1073741824 </code></pre> <p>Is there an easier way?</p>
[ { "answer_id": 266678, "author": "dove", "author_id": 30913, "author_profile": "https://Stackoverflow.com/users/30913", "pm_score": 0, "selected": false, "text": "<p>I've worked with memcached on windows and found this to be one of the main drawbacks. It's surprising better tools have not appeared but I guess it's a case of not asking for whom the bell tolls...</p>\n" }, { "answer_id": 266722, "author": "Alister Bulman", "author_id": 6216, "author_profile": "https://Stackoverflow.com/users/6216", "pm_score": 3, "selected": true, "text": "<p>The PHP Memcached module also includes <a href=\"http://svn.php.net/viewvc/pecl/apc/trunk/apc.php?view=markup\" rel=\"nofollow noreferrer\">a script</a> that will display the stats in summary, and also graph form, as well as being able to view individual cached items. If you are already using PHP &amp; memcache on windows, it's an almost drop-in solution.</p>\n" }, { "answer_id": 5094999, "author": "prasanna jayapalan", "author_id": 630763, "author_profile": "https://Stackoverflow.com/users/630763", "pm_score": 1, "selected": false, "text": "<p>Checkout <a href=\"http://www.evidentsoftware.com/\" rel=\"nofollow\">Evident Software's</a> ClearStone for <a href=\"http://support.evidentsoftware.com/entries/444446-monotoring-memcached-using-clearstone-s-rest-based-open-data-interface\" rel=\"nofollow\">memcached</a></p>\n" }, { "answer_id": 8737483, "author": "Tilman", "author_id": 358936, "author_profile": "https://Stackoverflow.com/users/358936", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://code.google.com/p/phpmemcacheadmin/\" rel=\"nofollow\">phpmemcacheadmin</a> is another free PHP app to monitor your memcached cluster, that I find a lot nicer than the script that comes with the PHP extension.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109/" ]
What's the easiest method people have found to monitor memcached on Windows? One method I've tried, which works decently: telnet into the memcached port (11211) and enter the "stats" command. You'll get back a listing like this: ``` stats STAT pid 2816 STAT uptime 791 STAT time 1225918895 STAT version 1.2.1 STAT pointer_size 32 STAT curr_items 10 STAT total_items 10 STAT bytes 122931 STAT curr_connections 1 STAT total_connections 5 STAT connection_structures 4 STAT cmd_get 20 STAT cmd_set 10 STAT get_hits 0 STAT get_misses 20 STAT bytes_read 122986 STAT bytes_written 187 STAT limit_maxbytes 1073741824 ``` Is there an easier way?
The PHP Memcached module also includes [a script](http://svn.php.net/viewvc/pecl/apc/trunk/apc.php?view=markup) that will display the stats in summary, and also graph form, as well as being able to view individual cached items. If you are already using PHP & memcache on windows, it's an almost drop-in solution.
266,665
<p>I'm learning C++ and writing little programs as I go along. The following is one such program:</p> <pre><code>// This program is intended to take any integer and convert to the // corresponding signed char. #include &lt;iostream&gt; int main() { signed char sch = 0; int n = 0; while(true){ std::cin &gt;&gt; n; sch = n; std::cout &lt;&lt; n &lt;&lt; " --&gt; " &lt;&lt; sch &lt;&lt; std::endl; } } </code></pre> <p>When I run this program and keep inputs at reasonably small absolute values, it behaves as expected. But when I enter larger inputs, e.g., 10000000000, the program repetitively spits out the same output. Some combinations of input cause erratic behavior. For example:</p> <pre><code>#: ./int2ch 10 10 --&gt; 10000000000 10 --&gt; 10 --&gt; 10 --&gt; 10 --&gt; </code></pre> <p>The program spits out "10 --> " until it's killed. (With this particular sequence of inputs, the program's output changes speed erratically.) I also noticed that the output of large values is determined by the previous legal input as well as the value of the current illegal input.</p> <p>What's going on? (I don't care about fixing the program, that's easy. I want to understand it.)</p>
[ { "answer_id": 266699, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 2, "selected": false, "text": "<p>Given that you are on a 32 bit machine, 10000000000 is too big a number to be represented by an int. Also converting an int to a char will only give you from 0..255 or -128..127 depending on the compiler. </p>\n" }, { "answer_id": 266703, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 5, "selected": true, "text": "<p>Basically your <code>cin</code> stream is in a fail state and thus returns immediately when you try to read it. Rewrite your example like this:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nint main()\n{\n signed char sch = 0;\n int n = 0;\n while(std::cin &gt;&gt; n){\n sch = n;\n std::cout &lt;&lt; n &lt;&lt; \" --&gt; \" &lt;&lt; sch &lt;&lt; std::endl;\n }\n}\n</code></pre>\n\n<p><code>cin &gt;&gt; n</code> will return a reference to <code>cin</code>, which you can test for \"good-ness\" in a conditional. So basically the the \"<code>while(std::cin &gt;&gt; n)</code>\" is saying \"while i could still read from standard input successfully, do the following\"</p>\n\n<p>EDIT: the reason it repeatedly output the last good value entered is because that was the last value successfully read in n, the failed reads won't change the value of n</p>\n\n<p>EDIT: as noted in a comment, you can clear the error state and try again something like this would probably work and just ignore bad numbers:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;climits&gt;\n\nint main() {\n signed char sch = 0;\n int n = 0;\n while(true) {\n if(std::cin &gt;&gt; n) {\n sch = n;\n std::cout &lt;&lt; n &lt;&lt; \" --&gt; \" &lt;&lt; sch &lt;&lt; std::endl;\n } else {\n std::cin.clear(); // clear error state\n std::cin.ignore(INT_MAX, '\\n'); // ignore this line we couldn't read it\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 266711, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 0, "selected": false, "text": "<p>One problem here is that a <code>char</code> has a size of one byte, and thus can only hold a number between -127 and 128. An <code>int</code> on the other hand, is typically 4 bytes, and can take on much larger values. Second problem is that you are inputting a value that is too large even for an <code>int</code>.</p>\n" }, { "answer_id": 266974, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 3, "selected": false, "text": "<p>Yes, Evan Teran pointed out most things already. One thing i want to add (since i cannot comment his comment yet :)) is that you must put the call to istream::clear <em>before</em> the call to istream::ignore. The reason is that istream::ignore likewise will just refuse to do anything if the stream is still in the fail state.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32944/" ]
I'm learning C++ and writing little programs as I go along. The following is one such program: ``` // This program is intended to take any integer and convert to the // corresponding signed char. #include <iostream> int main() { signed char sch = 0; int n = 0; while(true){ std::cin >> n; sch = n; std::cout << n << " --> " << sch << std::endl; } } ``` When I run this program and keep inputs at reasonably small absolute values, it behaves as expected. But when I enter larger inputs, e.g., 10000000000, the program repetitively spits out the same output. Some combinations of input cause erratic behavior. For example: ``` #: ./int2ch 10 10 --> 10000000000 10 --> 10 --> 10 --> 10 --> ``` The program spits out "10 --> " until it's killed. (With this particular sequence of inputs, the program's output changes speed erratically.) I also noticed that the output of large values is determined by the previous legal input as well as the value of the current illegal input. What's going on? (I don't care about fixing the program, that's easy. I want to understand it.)
Basically your `cin` stream is in a fail state and thus returns immediately when you try to read it. Rewrite your example like this: ``` #include <iostream> int main() { signed char sch = 0; int n = 0; while(std::cin >> n){ sch = n; std::cout << n << " --> " << sch << std::endl; } } ``` `cin >> n` will return a reference to `cin`, which you can test for "good-ness" in a conditional. So basically the the "`while(std::cin >> n)`" is saying "while i could still read from standard input successfully, do the following" EDIT: the reason it repeatedly output the last good value entered is because that was the last value successfully read in n, the failed reads won't change the value of n EDIT: as noted in a comment, you can clear the error state and try again something like this would probably work and just ignore bad numbers: ``` #include <iostream> #include <climits> int main() { signed char sch = 0; int n = 0; while(true) { if(std::cin >> n) { sch = n; std::cout << n << " --> " << sch << std::endl; } else { std::cin.clear(); // clear error state std::cin.ignore(INT_MAX, '\n'); // ignore this line we couldn't read it } } } ```
266,681
<p>I just realized that in some place in my code I have the return statement inside the lock and sometime outside. Which one is the best?</p> <p>1)</p> <pre><code>void example() { lock (mutex) { //... } return myData; } </code></pre> <p>2)</p> <pre><code>void example() { lock (mutex) { //... return myData; } } </code></pre> <p>Which one should I use?</p>
[ { "answer_id": 266685, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 5, "selected": false, "text": "<p>It doesn't make any difference; they're both translated to the same thing by the compiler.</p>\n\n<p>To clarify, either is effectively translated to something with the following semantics:</p>\n\n<pre><code>T myData;\nMonitor.Enter(mutex)\ntry\n{\n myData= // something\n}\nfinally\n{\n Monitor.Exit(mutex);\n}\n\nreturn myData;\n</code></pre>\n" }, { "answer_id": 266701, "author": "Adam Asham", "author_id": 31518, "author_profile": "https://Stackoverflow.com/users/31518", "pm_score": 0, "selected": false, "text": "<p>To make it easier for fellow developers to read the code I would suggest the first alternative.</p>\n" }, { "answer_id": 266706, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 3, "selected": false, "text": "<p>If think the lock outside looks better, but be careful if you end up changing the code to:</p>\n\n<pre><code>return f(...)\n</code></pre>\n\n<p>If f() needs to be called with the lock held then it obviously needs to be inside the lock, as such keeping returns inside the lock for consistency makes sense.</p>\n" }, { "answer_id": 266718, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 9, "selected": true, "text": "<p>Essentially, which-ever makes the code simpler. Single point of exit is a nice ideal, but I wouldn't bend the code out of shape just to achieve it... And if the alternative is declaring a local variable (outside the lock), initializing it (inside the lock) and then returning it (outside the lock), then I'd say that a simple \"return foo\" inside the lock is a lot simpler.</p>\n\n<p>To show the difference in IL, lets code:</p>\n\n<pre><code>static class Program\n{\n static void Main() { }\n\n static readonly object sync = new object();\n\n static int GetValue() { return 5; }\n\n static int ReturnInside()\n {\n lock (sync)\n {\n return GetValue();\n }\n }\n\n static int ReturnOutside()\n {\n int val;\n lock (sync)\n {\n val = GetValue();\n }\n return val;\n }\n}\n</code></pre>\n\n<p>(note that I'd happily argue that <code>ReturnInside</code> is a simpler/cleaner bit of C#)</p>\n\n<p>And look at the IL (release mode etc):</p>\n\n<pre><code>.method private hidebysig static int32 ReturnInside() cil managed\n{\n .maxstack 2\n .locals init (\n [0] int32 CS$1$0000,\n [1] object CS$2$0001)\n L_0000: ldsfld object Program::sync\n L_0005: dup \n L_0006: stloc.1 \n L_0007: call void [mscorlib]System.Threading.Monitor::Enter(object)\n L_000c: call int32 Program::GetValue()\n L_0011: stloc.0 \n L_0012: leave.s L_001b\n L_0014: ldloc.1 \n L_0015: call void [mscorlib]System.Threading.Monitor::Exit(object)\n L_001a: endfinally \n L_001b: ldloc.0 \n L_001c: ret \n .try L_000c to L_0014 finally handler L_0014 to L_001b\n} \n\nmethod private hidebysig static int32 ReturnOutside() cil managed\n{\n .maxstack 2\n .locals init (\n [0] int32 val,\n [1] object CS$2$0000)\n L_0000: ldsfld object Program::sync\n L_0005: dup \n L_0006: stloc.1 \n L_0007: call void [mscorlib]System.Threading.Monitor::Enter(object)\n L_000c: call int32 Program::GetValue()\n L_0011: stloc.0 \n L_0012: leave.s L_001b\n L_0014: ldloc.1 \n L_0015: call void [mscorlib]System.Threading.Monitor::Exit(object)\n L_001a: endfinally \n L_001b: ldloc.0 \n L_001c: ret \n .try L_000c to L_0014 finally handler L_0014 to L_001b\n}\n</code></pre>\n\n<p>So at the IL level they are [give or take some names] identical (I learnt something ;-p).\nAs such, the only sensible comparison is the (highly subjective) law of local coding style... I prefer <code>ReturnInside</code> for simplicity, but I wouldn't get excited about either.</p>\n" }, { "answer_id": 266766, "author": "Edward Kmett", "author_id": 34707, "author_profile": "https://Stackoverflow.com/users/34707", "pm_score": 3, "selected": false, "text": "<p>It depends, </p>\n\n<p>I am going to go against the grain here. I generally would return inside of the lock.</p>\n\n<p>Usually the variable mydata is a local variable. I am fond of declaring local variables while I initialize them. I rarely have the data to initialize my return value outside of my lock.</p>\n\n<p>So your comparison is actually flawed. While ideally the difference between the two options would be as you had written, which seems to give the nod to case 1, in practice its a little uglier.</p>\n\n<pre><code>void example() { \n int myData;\n lock (foo) { \n myData = ...;\n }\n return myData\n}\n</code></pre>\n\n<p>vs.</p>\n\n<pre><code>void example() { \n lock (foo) {\n return ...;\n }\n}\n</code></pre>\n\n<p>I find case 2 to be considerably easier to read and harder to screw up, especially for short snippets.</p>\n" }, { "answer_id": 272974, "author": "Ricardo Villamil", "author_id": 19314, "author_profile": "https://Stackoverflow.com/users/19314", "pm_score": 5, "selected": false, "text": "<p>I would definitely put the return inside the lock. Otherwise you risk another thread entering the lock and modifying your variable before the return statement, therefore making the original caller receive a different value than expected.</p>\n" }, { "answer_id": 17283958, "author": "greyseal96", "author_id": 1600090, "author_profile": "https://Stackoverflow.com/users/1600090", "pm_score": 2, "selected": false, "text": "<p>For what it's worth, the <a href=\"http://msdn.microsoft.com/en-us/library/c5kehkcz%28v=vs.100%29.aspx\" rel=\"nofollow\">documentation on MSDN</a> has an example of returning from inside of the lock. From the other answers on here, it does appear to be pretty similar IL but, to me, it does seem safer to return from inside the lock because then you don't run the risk of a return variable being overwritten by another thread.</p>\n" }, { "answer_id": 47995372, "author": "mshakurov", "author_id": 3787814, "author_profile": "https://Stackoverflow.com/users/3787814", "pm_score": 0, "selected": false, "text": "<p><code>lock() return &lt;expression&gt;</code> statements always:</p>\n\n<p>1) enter lock</p>\n\n<p>2) makes local (thread-safe) store for the value of the specified type,</p>\n\n<p>3) fills the store with the value returned by <code>&lt;expression&gt;</code>,</p>\n\n<p>4) exit lock</p>\n\n<p>5) return the store.</p>\n\n<p>It means that value, returned from lock statement, always \"cooked\" before return.</p>\n\n<p>Don't worry about <code>lock() return</code>, do not listen to anyone here ))</p>\n" }, { "answer_id": 62028761, "author": "mklement0", "author_id": 45375, "author_profile": "https://Stackoverflow.com/users/45375", "pm_score": -1, "selected": false, "text": "<p><sup>Note: I believe this answer to be factually correct and I hope that it is helpful too, but I'm always happy to improve it based on concrete feedback.\n</sup></p>\n<p>To summarize and complement the existing answers:</p>\n<ul>\n<li><p>The <a href=\"https://stackoverflow.com/a/266718/45375\">accepted answer</a> shows that, irrespective of which syntax form you choose in your <em>C#</em> code, in the IL code - and therefore at runtime - the <code>return</code> doesn't happen until <em>after</em> the lock is released.</p>\n<ul>\n<li>Even though placing the <code>return</code> <em>inside</em> the <code>lock</code> block therefore, strictly speaking, misrepresents the flow of control<sup>[1]</sup>, it is syntactically <em>convenient</em> in that it obviates the need for storing the return value in an aux. local variable (declared outside the block, so that it can be used with a <code>return</code> outside the block) - see <a href=\"https://stackoverflow.com/a/266766/45375\">Edward KMETT's answer</a>.</li>\n</ul>\n</li>\n<li><p>Separately - and this aspect is <em>incidental</em> to the question, but may still be of interest (<a href=\"https://stackoverflow.com/a/272974/45375\">Ricardo Villamil's answer</a> tries to address it, but incorrectly, I think) - combining a <code>lock</code> statement with a <code>return</code> statement - i.e., obtaining value to <code>return</code> in a block protected from concurrent access - only meaningfully &quot;protects&quot; the returned value in the <em>caller</em>'s scope <em>if it doesn't actually need protecting once obtained</em>, which applies in the following scenarios:</p>\n<ul>\n<li><p>If the returned value is an element from a collection that only needs protection in terms of <em>adding and removing</em> elements, not in terms of modifications of the <em>elements themselves</em> and/or ...</p>\n</li>\n<li><p>... if the value being returned is an instance of a <em>value type</em> or a <em>string</em>.</p>\n<ul>\n<li>Note that in this case the caller receives a <em>snapshot</em> (copy)<sup>[2]</sup> of the value - which by the time the caller inspects it may no longer be the current value in the data structure of origin.</li>\n</ul>\n</li>\n<li><p>In any other case, the locking must be performed by the <em>caller</em>, not (just) inside the method.</p>\n</li>\n</ul>\n</li>\n</ul>\n<hr />\n<p><sup>[1] <a href=\"https://stackoverflow.com/users/11178549/theodor-zoulias\">Theodor Zoulias</a> points out that that is technically also true for placing <code>return</code> inside <code>try</code>, <code>catch</code>, <code>using</code>, <code>if</code>, <code>while</code>, <code>for</code>, ... statements; however, it is the specific purpose of the <code>lock</code> statement that is likely to invite scrutiny of the true control flow, as evidenced by this question having been asked and having received much attention.</sup></p>\n<p><sup>[2] Accessing a value-type instance invariably creates a thread-local, on-the-stack copy of it; even though strings are technically reference-type instances, they effectively behave like-value type instances.</sup></p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
I just realized that in some place in my code I have the return statement inside the lock and sometime outside. Which one is the best? 1) ``` void example() { lock (mutex) { //... } return myData; } ``` 2) ``` void example() { lock (mutex) { //... return myData; } } ``` Which one should I use?
Essentially, which-ever makes the code simpler. Single point of exit is a nice ideal, but I wouldn't bend the code out of shape just to achieve it... And if the alternative is declaring a local variable (outside the lock), initializing it (inside the lock) and then returning it (outside the lock), then I'd say that a simple "return foo" inside the lock is a lot simpler. To show the difference in IL, lets code: ``` static class Program { static void Main() { } static readonly object sync = new object(); static int GetValue() { return 5; } static int ReturnInside() { lock (sync) { return GetValue(); } } static int ReturnOutside() { int val; lock (sync) { val = GetValue(); } return val; } } ``` (note that I'd happily argue that `ReturnInside` is a simpler/cleaner bit of C#) And look at the IL (release mode etc): ``` .method private hidebysig static int32 ReturnInside() cil managed { .maxstack 2 .locals init ( [0] int32 CS$1$0000, [1] object CS$2$0001) L_0000: ldsfld object Program::sync L_0005: dup L_0006: stloc.1 L_0007: call void [mscorlib]System.Threading.Monitor::Enter(object) L_000c: call int32 Program::GetValue() L_0011: stloc.0 L_0012: leave.s L_001b L_0014: ldloc.1 L_0015: call void [mscorlib]System.Threading.Monitor::Exit(object) L_001a: endfinally L_001b: ldloc.0 L_001c: ret .try L_000c to L_0014 finally handler L_0014 to L_001b } method private hidebysig static int32 ReturnOutside() cil managed { .maxstack 2 .locals init ( [0] int32 val, [1] object CS$2$0000) L_0000: ldsfld object Program::sync L_0005: dup L_0006: stloc.1 L_0007: call void [mscorlib]System.Threading.Monitor::Enter(object) L_000c: call int32 Program::GetValue() L_0011: stloc.0 L_0012: leave.s L_001b L_0014: ldloc.1 L_0015: call void [mscorlib]System.Threading.Monitor::Exit(object) L_001a: endfinally L_001b: ldloc.0 L_001c: ret .try L_000c to L_0014 finally handler L_0014 to L_001b } ``` So at the IL level they are [give or take some names] identical (I learnt something ;-p). As such, the only sensible comparison is the (highly subjective) law of local coding style... I prefer `ReturnInside` for simplicity, but I wouldn't get excited about either.
266,688
<p>As many do I have a config.php file in the root of a web app that I want to include in almost every other php file. So most of them have a line like:</p> <pre><code>require_once("config.php"); </code></pre> <p>or sometimes</p> <pre><code>require_once("../config.php"); </code></pre> <p>or even</p> <pre><code>require_once("../../config.php"); </code></pre> <p>But I never get it right the first time. I can't figure out what php is going to consider to be the current working directory when reading one of these files. It is apparently not the directory where the file containing the require_once() call is made because I can have two files in the same directory that have different paths for the config.php.</p> <p>How I have a situation where one path is correct for refreshing the page but an ajax can that updates part of the page requires a different path to the config.php in the require_once() statement;</p> <p>What's the secret? From where is that path evaluated?</p> <p>Shoot, I was afraid this wouldn't be a common problem - This is occurring under apache 2.2.8 and PHP 5.2.6 running on windows.</p>
[ { "answer_id": 266707, "author": "Thomas Owens", "author_id": 572, "author_profile": "https://Stackoverflow.com/users/572", "pm_score": 0, "selected": false, "text": "<p>The only place I've seen the path evaluated from is the file that you are currently editing. I've never had any problems with it, but if you are, you might want to provide more information (PHP version, OS, etc).</p>\n" }, { "answer_id": 266730, "author": "bobwienholt", "author_id": 24257, "author_profile": "https://Stackoverflow.com/users/24257", "pm_score": 4, "selected": false, "text": "<p>I like to do this:</p>\n\n<pre><code>require_once(dirname(__FILE__).\"/../_include/header.inc\");\n</code></pre>\n\n<p>That way your paths can always be relative to the current file location.</p>\n" }, { "answer_id": 266749, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": "<p>I use the <code>dirname(<code>__FILE__</code>)</code> thing like <a href=\"https://stackoverflow.com/questions/266688/how-do-you-know-the-correct-path-to-use-in-a-php-requireonce-statement#266730\">bobwienholt</a> most the time, but what it could pay to do is have a base entry point that loads all your other code that defines a constant refereing to the root of the project, ie</p>\n\n<pre><code>define(\"ROOT\",dirname(__FILE__).'/' ); \n</code></pre>\n\n<p>and then later all you need to know is where the path is relative to root, ie: </p>\n\n<pre><code>require(ROOT . \"/lib/tool/error.php\"); \n</code></pre>\n\n<p><H3>note, </h3>\nyou should <em>REALLY</em> avoid paths with \"../\" at the start of them, they are not relative to the file, but relative to where you <strong>ARE</strong> and this creates broken-ass code. </p>\n\n<pre><code> cd foo\n php bar/baz.php \n -&gt; some error saying it cant find the file\n cd bar \n php baz.php \n -&gt; suddenly working.\n</code></pre>\n\n<h3>Important</h3>\n\n<p>If you use \"../\" notation, it takes <strong>complete</strong> ignorance of the PHP Include Path, And <strong>ONLY</strong> considers where the person whom is running it is. </p>\n" }, { "answer_id": 266760, "author": "Zak", "author_id": 2112692, "author_profile": "https://Stackoverflow.com/users/2112692", "pm_score": 1, "selected": false, "text": "<p>Since require and require_once are very similar to include and include_once, all the documentation is posted under the \"include\" functions doc area on php.net From <a href=\"http://us.php.net/manual/en/function.include.php\" rel=\"nofollow noreferrer\">that page</a> </p>\n\n<blockquote>\n <p>Files for including are first looked\n for in each include_path entry\n relative to the current working\n directory, and then in the directory\n of current script. E.g. if your\n include_path is libraries, current\n working directory is /www/, you\n included include/a.php and there is\n include \"b.php\" in that file, b.php\n is first looked in /www/libraries/ \n and then in /www/include/. If filename\n begins with ./ or ../, it is looked\n only in the current working directory.</p>\n</blockquote>\n\n<p>Further, you can find all the current include paths by doing a \"php -i\" from the command line. You can edit the include path in your php.ini file, and also via ini_set(). You can also run the php_info() function in your page to get a printout of your env vars if the CLI is inconvenient.</p>\n" }, { "answer_id": 266763, "author": "andyhky", "author_id": 2764, "author_profile": "https://Stackoverflow.com/users/2764", "pm_score": -1, "selected": false, "text": "<p>Take a look at the function getcwd. <a href=\"http://us2.php.net/getcwd\" rel=\"nofollow noreferrer\" title=\"getcwd\">http://us2.php.net/getcwd</a></p>\n" }, { "answer_id": 266768, "author": "Ferdinand Beyer", "author_id": 34855, "author_profile": "https://Stackoverflow.com/users/34855", "pm_score": 1, "selected": false, "text": "<p>If you have sufficient access rights, try to modify PHP's <code>include_path</code> setting for the whole site. If you cannot do that, you'll either have to route every request through the same PHP script (eg. using Apache mod_rewrite) or you'll have to use an \"initialization\" script that sets up the include_path:</p>\n\n<pre><code>$includeDir = realpath(dirname(__FILE__) . '/include'); \nini_set('include_path', $includeDir . PATH_SEPARATOR . ini_get('include_path'));\n</code></pre>\n\n<p>After that file is included, use paths relative to the include directory:</p>\n\n<pre><code>require_once '../init.php'; // The init-script\nrequire_once 'MyFile.php'; // Includes /include/MyFile.php\n</code></pre>\n" }, { "answer_id": 266775, "author": "Seamus", "author_id": 30443, "author_profile": "https://Stackoverflow.com/users/30443", "pm_score": 6, "selected": true, "text": "<p>The current working directory for PHP is the directory in which the called script file is located. If your files looked like this:</p>\n\n<pre><code>/A\n foo.php\n tar.php\n B/\n bar.php\n</code></pre>\n\n<p>If you call foo.php (ex: <a href=\"http://example.com/foo.php\" rel=\"noreferrer\">http://example.com/foo.php</a>), the working directory will be /A/. If you call bar.php (ex: <a href=\"http://example.com/B/bar.php\" rel=\"noreferrer\">http://example.com/B/bar.php</a>), the working directory will be /A/B/.</p>\n\n<p>There is where it gets tricky. Let us say that foo.php is such:</p>\n\n<pre><code>&lt;?php\nrequire_once( 'B/bar.php' );\n?&gt;\n</code></pre>\n\n<p>And bar.php is:</p>\n\n<pre><code>&lt;?php\nrequire_once( 'tar.php');\n?&gt;\n</code></pre>\n\n<p>If we call foo.php, then bar.php will successfully call tar.php because tar.php and foo.php are in the same directory which happens to be the working directory. If you instead call bar.php, it will fail.</p>\n\n<p>Generally you will see either in all files:</p>\n\n<pre><code>require_once( realpath( dirname( __FILE__ ) ).'/../../path/to/file.php' );\n</code></pre>\n\n<p>or with the config file:</p>\n\n<pre><code>// config file\ndefine( \"APP_ROOT\", realpath( dirname( __FILE__ ) ).'/' );\n</code></pre>\n\n<p>with the rest of the files using:</p>\n\n<pre><code>require_once( APP_ROOT.'../../path/to/file.php' );\n</code></pre>\n" }, { "answer_id": 266780, "author": "Michael Luton", "author_id": 2158, "author_profile": "https://Stackoverflow.com/users/2158", "pm_score": 0, "selected": false, "text": "<p>The path of the PHP file requested in the original GET or POST is essentially the 'working directory' of that script. Any \"included\" or \"required\" scripts will inherit that as their working directory as well.</p>\n\n<p>I will either use absolute paths in require statements or modify PHP's include_path to include any path in my app I may want to use to save me the extra typing. You'll find that in php.ini.</p>\n\n<p>include_path = \".:/list/of/paths/:/another/path/:/and/another/one\"</p>\n\n<p>I don't know if it'll help you out in this particular instance but the magical constants like <strong>FILE</strong> and <strong>DIR</strong> can come in handy if you ever need to know the path a particular file is running in.</p>\n\n<p><a href=\"http://us2.php.net/manual/en/language.constants.predefined.php\" rel=\"nofollow noreferrer\">http://us2.php.net/manual/en/language.constants.predefined.php</a></p>\n" }, { "answer_id": 267037, "author": "Steve Massing", "author_id": 34889, "author_profile": "https://Stackoverflow.com/users/34889", "pm_score": 2, "selected": false, "text": "<p>I include this code at the top of every page:</p>\n\n<pre><code>//get basic page variables\n$self=$_SERVER['PHP_SELF']; \n$thispath=dirname($_SERVER['PHP_SELF']);\n$sitebasepath=$_SERVER['DOCUMENT_ROOT'];\n\n//include the global settings, variables and includes\n\ninclude_once(\"$sitebasepath/globals/global.include.php\");\n</code></pre>\n\n<p>Include and require both take either a relative path or the full rooted path. I prefer working with the full path and make all my references like the inlcude statement above. This allows me to enter a general variable $sitebasepath that handles account specific information that may change from machine to machine and then simply type the path from the webroot, ie. /globals/whatever_file.php</p>\n\n<p>I also use the $self variable in forms that may call themselves to handle data input.</p>\n\n<p>Hope that helps.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28565/" ]
As many do I have a config.php file in the root of a web app that I want to include in almost every other php file. So most of them have a line like: ``` require_once("config.php"); ``` or sometimes ``` require_once("../config.php"); ``` or even ``` require_once("../../config.php"); ``` But I never get it right the first time. I can't figure out what php is going to consider to be the current working directory when reading one of these files. It is apparently not the directory where the file containing the require\_once() call is made because I can have two files in the same directory that have different paths for the config.php. How I have a situation where one path is correct for refreshing the page but an ajax can that updates part of the page requires a different path to the config.php in the require\_once() statement; What's the secret? From where is that path evaluated? Shoot, I was afraid this wouldn't be a common problem - This is occurring under apache 2.2.8 and PHP 5.2.6 running on windows.
The current working directory for PHP is the directory in which the called script file is located. If your files looked like this: ``` /A foo.php tar.php B/ bar.php ``` If you call foo.php (ex: <http://example.com/foo.php>), the working directory will be /A/. If you call bar.php (ex: <http://example.com/B/bar.php>), the working directory will be /A/B/. There is where it gets tricky. Let us say that foo.php is such: ``` <?php require_once( 'B/bar.php' ); ?> ``` And bar.php is: ``` <?php require_once( 'tar.php'); ?> ``` If we call foo.php, then bar.php will successfully call tar.php because tar.php and foo.php are in the same directory which happens to be the working directory. If you instead call bar.php, it will fail. Generally you will see either in all files: ``` require_once( realpath( dirname( __FILE__ ) ).'/../../path/to/file.php' ); ``` or with the config file: ``` // config file define( "APP_ROOT", realpath( dirname( __FILE__ ) ).'/' ); ``` with the rest of the files using: ``` require_once( APP_ROOT.'../../path/to/file.php' ); ```
266,693
<p>I'd like to remove all "unchecked" warnings from this general utility method (part of a larger class with a number of similar methods). In a pinch, I can use @SuppressWarnings("unchecked") but I'm wondering if I can use generics properly to avoid the warning.</p> <p>The method is intended to be allow callers to compare two objects by passing through to compareTo, with the exception that if the object is a strings it does it in a case insensitive manner.</p> <pre><code>public static int compareObject(Comparable o1, Comparable o2) { if ((o1 instanceof String) &amp;&amp; (o2 instanceof String)) return ((String) o1).toUpperCase().compareTo(((String) o2).toUpperCase()); else return o1.compareTo(o2); } </code></pre> <p>This was my first (incorrect) attempt at a solution. The parameters work fine, but the line o1.compareTo(o2) has a compile error "The method compareTo(capture#15-of ?) in the type Comparable is not applicable for the arguments (Comparable".</p> <pre><code>public static int compareObject(Comparable&lt;?&gt; o1, Comparable&lt;?&gt; o2) { if ((o1 instanceof String) &amp;&amp; (o2 instanceof String)) return ((String) o1).toUpperCase().compareTo(((String) o2).toUpperCase()); else return o1.compareTo(o2); } </code></pre> <p>Any suggestions?</p>
[ { "answer_id": 266741, "author": "jfpoilpret", "author_id": 1440720, "author_profile": "https://Stackoverflow.com/users/1440720", "pm_score": -1, "selected": false, "text": "<p>Did you test the following?</p>\n\n<pre><code>public static &lt;T&gt; int compareObject(Comparable&lt;T&gt; o1, Comparable&lt;T&gt; o2)\n{\n if ((o1 instanceof String) &amp;&amp; (o2 instanceof String))\n return ((String) o1).toUpperCase().compareTo(((String) o2).toUpperCase());\n else\n return o1.compareTo(o2);\n}\n</code></pre>\n\n<p>I think it should work correctly.</p>\n" }, { "answer_id": 266786, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 3, "selected": true, "text": "<p>I just tried this:</p>\n\n<pre><code>public static &lt;T extends Comparable&gt; int compareObject(T o1, T o2) {\n if ((o1 instanceof String) &amp;&amp; (o2 instanceof String))\n return ((String) o1).toUpperCase().compareTo(((String) o2).toUpperCase());\n else\n return o1.compareTo(o2);\n}\n</code></pre>\n\n<p>It compiles, but gives a unchecked cast warning on the compareTo() call.<br>\nI tried changing it to</p>\n\n<pre><code>public static &lt;T extends Comparable&lt;T&gt;&gt; int compareObject(T o1, T o2) {\n</code></pre>\n\n<p>and the String checks failed to compile (\"inconvertible types: found: T, required: String\"). I think this must be close, though.</p>\n\n<hr>\n\n<p>EDIT: As pointed out in the comments, this is a <a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6548436\" rel=\"nofollow noreferrer\">bug in javac</a>. The second form is indeed correct, but will not compile currently. Crazy as it may look, this is the code that works with no warnings:</p>\n\n<pre><code>public static &lt;T extends Comparable&lt;T&gt;&gt; int compareObject(T o1, T o2) {\n if (((Object) o1 instanceof String) &amp;&amp; ((Object) o2 instanceof String))\n return ((String) (Object)o1).toUpperCase().compareTo(((String) (Object)o2).toUpperCase());\n else\n return o1.compareTo(o2);\n}\n</code></pre>\n\n<p>As you can see, the only difference is all the redundant casts to <code>Object</code>.</p>\n" }, { "answer_id": 266789, "author": "Frederic Morin", "author_id": 4064, "author_profile": "https://Stackoverflow.com/users/4064", "pm_score": 1, "selected": false, "text": "<p>Here's what you are looking for:</p>\n\n<pre><code>public static &lt;T extends Comparable&lt;T&gt;&gt; int compareObject(T o1, T o2) {\n if ((o1 instanceof String) &amp;&amp; (o2 instanceof String))\n return ((String) o1).toUpperCase().compareTo(((String) o2).toUpperCase());\n else\n return o1.compareTo(o2);\n}\n</code></pre>\n" }, { "answer_id": 267913, "author": "Hans-Peter Störr", "author_id": 21499, "author_profile": "https://Stackoverflow.com/users/21499", "pm_score": 1, "selected": false, "text": "<p>I hope you are aware that many of the approaches here do change the semantics of the method. With the original method you could compare objects of different types if they allow this, but with</p>\n\n<pre><code>public static &lt;T extends Comparable&lt;T&gt;&gt; int compareObject(T o1, T o2)\n</code></pre>\n\n<p>you cannot do this comparison anymore. A variant that allows this would be</p>\n\n<pre><code> public static int compareObject2(Comparable&lt;Object&gt; o1, Comparable&lt;Object&gt; o2) {\n if (((Object) o1 instanceof String) &amp;&amp; ((Object) o2 instanceof String))\n return ((String) (Object)o1).toUpperCase().compareTo(((String) (Object)o2).toUpperCase());\n else\n return o1.compareTo(o2);\n}\n</code></pre>\n\n<p>(I inserted the workaround for the mentioned javac bug.) But this does not enhance type safety or anything, so in this case it is probably better to use the more understandable non generic method and live with a <code>@SuppressWarnings(\"unchecked\")</code>. There is such a thing as overuse of generics.</p>\n" }, { "answer_id": 666938, "author": "Bartosz Klimek", "author_id": 79920, "author_profile": "https://Stackoverflow.com/users/79920", "pm_score": 0, "selected": false, "text": "<p>What about the following:</p>\n\n<pre><code> public static &lt;T extends Comparable&lt;T&gt;&gt; int compareObjects(T o1, T o2)\n {\n return o1.compareTo(o2);\n }\n\n public static int compareObjects(String o1, String o2)\n {\n return o1.compareToIgnoreCase(o2);\n }\n</code></pre>\n\n<p>The drawback is that when call <code>compareObjects()</code> with Objects that happen to be Strings, the compiler will bind your call to the first function, and you'll end up with the case-sensitive comparison.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32978/" ]
I'd like to remove all "unchecked" warnings from this general utility method (part of a larger class with a number of similar methods). In a pinch, I can use @SuppressWarnings("unchecked") but I'm wondering if I can use generics properly to avoid the warning. The method is intended to be allow callers to compare two objects by passing through to compareTo, with the exception that if the object is a strings it does it in a case insensitive manner. ``` public static int compareObject(Comparable o1, Comparable o2) { if ((o1 instanceof String) && (o2 instanceof String)) return ((String) o1).toUpperCase().compareTo(((String) o2).toUpperCase()); else return o1.compareTo(o2); } ``` This was my first (incorrect) attempt at a solution. The parameters work fine, but the line o1.compareTo(o2) has a compile error "The method compareTo(capture#15-of ?) in the type Comparable is not applicable for the arguments (Comparable". ``` public static int compareObject(Comparable<?> o1, Comparable<?> o2) { if ((o1 instanceof String) && (o2 instanceof String)) return ((String) o1).toUpperCase().compareTo(((String) o2).toUpperCase()); else return o1.compareTo(o2); } ``` Any suggestions?
I just tried this: ``` public static <T extends Comparable> int compareObject(T o1, T o2) { if ((o1 instanceof String) && (o2 instanceof String)) return ((String) o1).toUpperCase().compareTo(((String) o2).toUpperCase()); else return o1.compareTo(o2); } ``` It compiles, but gives a unchecked cast warning on the compareTo() call. I tried changing it to ``` public static <T extends Comparable<T>> int compareObject(T o1, T o2) { ``` and the String checks failed to compile ("inconvertible types: found: T, required: String"). I think this must be close, though. --- EDIT: As pointed out in the comments, this is a [bug in javac](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6548436). The second form is indeed correct, but will not compile currently. Crazy as it may look, this is the code that works with no warnings: ``` public static <T extends Comparable<T>> int compareObject(T o1, T o2) { if (((Object) o1 instanceof String) && ((Object) o2 instanceof String)) return ((String) (Object)o1).toUpperCase().compareTo(((String) (Object)o2).toUpperCase()); else return o1.compareTo(o2); } ``` As you can see, the only difference is all the redundant casts to `Object`.
266,697
<p>I have a stored procedure that has a optional parameter, <code>@UserID VARCHAR(50)</code>. The thing is, there are two ways to work with it:</p> <ol> <li>Give it a default value of <code>NULL</code>, the have an <code>IF...ELSE</code> clause, that performs two different <code>SELECT</code> queries, one with <code>'WHERE UserID = @UserID'</code> and without the where.</li> <li>Give it a default value of <code>'%'</code> and then just have the where clause use <code>'WHERE UserID LIKE @UserID'</code>. In the calling code, the '%' wont be used, so only exact matches will be found.</li> </ol> <p>The question is: Which option is faster? Which option provides better performance as the table grows? Be aware that the <code>UserID</code> column is a foreign key and is not indexed. </p> <p><b>EDIT:</b> Something I want to add, based on some answers: The <code>@UserID</code> parameter is not (necessarily) the only <b>optional</b> parameter being passed. In some cases there are as many as 4 or 5 optional parameters.</p>
[ { "answer_id": 266717, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 3, "selected": false, "text": "<p>What I typically do is something like</p>\n\n<pre><code>WHERE ( @UserID IS NULL OR UserID = @UserID )\n</code></pre>\n\n<p>And why isn't it indexed? It's generally good form to index FKs, since you often join on them...</p>\n\n<p>If you're worried about query plan storage, simply do:\nCREATE PROCEDURE ... WITH RECOMPILE</p>\n" }, { "answer_id": 266728, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 2, "selected": false, "text": "<p>The only way to tell for sure is to implement both and measure. For reference there is a third way to implement this, which is what I tend to use:</p>\n\n<pre><code>WHERE (@UserID IS NULL OR UserId = @UserId)\n</code></pre>\n" }, { "answer_id": 266729, "author": "Ovidiu Pacurar", "author_id": 28419, "author_profile": "https://Stackoverflow.com/users/28419", "pm_score": 2, "selected": false, "text": "<p>Why not use:</p>\n\n<pre><code>where @UserID is null or UserID=@UserID \n</code></pre>\n\n<p>+ on maintainability and performance</p>\n" }, { "answer_id": 266750, "author": "Cruachan", "author_id": 7315, "author_profile": "https://Stackoverflow.com/users/7315", "pm_score": 1, "selected": false, "text": "<p>I'd defiantly go with the first because although it's less 'clever' it's easier to understand what's going on and will hence be easier to maintain. </p>\n\n<p>The use of the special meaning default is likely to trip you up later with some unintended side-effect (documentation as to why you're using that default and it's usage is likely to be missed by any maintainer)</p>\n\n<p>As to efficiency - unless you're looking at 1,000 users or more then it's unlikely to be sufficient an issue to override maintainability.</p>\n" }, { "answer_id": 266767, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "<p>First, you should create an index for <code>UserID</code> if you use it as a search criteria in this way.</p>\n\n<p>Second, comparing <code>UserID LIKE @UserID</code> cannot use an index, because the optimizer doesn't know if you will give a <code>@UserID</code> parameter value that begins with a wildcard. Such a value cannot use the index, so the optimizer must assume it cannot create an execution plan using that index.</p>\n\n<p>So I recommend:</p>\n\n<ol>\n<li>Create an index on <code>UserID</code></li>\n<li>Use the first option, <code>WHERE UserID = @UserID</code>, which should be optimized to use the index.</li>\n</ol>\n\n<p><strong>edit:</strong> Mark Brady reminds me I forgot to address the <code>NULL</code> case. I agree with Mark's answer, do the <code>IF</code> and execute one of two queries. I give Mark's answer +1.</p>\n" }, { "answer_id": 266893, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 0, "selected": false, "text": "<p>I would sort-of go with option 1, but actually have two stored procedures. One would get all the users and one would get a specific user. I think this is clearer than passing in a NULL. This is a scenario where you do want two different SQL statements because you're asking for different things (all rows vs one row).</p>\n" }, { "answer_id": 266938, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": 2, "selected": false, "text": "<p>The issue with having only one stored procedure is as mentioned quite well above that the SQL stores a compiled plan for the procedure, a plan for null is quite different to one with a value.</p>\n\n<p>However, creating an if statement in the stored procedure will lead to the stored procedure being recompiled at run time. This may also add to the performance issues.</p>\n\n<p>As mentioned elsewhere, this is suitable for a test and see approach, taking into account the if statement, an @UserID is null and two separate procedures.</p>\n\n<p>Unfortunately, the speed of these approaches is going to vary greatly based on the amount of data and the frequency of the calls where the parameter is null vs the calls where the parameter is not. Again the number of parameters is also going to affect the efficacy of an approach that requires re-writing the procedures.</p>\n\n<p>If you are using SQL 2005, you may get some mileage from the query <a href=\"http://www.microsoft.com/technet/prodtechnol/sql/2005/frcqupln.mspx\" rel=\"nofollow noreferrer\">plan hint option</a>.</p>\n\n<p><strong>Correction:</strong>\nSql 2005 and since has \"statement-Level Recompilation\" which store separate plans in cache for each statement in a procedure... So the old Pre-2005 policy of not putting multiple logic branch statements into a single stored procedure is no longer true... – Charles Bretana \n(i figure this was important enough to elevate from a comment)</p>\n" }, { "answer_id": 266961, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 2, "selected": false, "text": "<p>SQL Server 2005 and subsequent have something called \"statement-level recompilation\". Check out \n<a href=\"http://www.microsoft.com/technet/prodtechnol/sql/2005/recomp.mspx\" rel=\"nofollow noreferrer\">http://www.microsoft.com/technet/prodtechnol/sql/2005/recomp.mspx</a> </p>\n\n<p>Basically, each individual statement executed by the query processor gets it's own optimized plan, which is then stored in \"Plan Cache\" (This is why they changed the name from \"Procedure-Cache\") </p>\n\n<p>So branching your T-SQL into separate statements is better... </p>\n" }, { "answer_id": 266972, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 1, "selected": false, "text": "<p>Replace the single stored procedure with two. There's way to much room for the query optimizer to start whacking you with unintended consequence on this one. Change the client code to detect which one to call.</p>\n\n<p>I bet if you had done it that way, we wouldn't need to be having this dialog.</p>\n\n<p>And put an index on userid. Indexes are in there for a reason, and this is it.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8363/" ]
I have a stored procedure that has a optional parameter, `@UserID VARCHAR(50)`. The thing is, there are two ways to work with it: 1. Give it a default value of `NULL`, the have an `IF...ELSE` clause, that performs two different `SELECT` queries, one with `'WHERE UserID = @UserID'` and without the where. 2. Give it a default value of `'%'` and then just have the where clause use `'WHERE UserID LIKE @UserID'`. In the calling code, the '%' wont be used, so only exact matches will be found. The question is: Which option is faster? Which option provides better performance as the table grows? Be aware that the `UserID` column is a foreign key and is not indexed. **EDIT:** Something I want to add, based on some answers: The `@UserID` parameter is not (necessarily) the only **optional** parameter being passed. In some cases there are as many as 4 or 5 optional parameters.
What I typically do is something like ``` WHERE ( @UserID IS NULL OR UserID = @UserID ) ``` And why isn't it indexed? It's generally good form to index FKs, since you often join on them... If you're worried about query plan storage, simply do: CREATE PROCEDURE ... WITH RECOMPILE
266,719
<p>I've seen a lot of discussion on URL Routing, and LOTS of great suggestions... but in the real world, one thing I haven't seen discussed are: </p> <ol> <li>Creating Friendly URLs <strong>with Spaces and illegal characters</strong> </li> <li>Querying the DB</li> </ol> <p>Say you're building a Medical site, which has <strong>Articles</strong> with a <strong>Category</strong> and optional <strong>Subcategory</strong>. (1 to many). ( <strong>Could've used any example, but the medical field has lots of long words</strong>)</p> <hr> <h2><strong>Example Categories/Sub/Article Structure:</strong></h2> <ol> <li><strong>Your General Health (Category)</strong> <ul> <li><em>Natural Health <strong>(Subcategory)</em></strong> <ol> <li>Your body's immune system and why it needs help. <strong>(Article)</strong></li> <li>Are plants and herbs really the solution?</li> <li>Should I eat fortified foods?</li> </ol></li> <li>Homeopathic Medicine <ol> <li>What's homeopathic medicine?</li> </ol></li> <li><em>Healthy Eating</em> <ol> <li>Should you drink 10 cups of coffee per day?</li> <li>Are Organic Vegetables worth it?</li> <li>Is Burger King&reg; evil?</li> <li>Is "French café" or American coffee healthier?</li> </ol></li> </ul></li> <li><strong>Diseases &amp; Conditions (Category)</strong> <ul> <li><em>Auto-Immune Disorders <strong>(Subcategory)</em></strong> <ol> <li>The #1 killer of people is some disease</li> <li>How to get help </li> </ol></li> <li><em>Genetic Conditions</em> <ol> <li>Preventing Spina Bifida before pregnancy.</li> <li>Are you predisposed to live a long time?</li> </ol></li> </ul></li> <li><strong>Dr. FooBar's personal suggestions (Category)</strong> <ol> <li>My thoughts on Herbal medicine &amp; natural remedies <strong>(Article - no subcategory)</strong></li> <li>Why should you care about your health?</li> <li>It IS possible to eat right and have a good diet.</li> <li>Has bloodless surgery come of age?</li> </ol></li> </ol> <hr> <p>In a structure like this, you're going to have some <strong>LOOONG URLs</strong> if you go: /{Category}/{subcategory}/{Article Title}</p> <p>In addition, there are numerous <strong>illegal characters</strong>, like # ! ? ' é " etc.</p> <h2><strong>SO, the QUESTION(S) ARE:</strong></h2> <ol> <li>How would you handle illegal characters and Spaces? (Pros and Cons?)</li> <li>Would you handle getting this from the Database <ul> <li>In other words, would you <strong>trust the DB to find</strong> the Item, passing the title, <strong>or pull all the titles</strong> and find the key in code to get the key to pass to the Database (two calls to the database)?</li> </ul></li> </ol> <p><em>note: I always see nice pretty examples like /products/beverages/Short-Product-Name/ how about handling some ugly examples ^_^</em></p>
[ { "answer_id": 266725, "author": "Armstrongest", "author_id": 26931, "author_profile": "https://Stackoverflow.com/users/26931", "pm_score": 0, "selected": false, "text": "<p>As a follow-up. I do have some ideas. So feel free to comment on the ideas or give your own answer to the question:</p>\n\n<p>Solution #1: Replace all illegal characters with dashes:</p>\n\n<ul>\n<li><strong>www.mysite.com/diseases---conditions/Auto-immune-disorders/the--1-killer-of-people-is-some-disease/</strong></li>\n</ul>\n\n<p>That looks a little ugly to me... </p>\n\n<p>Solution #2: Strip illegal characters and replace spaces with single dashes:</p>\n\n<ul>\n<li><strong>www.mysite.com/diseases-conditions/Auto-immune-disorders/the-1-killer-of-people-is-some-disease/</strong></li>\n</ul>\n\n<p>Solution #3 Apply a few rules to replace certain characters with words:</p>\n\n<ul>\n<li><strong>www.mysite.com/diseases-and-conditions/Auto-immune-disorders/the-number1-killer-of-people-is-some-disease/</strong></li>\n</ul>\n\n<p>Solution #4 Strip All Spaces and use Capitalization</p>\n\n<ul>\n<li><strong>www.mysite.com/DiseasesAndConditions/AutoImmuneDisorders/TheNumber1KillerOfPeopleIsSomeDisease/</strong></li>\n</ul>\n\n<p>(May not work well on case sensitive servers and is hard to read)</p>\n" }, { "answer_id": 266765, "author": "da5id", "author_id": 14979, "author_profile": "https://Stackoverflow.com/users/14979", "pm_score": 0, "selected": false, "text": "<p>Solution 2 would be my recommendation. I'm not the worlds biggest SEO expert, but I believe it's pretty much the 'standard' way to get good rankings anyway.</p>\n" }, { "answer_id": 266769, "author": "Arief", "author_id": 34096, "author_profile": "https://Stackoverflow.com/users/34096", "pm_score": 0, "selected": false, "text": "<p>What I do normally is to allow only legal character and keep the friendly URL as short as possible. Also important is that friendly URLs are often inserted by human, I never generate a friendly URL from title or content, and then use that one to query the database. I would use a column in a table e.g. friendly_url, so that the website admin can insert friendly URLs.</p>\n" }, { "answer_id": 266796, "author": "alex", "author_id": 26787, "author_profile": "https://Stackoverflow.com/users/26787", "pm_score": 2, "selected": false, "text": "<p>My last approach is:</p>\n\n<ol>\n<li>Convert all \"strange letters\" to \"normal letters\" -> à to a, ñ to n, etc.</li>\n<li>Convert all non-word characters to _ (i.e not a-zA-Z0-9)</li>\n<li>replace groups of underscores with a single underscore</li>\n<li>remove all tailing and leading underscores</li>\n</ol>\n\n<p>As for storage, I believe the friendly URL should go to the database, and be immutable, after all <a href=\"http://www.w3.org/Provider/Style/URI\" rel=\"nofollow noreferrer\">cool URIs don't change</a></p>\n" }, { "answer_id": 266798, "author": "Nick", "author_id": 14072, "author_profile": "https://Stackoverflow.com/users/14072", "pm_score": 0, "selected": false, "text": "<p>I solved this problem by adding an additional column in the database (e.g: UrlTitle alongside the Title column) and saving a title stripped of all illegal characters with '&amp;' symbols replaced with 'and', and spaces replaced by underscores. Then you can lookup via the UrlTitle and use the real one in the page title or wherever.</p>\n" }, { "answer_id": 266834, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 1, "selected": false, "text": "<p>Solution 2 is the typical approach of those... some refinements are possible, eg. turning apostrophes into nothing instead of a dash, for readability. Typically you will want to store the munged-for-URL-validity version of the title in the database as well as the ‘real’ title, so you can select the item using an indexed SELECT WHERE.</p>\n\n<p>However. There is no actual illegal character in a URL path part, as long as you encode it appropriately. For example a space, hash or slash can be encoded as %20, %23 or %2F. This way it is possible to encode <em>any</em> string into a URL part, so you can SELECT it back out of the database by actual, unchanged title.</p>\n\n<p>There are a few potential problems with this depending on your web framework though. For example anything based on CGI will be unable to tell the difference between an encoded %2F and a real /, and some frameworks/deployments can have difficulty with Unicode characters.</p>\n\n<p>Alternatively, a simple and safe solution is to include the primary key in the URL, using the titled parts purely for making the address nicer. eg.:</p>\n\n<pre><code>http://www.example.com/x/category-name/subcat-name/article-name/348254863\n</code></pre>\n\n<p>This is how eg. Amazon does it. It does have the advantage that you can change the title in the database and have the URL with the old title redirect automatically to the new one.</p>\n" }, { "answer_id": 266847, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I suggest doing what wordpress does - strip out small words and replce illegal characters with dashes (max 1 dash) then let the user correct the URL if they want to. It better for SEO to make the URL configurable.</p>\n" }, { "answer_id": 266898, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 3, "selected": true, "text": "<p>I myself prefer _ to - for readability reasons ( you put an underline on it and the <code>_</code>'s virtually go_away ) , if you're going to strip spaces. </p>\n\n<p>You may want to try casting extended characters, ie, ü , to close-ascii equivelants where possible, ie:</p>\n\n<p>ü -> u </p>\n\n<p>However, in my experience the biggest problem with <em>Actual</em> SEO related issues, is not that the URL contains all the lovely text, its that when people <em>change</em> the text in the link, all your SEO work turns to crap because you now have <em>DEADLINKS</em> in the indexes. </p>\n\n<p>For this, I would suggest what stackoverflow do, and have a numeric part which references a constant entity, and totally ignore the rest of the text ( and/or update it when its wrong ) </p>\n\n<p>Also, the grossly hericichial nature just makes for bad usability by humans. Humans <em>hate</em> long urls. Copy pasting them sucks and they're just more prone to breaking. If you can subdivide it into lower teirs, ie </p>\n\n<pre><code>/article/1/Some_Article_Title_Here\n/article/1/Section/5/Section_Title_Here\n/section/19023/Section_Title_here ( == above link ) \n</code></pre>\n\n<p>That way the only time you need to do voodoo magic is when the numbered article actually <em>has</em> been deleted, at which time you use the text part as a search string to try find the real article or something like it. </p>\n" }, { "answer_id": 271568, "author": "Armstrongest", "author_id": 26931, "author_profile": "https://Stackoverflow.com/users/26931", "pm_score": 1, "selected": false, "text": "<p>In case anyone is interested. This is the route (oooh... punny) I'm taking: </p>\n\n<pre><code>Route r = new Route(\"{country}/{lang}/Article/{id}/{title}/\", new NFRouteHandler(\"OneArticle\"));\nRoute r2 = new Route(\"{country}/{lang}/Section/{id}-{subid}/{title}/\", new NFRouteHandler(\"ArticlesInSubcategory\"));\nRoute r3 = new Route(\"{country}/{lang}/Section/{id}/{title}/\", new NFRouteHandler(\"ArticlesByCategory\"));\n</code></pre>\n\n<p>This offers me the ability to do urls like so:</p>\n\n<ul>\n<li>site.com/ca/en/Article/123/my-life-and-health</li>\n<li>site.com/ca/en/Section/12-3/Health-Issues</li>\n<li>site.com/ca/en/Section/12/</li>\n</ul>\n" }, { "answer_id": 273767, "author": "Armstrongest", "author_id": 26931, "author_profile": "https://Stackoverflow.com/users/26931", "pm_score": 1, "selected": false, "text": "<p>When cleaning URLs, here's a method I'm using to replace accented characters:</p>\n\n<pre><code>private static string anglicized(this string urlpart) {\n string before = \"àÀâÂäÄáÁéÉèÈêÊëËìÌîÎïÏòÒôÔöÖùÙûÛüÜçÇ’ñ\";\n string after = \"aAaAaAaAeEeEeEeEiIiIiIoOoOoOuUuUuUcC'n\";\n\n string cleaned = urlpart;\n\n for (int i = 0; i &lt; avantConversion.Length; i++ ) {\n\n cleaned = Regex.Replace(urlpart, before[i].ToString(), after[i].ToString());\n }\n\n return cleaned;\n\n // Here's some for Spanish : ÁÉÍÑÓÚÜ¡¿áéíñóúü\"\n\n}\n</code></pre>\n\n<p>Don't know if it's the most efficient Regex, but it is certainly effective. It's an extension method so to call it you simply put the method in a Static Class and do somthing like this:</p>\n\n<pre><code>string articleTitle = \"My Article about café and the letters àâäá\";\nstring cleaned = articleTitle.anglicized();\n\n// replace spaces with dashes\ncleaned = Regex.Replace( cleaned, \"[^A-Za-z0-9- ]\", \"\");\n\n// strip all illegal characters like punctuation\ncleaned = Regex.Replace( cleaned, \" +\", \"-\").ToLower();\n\n// returns \"my-article-about-cafe-and-the-letters-aaaa\"\n</code></pre>\n\n<p>Of course, you could combine it into one method called \"CleanUrl\" or something but that's up to you.</p>\n" }, { "answer_id": 929431, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>As a client user, not a Web designer, I find Firefox sometimes breaks the URL when it tries to replace \"illegal\" characters with usable ones. For example, FF replaces ~ with %7E. That never loads for me. I can't understand why the HTML editors and browsers don't simply agree not to accept characters other than A-Z and 0-9. If certain scripts need %, ?, and such, change the scripting applications so they will work with alpha numeric.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26931/" ]
I've seen a lot of discussion on URL Routing, and LOTS of great suggestions... but in the real world, one thing I haven't seen discussed are: 1. Creating Friendly URLs **with Spaces and illegal characters** 2. Querying the DB Say you're building a Medical site, which has **Articles** with a **Category** and optional **Subcategory**. (1 to many). ( **Could've used any example, but the medical field has lots of long words**) --- **Example Categories/Sub/Article Structure:** --------------------------------------------- 1. **Your General Health (Category)** * *Natural Health **(Subcategory)*** 1. Your body's immune system and why it needs help. **(Article)** 2. Are plants and herbs really the solution? 3. Should I eat fortified foods? * Homeopathic Medicine 1. What's homeopathic medicine? * *Healthy Eating* 1. Should you drink 10 cups of coffee per day? 2. Are Organic Vegetables worth it? 3. Is Burger King® evil? 4. Is "French café" or American coffee healthier? 2. **Diseases & Conditions (Category)** * *Auto-Immune Disorders **(Subcategory)*** 1. The #1 killer of people is some disease 2. How to get help * *Genetic Conditions* 1. Preventing Spina Bifida before pregnancy. 2. Are you predisposed to live a long time? 3. **Dr. FooBar's personal suggestions (Category)** 1. My thoughts on Herbal medicine & natural remedies **(Article - no subcategory)** 2. Why should you care about your health? 3. It IS possible to eat right and have a good diet. 4. Has bloodless surgery come of age? --- In a structure like this, you're going to have some **LOOONG URLs** if you go: /{Category}/{subcategory}/{Article Title} In addition, there are numerous **illegal characters**, like # ! ? ' é " etc. **SO, the QUESTION(S) ARE:** ---------------------------- 1. How would you handle illegal characters and Spaces? (Pros and Cons?) 2. Would you handle getting this from the Database * In other words, would you **trust the DB to find** the Item, passing the title, **or pull all the titles** and find the key in code to get the key to pass to the Database (two calls to the database)? *note: I always see nice pretty examples like /products/beverages/Short-Product-Name/ how about handling some ugly examples ^\_^*
I myself prefer \_ to - for readability reasons ( you put an underline on it and the `_`'s virtually go\_away ) , if you're going to strip spaces. You may want to try casting extended characters, ie, ü , to close-ascii equivelants where possible, ie: ü -> u However, in my experience the biggest problem with *Actual* SEO related issues, is not that the URL contains all the lovely text, its that when people *change* the text in the link, all your SEO work turns to crap because you now have *DEADLINKS* in the indexes. For this, I would suggest what stackoverflow do, and have a numeric part which references a constant entity, and totally ignore the rest of the text ( and/or update it when its wrong ) Also, the grossly hericichial nature just makes for bad usability by humans. Humans *hate* long urls. Copy pasting them sucks and they're just more prone to breaking. If you can subdivide it into lower teirs, ie ``` /article/1/Some_Article_Title_Here /article/1/Section/5/Section_Title_Here /section/19023/Section_Title_here ( == above link ) ``` That way the only time you need to do voodoo magic is when the numbered article actually *has* been deleted, at which time you use the text part as a search string to try find the real article or something like it.
266,761
<p>I'm pivoting data in MS SQL stored procedure. Columns which are pivoted are dynamically created using stored procedure parameter (for exampe: "location1,location2,location3,") so number of columns which will be generated is not known. Output should look like (where locations are taken from stored procedure parameter):</p> <blockquote> <p>OrderTime | Location1 | Location2 | Location3</p> </blockquote> <p>Any chance that this can be used in LINQ to SQL? When I dragged this procedure to dbml file it shows that this procedure returns int type.</p> <p>Columns I use from <code>log_sales</code> table are:</p> <ul> <li>Location (various location which I'm pivoting),</li> <li>Charge (amount of money)</li> <li>OrderTime</li> </ul> <p>Stored procedure:</p> <pre><code>CREATE PROCEDURE [dbo].[proc_StatsDay] @columns NVARCHAR(64) AS DECLARE @SQL_PVT1 NVARCHAR(512), @SQL_PVT2 NVARCHAR(512), @SQL_FULL NVARCHAR(4000); SET @SQL_PVT1 = 'SELECT OrderTime, ' + LEFT(@columns,LEN(@columns)-1) +' FROM (SELECT ES.Location, CONVERT(varchar(10), ES.OrderTime, 120),ES.Charge FROM dbo.log_sales ES ) AS D (Location,OrderTime,Charge) PIVOT (SUM (D.Charge) FOR D.Location IN ('; SET @SQL_PVT2 = ') )AS PVT ORDER BY OrderTime DESC'; SET @SQL_FULL = @SQL_PVT1 + LEFT(@columns,LEN(@columns)-1) + @SQL_PVT2; EXEC sp_executesql @SQL_FULL, N'@columns NVARCHAR(64)',@columns = @columns </code></pre> <p>In dbml <code>designer.cs</code> file my stored procedure part of code:</p> <pre><code>[Function(Name="dbo.proc_StatsDay")] public int proc_EasyDay([Parameter(DbType="NVarChar(64)")] string columns) { IExecuteResult result = this.ExecuteMethodCall(this,((MethodInfo)MethodInfo.GetCurrentMethod())), columns); return ((int)(result.ReturnValue)); } </code></pre>
[ { "answer_id": 266810, "author": "bovium", "author_id": 11135, "author_profile": "https://Stackoverflow.com/users/11135", "pm_score": 0, "selected": false, "text": "<p>You can create your linq object for access after your returned dataset.</p>\n\n<p>But would that really be of any use. Linq are usefull for typesafe calls and not dynamic results. You would not know what to look for compile time.</p>\n" }, { "answer_id": 266860, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<p>You'd run your select statement</p>\n\n<pre><code>SELECT ES.Location, DateAdd(dd, DateDiff(dd, 0, ES.OrderTime), 0),ES.Charge\nFROM dbo.log_sales ES\n</code></pre>\n\n<p>and capture the result to a type like this</p>\n\n<pre><code>public class LogSale\n{\n public string Location {get;set;}\n public DateTime OrderDate {get;set;}\n public decimal Charge {get;set;}\n}\n</code></pre>\n\n<p>And then \"pivot\"/organize that in memory</p>\n\n<pre><code>List&lt;LogSale&gt; source = LoadData();\nvar pivot = source\n .GroupBy(ls =&gt; ls.OrderDate)\n .OrderBy(g =&gt; g.Key)\n .Select(g =&gt; new {\n Date = g.Key,\n Details = g\n .GroupBy(ls =&gt; ls.Location)\n .Select(loc =&gt; new {\n Location = loc.Key,\n Amount = loc.Sum(ls =&gt; ls.Charge)\n })\n });\n</code></pre>\n\n<p>Here's a second pivoty Linq which pushes the data into XML instead of anonymous types.</p>\n\n<pre><code>var pivot = source\n .GroupBy(ls =&gt; ls.OrderDate)\n .OrderBy(g =&gt; g.Key)\n .Select(g =&gt; new XElement(\"Date\",\n new XAttribute(\"Value\", g.key),\n g.GroupBy(ls =&gt; ls.Location)\n .Select(loc =&gt; new XElement(\"Detail\",\n new XAttribute(\"Location\", loc.Key),\n new XAttribute(\"Amount\", loc.Sum(ls =&gt; ls.Charge))\n ))\n ));\n</code></pre>\n" }, { "answer_id": 266928, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 3, "selected": true, "text": "<p>Assuming truly dire dynamic need, you could use <a href=\"http://msdn.microsoft.com/en-us/library/bb361109.aspx\" rel=\"nofollow noreferrer\">DataContext.ExecuteQuery</a></p>\n\n<p>Just whip up a type that will cover the result space (the property names must match the column names in the query):</p>\n\n<pre><code>public class DynamicResult\n{\n public DateTime OrderDate {get;set;}\n public decimal? Location1 {get;set;}\n public decimal? Location2 {get;set;}\n//..\n public decimal? Location100 {get;set;}\n}\n</code></pre>\n\n<p>Then call</p>\n\n<pre><code>IEnumerable&lt;DynamicResult&gt; result =\n myDataContext.ExecuteQuery&lt;DynamicResult&gt;(commandString, param1);\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23280/" ]
I'm pivoting data in MS SQL stored procedure. Columns which are pivoted are dynamically created using stored procedure parameter (for exampe: "location1,location2,location3,") so number of columns which will be generated is not known. Output should look like (where locations are taken from stored procedure parameter): > > OrderTime | Location1 | Location2 | > Location3 > > > Any chance that this can be used in LINQ to SQL? When I dragged this procedure to dbml file it shows that this procedure returns int type. Columns I use from `log_sales` table are: * Location (various location which I'm pivoting), * Charge (amount of money) * OrderTime Stored procedure: ``` CREATE PROCEDURE [dbo].[proc_StatsDay] @columns NVARCHAR(64) AS DECLARE @SQL_PVT1 NVARCHAR(512), @SQL_PVT2 NVARCHAR(512), @SQL_FULL NVARCHAR(4000); SET @SQL_PVT1 = 'SELECT OrderTime, ' + LEFT(@columns,LEN(@columns)-1) +' FROM (SELECT ES.Location, CONVERT(varchar(10), ES.OrderTime, 120),ES.Charge FROM dbo.log_sales ES ) AS D (Location,OrderTime,Charge) PIVOT (SUM (D.Charge) FOR D.Location IN ('; SET @SQL_PVT2 = ') )AS PVT ORDER BY OrderTime DESC'; SET @SQL_FULL = @SQL_PVT1 + LEFT(@columns,LEN(@columns)-1) + @SQL_PVT2; EXEC sp_executesql @SQL_FULL, N'@columns NVARCHAR(64)',@columns = @columns ``` In dbml `designer.cs` file my stored procedure part of code: ``` [Function(Name="dbo.proc_StatsDay")] public int proc_EasyDay([Parameter(DbType="NVarChar(64)")] string columns) { IExecuteResult result = this.ExecuteMethodCall(this,((MethodInfo)MethodInfo.GetCurrentMethod())), columns); return ((int)(result.ReturnValue)); } ```
Assuming truly dire dynamic need, you could use [DataContext.ExecuteQuery](http://msdn.microsoft.com/en-us/library/bb361109.aspx) Just whip up a type that will cover the result space (the property names must match the column names in the query): ``` public class DynamicResult { public DateTime OrderDate {get;set;} public decimal? Location1 {get;set;} public decimal? Location2 {get;set;} //.. public decimal? Location100 {get;set;} } ``` Then call ``` IEnumerable<DynamicResult> result = myDataContext.ExecuteQuery<DynamicResult>(commandString, param1); ```
266,771
<p>I'm trying to figure out a way to detect files that are not opened for editing but have nevertheless been modified locally. <code>p4 fstat</code> returns a value <code>headModTime</code> for any given file, but this is the change time in the depot, which should not be equal to the filesystem's <code>stat</code> last modified time.</p> <p>I'm hoping that there exists a more lightweight operation than backing up the original file, forcing a sync of the file, and then running a diff. Ideas?</p>
[ { "answer_id": 266813, "author": "grieve", "author_id": 34329, "author_profile": "https://Stackoverflow.com/users/34329", "pm_score": 6, "selected": true, "text": "<p>From: <a href=\"http://answers.perforce.com/articles/KB/3481/?q=disconnected&amp;l=en_US&amp;fs=Search&amp;pn=1\" rel=\"noreferrer\">http://answers.perforce.com/articles/KB/3481/?q=disconnected&amp;l=en_US&amp;fs=Search&amp;pn=1</a></p>\n\n<p>See step 2 specifically:</p>\n\n<hr>\n\n<p>2 . Next, open for \"edit\" any files that have changed:</p>\n\n<pre><code>p4 diff -se //myclient/... | p4 -x - edit\n</code></pre>\n\n<p>p4 diff -se returns the names of depot files whose corresponding client file differs in any way from the clients #have revision.</p>\n" }, { "answer_id": 308051, "author": "Epu", "author_id": 30015, "author_profile": "https://Stackoverflow.com/users/30015", "pm_score": 2, "selected": false, "text": "<p>From the working disconnected article, using p4win you can also select the folder/files in question and select 'file menu->more->check consistency' which basically does the 'p4 diff -se' and 'p4 diff -sd', and prompts the user to resolve the inconsistencies.</p>\n" }, { "answer_id": 1013591, "author": "Cristian Diaconescu", "author_id": 11545, "author_profile": "https://Stackoverflow.com/users/11545", "pm_score": 5, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/9272/finding-untracked-files-in-a-perforce-tree\">This SO question</a> gives a way to do this in the P4V GUI:</p>\n<blockquote>\n<p>In the Jan 2009 version of P4V, you can right-click on any folder in your workspace tree and click &quot;reconcile offline work...&quot;</p>\n<p>This will do a little processing then bring up a split-tree view of files that are not checked out but have differences from the depot version, or not checked in at all. There may even be a few other categories it brings up.</p>\n<p>You can right-click on files in this view and check them out, add them, or even revert them.</p>\n</blockquote>\n<p>Later EDIT:</p>\n<p>In the &quot;Reconcile...&quot; window, you can click 'Advanced Reconcile' and be presented with a two-pane, folder hierarchy diff window which is especially useful for finding files you need to add.</p>\n<p>PROS: This whole P4V feature is more user-friendly than the command-line version (because it allows utmost granularity in selecting what to reconcile)</p>\n<p>CONS: It is in dire need of a subversion/git/hg <code>.ignore</code>-like list, to spare you the pain of manually skipping all the dll's and other cruft in your projects.</p>\n" }, { "answer_id": 4949431, "author": "engtech", "author_id": 175, "author_profile": "https://Stackoverflow.com/users/175", "pm_score": 0, "selected": false, "text": "<p>Here's a unix solution that has worked very well for me.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/9272/finding-untracked-files-in-a-perforce-tree/100126#100126\">How to find untracked files in a Perforce tree? (analogue of svn status)</a></p>\n" }, { "answer_id": 13127491, "author": "Colonel Panic", "author_id": 284795, "author_profile": "https://Stackoverflow.com/users/284795", "pm_score": 2, "selected": false, "text": "<p>As of Perforce version 2012.1, use the command line commands <code>p4 status</code> and <code>p4 reconcile</code></p>\n<p><a href=\"http://www.perforce.com/perforce/r12.2/manuals/cmdref/status.html\" rel=\"nofollow noreferrer\">http://www.perforce.com/perforce/r12.2/manuals/cmdref/status.html</a></p>\n<blockquote>\n<p>The <code>p4 status</code> command finds unopened files in a client's workspace and detects the following three types of inconsistencies between your workspace and the depot:</p>\n<ol>\n<li>Files present in the depot, present in your have list, but missing from your workspace. By default, these files are then opened for\ndelete.</li>\n<li>Files present in your workspace, but missing on the depot. By default, these files are opened for add.</li>\n<li>Files modified in your workspace that are not open for edit. By default, these files are opened for edit.</li>\n</ol>\n</blockquote>\n<p><a href=\"http://www.perforce.com/perforce/r12.1/manuals/cmdref/reconcile.html\" rel=\"nofollow noreferrer\">http://www.perforce.com/perforce/r12.1/manuals/cmdref/reconcile.html</a></p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ]
I'm trying to figure out a way to detect files that are not opened for editing but have nevertheless been modified locally. `p4 fstat` returns a value `headModTime` for any given file, but this is the change time in the depot, which should not be equal to the filesystem's `stat` last modified time. I'm hoping that there exists a more lightweight operation than backing up the original file, forcing a sync of the file, and then running a diff. Ideas?
From: <http://answers.perforce.com/articles/KB/3481/?q=disconnected&l=en_US&fs=Search&pn=1> See step 2 specifically: --- 2 . Next, open for "edit" any files that have changed: ``` p4 diff -se //myclient/... | p4 -x - edit ``` p4 diff -se returns the names of depot files whose corresponding client file differs in any way from the clients #have revision.
266,776
<p>We have some methods that call File.Copy, File.Delete, File.Exists, etc. How can we test these methods without actually hitting the file system?</p> <p>I consider myself a unit testing n00b, so any advice is appreciated.</p>
[ { "answer_id": 266783, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>If you absolutely have to do this, <a href=\"http://www.typemock.com/\" rel=\"nofollow noreferrer\">Typemock Isolator</a> is your friend.</p>\n\n<p>I can't say I've used it myself, and I would try to design my way around it instead, but it'll do the job as far as I'm aware.</p>\n" }, { "answer_id": 266788, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 2, "selected": false, "text": "<p>I would <a href=\"http://code.google.com/p/moq/\" rel=\"nofollow noreferrer\">use Moq for this</a>. You would have to create an interface and a class that proxies to the real thing so you could have Moq create an instance of your proxy (a mocked instance) but its the best way to test these sorts of things.</p>\n" }, { "answer_id": 266795, "author": "bovium", "author_id": 11135, "author_profile": "https://Stackoverflow.com/users/11135", "pm_score": 0, "selected": false, "text": "<p>You can use a mock framework for this and it will create a fake copy of the File object and you can inject the file in the system under test.</p>\n\n<p>I will recommend Rhino Mock.</p>\n" }, { "answer_id": 266804, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 6, "selected": true, "text": "<pre><code>public interface IFile {\n void Copy(string source, string dest);\n void Delete(string fn);\n bool Exists(string fn);\n}\n\npublic class FileImpl : IFile {\n public virtual void Copy(string source, string dest) { File.Copy(source, dest); }\n public virtual void Delete(string fn) { File.Delete(fn); }\n public virtual bool Exists(string fn) { return File.Exists(fn); }\n}\n\n[Test]\npublic void TestMySystemCalls() {\n var filesystem = new Moq.Mock&lt;IFile&gt;();\n var obj = new ClassUnderTest(filesystem);\n filesystem.Expect(fs =&gt; fs.Exists(\"MyFile.txt\")).Return(true);\n obj.CheckIfFileExists(); // doesn't hit the underlying filesystem!!!\n}\n</code></pre>\n" }, { "answer_id": 266883, "author": "Jamie Penney", "author_id": 68230, "author_profile": "https://Stackoverflow.com/users/68230", "pm_score": 0, "selected": false, "text": "<p>I tend to create an interface in most of my projects called IFileController that has all file operations on it. This can have the basic ones, plus any methods that the .NET framework doesn't provide that deal with files.</p>\n\n<p>Using a dependency injection framework, you can get an instance of IFileController without knowing exactly what type it is, and use it without needing to mess around with mocking framework types. This makes everything much more testable, and as a bonus you can change the file storage mechanism without changing your code at all.</p>\n\n<p>On the down side, any new developers need to be told about this interface, otherwise they will just use the .NET methods directly.</p>\n" }, { "answer_id": 1391017, "author": "Steve Guidi", "author_id": 131407, "author_profile": "https://Stackoverflow.com/users/131407", "pm_score": 0, "selected": false, "text": "<p>I maintain the <a href=\"http://jolt.codeplex.com\" rel=\"nofollow noreferrer\">Jolt.NET</a> project on CodePlex, which contains a library to generate such interfaces and their implementations for you. Please refer to the <a href=\"http://jolt.codeplex.com/Wiki/View.aspx?title=Jolt.Testing\" rel=\"nofollow noreferrer\">Jolt.Testing</a> library for more information.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681/" ]
We have some methods that call File.Copy, File.Delete, File.Exists, etc. How can we test these methods without actually hitting the file system? I consider myself a unit testing n00b, so any advice is appreciated.
``` public interface IFile { void Copy(string source, string dest); void Delete(string fn); bool Exists(string fn); } public class FileImpl : IFile { public virtual void Copy(string source, string dest) { File.Copy(source, dest); } public virtual void Delete(string fn) { File.Delete(fn); } public virtual bool Exists(string fn) { return File.Exists(fn); } } [Test] public void TestMySystemCalls() { var filesystem = new Moq.Mock<IFile>(); var obj = new ClassUnderTest(filesystem); filesystem.Expect(fs => fs.Exists("MyFile.txt")).Return(true); obj.CheckIfFileExists(); // doesn't hit the underlying filesystem!!! } ```
266,794
<p>I'm trying to submit a form with javascript. Firefox works fine but IE complains that "Object doesn't support this property or method" on the submit line of this function:</p> <pre><code>function submitPGV(formName, action) { var gvString = ""; pgVisibilities.each(function(pair) { gvString += pair.key + ":" + pair.value + ","; }); $('pgv_input').value = gvString; var form = $(formName); form.action = action; form.submit(); } </code></pre> <p>Called here:</p> <pre><code>&lt;a href="javascript:submitPGV('ProductGroupVisibility','config/productgroupvis/save')"&gt; </code></pre> <p>Here's the form:</p> <pre><code>&lt;form id="ProductGroupVisibility" action="save" method="post"&gt; &lt;input type="hidden" name="ows_gv..PGV" id="pgv_input" value=""/&gt; &lt;/form&gt; </code></pre> <p>Any ideas?</p>
[ { "answer_id": 266822, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "<p>Are you sure you have your JavaScript library loaded? (jQuery or Prototype)</p>\n\n<p>It worked for me in IE7 with Prototype.</p>\n\n<p>Try:</p>\n\n<pre><code>alert($('ProductGroupVisibility').id)\n</code></pre>\n\n<p>See if you get an error.</p>\n" }, { "answer_id": 266866, "author": "Brian", "author_id": 13264, "author_profile": "https://Stackoverflow.com/users/13264", "pm_score": 4, "selected": true, "text": "<p>Try checking the type of the element IE is selecting:</p>\n\n<pre><code>// For getting element with id you must use # \nalert( typeof( $( '#ProductGroupVisibility' )));\n</code></pre>\n\n<p>It is possible there is something else on the page with that ID that IE selects before the form.</p>\n" }, { "answer_id": 266889, "author": "Lance McNearney", "author_id": 25549, "author_profile": "https://Stackoverflow.com/users/25549", "pm_score": 1, "selected": false, "text": "<p>What javascript framework are you using? If it's jQuery I think you'll need to add # to your id:</p>\n\n<pre><code>$('#ProductGroupVisibility').submit();\n</code></pre>\n" }, { "answer_id": 266920, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": false, "text": "<p>What <code>name</code> does your <code>&lt;input type=\"submit\"&gt;</code> have? </p>\n\n<p>If you called it \"submit\", you have overridden the <code>form.submit()</code> function, much the same way an input called \"foo\" would generate a <code>form.foo</code> property. That would explain the behavior. </p>\n" }, { "answer_id": 10212666, "author": "Ben", "author_id": 1341805, "author_profile": "https://Stackoverflow.com/users/1341805", "pm_score": 2, "selected": false, "text": "<p>beware of any inputs in the form with name='submit', they break the javascript .submit() functionality!</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34859/" ]
I'm trying to submit a form with javascript. Firefox works fine but IE complains that "Object doesn't support this property or method" on the submit line of this function: ``` function submitPGV(formName, action) { var gvString = ""; pgVisibilities.each(function(pair) { gvString += pair.key + ":" + pair.value + ","; }); $('pgv_input').value = gvString; var form = $(formName); form.action = action; form.submit(); } ``` Called here: ``` <a href="javascript:submitPGV('ProductGroupVisibility','config/productgroupvis/save')"> ``` Here's the form: ``` <form id="ProductGroupVisibility" action="save" method="post"> <input type="hidden" name="ows_gv..PGV" id="pgv_input" value=""/> </form> ``` Any ideas?
Try checking the type of the element IE is selecting: ``` // For getting element with id you must use # alert( typeof( $( '#ProductGroupVisibility' ))); ``` It is possible there is something else on the page with that ID that IE selects before the form.
266,800
<p>I have a C# class the returns a List, using System.Collections.Generic Lists not F# List</p> <p>I want to iterate though the list to find a object or not find it. Here is how I would do it in C#. How would I accomplish the similar thing in F#</p> <pre><code>foreach (AperioCaseObj caseObj in CaseList) { if (caseObj.CaseId == "") { } else { } } </code></pre>
[ { "answer_id": 267047, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 3, "selected": true, "text": "<p>See this example for iterating an integer generic list:</p>\n\n<pre><code>#light\nopen System.Collections.Generic\n\nlet genList = new List&lt;int&gt;()\n\ngenList.Add(1)\ngenList.Add(2)\ngenList.Add(3)\n\n\nfor x in genList do\n printf \"%d\" x\n</code></pre>\n" }, { "answer_id": 267431, "author": "J D", "author_id": 13924, "author_profile": "https://Stackoverflow.com/users/13924", "pm_score": 2, "selected": false, "text": "<p>That kind of list is also an IEnumerable so you can still use F#'s <code>for elt in list do</code> notation:</p>\n\n<pre><code>for caseObj in CaseList do\n if caseObj.CaseId = \"\" then\n ...\n else\n ...\n</code></pre>\n" }, { "answer_id": 267448, "author": "Derek Slager", "author_id": 18636, "author_profile": "https://Stackoverflow.com/users/18636", "pm_score": 3, "selected": false, "text": "<pre><code>match Seq.tryfind ((=) \"\") caseList with\n None -&gt; print_string \"didn't find it\"\n | Some s -&gt; printfn \"found it: %s\" s\n</code></pre>\n" }, { "answer_id": 268310, "author": "simonuk", "author_id": 28136, "author_profile": "https://Stackoverflow.com/users/28136", "pm_score": 0, "selected": false, "text": "<p>Using tryfind to match against a field in a record:</p>\n\n<pre><code>type foo = {\n id : int;\n value : string;\n}\n\nlet foos = [{id=1; value=\"one\"}; {id=2; value=\"two\"}; {id=3; value=\"three\"} ]\n\n// This will return Some foo\nList.tryfind (fun f -&gt; f.id = 2) foos\n\n// This will return None\nList.tryfind (fun f -&gt; f.id = 4) foos\n</code></pre>\n" }, { "answer_id": 271256, "author": "user20155", "author_id": 20155, "author_profile": "https://Stackoverflow.com/users/20155", "pm_score": 2, "selected": false, "text": "<p>A C# list is called a ResizeArray in F#. To find an element within the ResizeArray you can use \"tryfind\" or \"find\". TryFind returns an option type (Option), which means if the element is not found, you'll get None. Find on the other hand raises an exception if it doesn't find the element you're looking for</p>\n\n<hr>\n\n<pre><code>let foo() = \n match CaseList |&gt; ResizeArray.tryfind (fun x -&gt; x.caseObj = \"imlookingforyou\") with\n |None -&gt; print-string \"\"notfound\n |Some(case ) -&gt; printfn \"found %s\" case \n</code></pre>\n\n<p>or</p>\n\n<pre><code>let foo()\n try\n let case = ResizeArray.find (fun x -&gt; x.caseObj = \"imlookingforyou\") \n printfn \"found %s\" case \n\n with\n | _ -&gt; print_string \"not found\"\n</code></pre>\n\n<hr>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72123/" ]
I have a C# class the returns a List, using System.Collections.Generic Lists not F# List I want to iterate though the list to find a object or not find it. Here is how I would do it in C#. How would I accomplish the similar thing in F# ``` foreach (AperioCaseObj caseObj in CaseList) { if (caseObj.CaseId == "") { } else { } } ```
See this example for iterating an integer generic list: ``` #light open System.Collections.Generic let genList = new List<int>() genList.Add(1) genList.Add(2) genList.Add(3) for x in genList do printf "%d" x ```
266,803
<p>I have several static factory patterns in my PHP library. However, memory footprint is getting out of hand and we want to reduce the number of files required during execution time. Here is an example of where we are today:</p> <pre><code>require_once('Car.php'); require_once('Truck.php'); abstract class Auto { // ... some stuff ... public static function Create($type) { switch ($type) { case 'Truck': return new Truck(); break; case 'Car': default: return new Car(); break; } } } </code></pre> <p>This is undesirable because Car.php AND Truck.php will need to be included even though only one or the other may be needed. As far as I know, require/include and their ..._once variation include libraries at the same scope as it's call. Is this true?</p> <p>If so, I believe this would lead to a memory leak:</p> <pre><code> abstract class Auto { // ... some stuff ... public static function Create($type) { switch ($type) { case 'Truck': require_once('Truck.php'); return new Truck(); break; case 'Car': default: require_once('Car.php'); return new Car(); break; } } } </code></pre> <p>It looks to me that in the 2nd example, multiple calls to Create() would lead to multiple requires because of the scope of the call even though the require_once flavor is used.</p> <p>Is this true? What is the best way to include libraries dynamically in php in an example such as these?</p> <p>Thanks!</p>
[ { "answer_id": 266820, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 4, "selected": true, "text": "<p>The Autoload facility is often seen as Evil, but it works at these task quite nicely. </p>\n\n<p>If you can get a good filesystem &lt;-> classname mapping so you can, when given a class to provide, find it, then it will save you overhead and only load classes when needed. </p>\n\n<p>It works for static classes too, so once the static class is in scope, it doesn't need to even call the \"is file included yet\" test of require once, because the Class is already in the symbol table. </p>\n\n<p>Then you can just create </p>\n\n<pre><code>require(\"autoloader.php\"); \n$x = new Car(); \n$x = new Bike(); \n</code></pre>\n\n<p>and it will just bring them in when needed. </p>\n\n<p>See <a href=\"http://nz2.php.net/__autoload\" rel=\"noreferrer\">Php.net/__autoload</a> for more details. </p>\n" }, { "answer_id": 266826, "author": "Davide Gualano", "author_id": 28582, "author_profile": "https://Stackoverflow.com/users/28582", "pm_score": 1, "selected": false, "text": "<p>Take a look to the <a href=\"http://it2.php.net/autoload\" rel=\"nofollow noreferrer\">__autoload() function</a>.</p>\n" }, { "answer_id": 266828, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 2, "selected": false, "text": "<p>I would recommend using the <a href=\"http://php.net/autoload\" rel=\"nofollow noreferrer\">autoloader</a>.</p>\n\n<p>That is, don't use <code>require_once()</code> to require either subclass, but allows the autoloader to call a function which can load the referenced class when you call <code>new Truck()</code> or <code>new Car()</code>.</p>\n\n<p>As for the memory leak question, no, <code>require_once</code> is not scoped by the code block.</p>\n" }, { "answer_id": 266922, "author": "Zak", "author_id": 2112692, "author_profile": "https://Stackoverflow.com/users/2112692", "pm_score": 0, "selected": false, "text": "<p>The point of the require_once function is that no matter the scope, you won't include a file twice and redefine a class causing a PHP error. So no worries about memory leaks, if the require_once is hit, the class def goes in the global symbol table only one time.</p>\n\n<p>But aside from that, yeah use autoloader.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20176/" ]
I have several static factory patterns in my PHP library. However, memory footprint is getting out of hand and we want to reduce the number of files required during execution time. Here is an example of where we are today: ``` require_once('Car.php'); require_once('Truck.php'); abstract class Auto { // ... some stuff ... public static function Create($type) { switch ($type) { case 'Truck': return new Truck(); break; case 'Car': default: return new Car(); break; } } } ``` This is undesirable because Car.php AND Truck.php will need to be included even though only one or the other may be needed. As far as I know, require/include and their ...\_once variation include libraries at the same scope as it's call. Is this true? If so, I believe this would lead to a memory leak: ``` abstract class Auto { // ... some stuff ... public static function Create($type) { switch ($type) { case 'Truck': require_once('Truck.php'); return new Truck(); break; case 'Car': default: require_once('Car.php'); return new Car(); break; } } } ``` It looks to me that in the 2nd example, multiple calls to Create() would lead to multiple requires because of the scope of the call even though the require\_once flavor is used. Is this true? What is the best way to include libraries dynamically in php in an example such as these? Thanks!
The Autoload facility is often seen as Evil, but it works at these task quite nicely. If you can get a good filesystem <-> classname mapping so you can, when given a class to provide, find it, then it will save you overhead and only load classes when needed. It works for static classes too, so once the static class is in scope, it doesn't need to even call the "is file included yet" test of require once, because the Class is already in the symbol table. Then you can just create ``` require("autoloader.php"); $x = new Car(); $x = new Bike(); ``` and it will just bring them in when needed. See [Php.net/\_\_autoload](http://nz2.php.net/__autoload) for more details.
266,805
<p>I'm trying to get rid of some spurious warnings in my SSIS Progress log. I'm getting a bunch of warnings about unused columns in tasks that use raw SQL to do their work. I have a Data Flow responsible for archiving data in a staging table prior to loading new data. The Data Flow looks like this:</p> <pre><code>+--------------------+ | OLEDB Source task: | | read staging table | +--------------------+ | | +---------------------------+ | OLEDB Command task: | | upsert into history table | +---------------------------+ | | +---------------------------+ | OLEDB Command task: | | delete from staging table | +---------------------------+ </code></pre> <p>my 'upsert' task is something like:</p> <pre><code>-------------------------------------- -- update existing rows first... update history set field1 = s.field1 ... from history h inner join staging s on h.id = s.id where h.last_edit_date &lt;&gt; s.last_edit_date -- only update changed records -- ... then insert new rows insert into history select s.* from staging s join history h on h.id = s.id where h.id is null -------------------------------------- </code></pre> <p>The cleanup task is also a SQL command:</p> <pre><code>-------------------------------------- delete from staging -------------------------------------- </code></pre> <p>Since the upsert task doesn't have any output column definitions, I'm getting a bunch of warnings in the log:</p> <pre><code>[DTS.Pipeline] Warning: The output column "product_id" (693) on output "OLE DB Source Output" (692) and component "read Piv_product staging table" (681) is not subsequently used in the Data Flow task. Removing this unused output column can increase Data Flow task performance. </code></pre> <p>How can I eliminate the references to those columns? I've tried dropping in a few different tasks, but none of them seem to let me 'swallow' the input columns and suppress them from the task's output. I'd like to keep my logs clean so I only see real problems. Any ideas?</p> <p>Thanks!</p>
[ { "answer_id": 266816, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 3, "selected": false, "text": "<p>Union All - select only the columns you want to pass through - delete any others.</p>\n\n<p>I thought they were going to address this in the 2008 version to allow columns to be trimmed/suppressed from the pipeline.</p>\n" }, { "answer_id": 267337, "author": "Val", "author_id": 34861, "author_profile": "https://Stackoverflow.com/users/34861", "pm_score": 2, "selected": false, "text": "<p>OK, I got a workaround on the <a href=\"http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=4090954&amp;SiteID=1\" rel=\"nofollow noreferrer\">MSDN forums</a>: </p>\n\n<p>use a Script Component transformation between task 1 and 2; select all the input columns; leave the script body empty. </p>\n\n<p>That consumes the columns, the job processes properly and no warnings are logged. </p>\n\n<p>Still not clear why I need the OLEDB Source at all, since the SQL in task 2 connects to the source tables and does all the work, but when I remove the OLEDB Source the dataflow runs but doesn't process any rows, so the staging table never gets emptied, and then the downstream process to put changed rows in the staging table fails because of PK violations. But that's a problem for another day. This is a bit clunky, but my logs are clean.</p>\n" }, { "answer_id": 273802, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 0, "selected": false, "text": "<p>Looking at your problem again, I think you are using SSIS \"against the grain\". I'm not really following what you are reading out of the staging table, since your upsert doesn't seem to depend on anything in a particular row, nor does the cleanup.</p>\n\n<p>It would seem to me that the cleanup would run once for every row, but that doesn't really make sense.</p>\n\n<p>DataFlows are not typically used to perform bulk actions for each row coming down the pipeline. If you are using a pipeline UPSERTs get handled using Lookup (or third-party TableDifference) components and then a spli in the pipeline to an OLEDB Destination (BULK INSERT) and either an OLEDB Command (once per UPDATE) or another OLDEB Destination for an \"UPDATE staging table\".</p>\n\n<p>Normally, I would do this with a DataFlow to load the staging table without any split, then a single Execute SQL Task in the control flow to perform everything else in straight SQL UPSERT (like you have) by calling an SP.</p>\n\n<p>OLEDBCommand is useful if you DON'T want to have a staging table, and instead read a flat file and want to execute an UPDATE or INSERT using a Lookup component or something. But it will be called for every row in the pipeline.</p>\n" }, { "answer_id": 306393, "author": "AdamH", "author_id": 21081, "author_profile": "https://Stackoverflow.com/users/21081", "pm_score": 0, "selected": false, "text": "<p>Your <code>DataFlow Task</code> should finish with the \"upsert\". Then back in the control flow create an <code>Execute SQL Task</code> for the delete from staging. Link your <code>DataFlow Task</code> to your exec sql.</p>\n\n<p>I don't use a 3rd party tool for my upserts, but do as Cade suggests, which is to split your dataflow into new records that just head to a <code>OLE DB Destination</code> (or similar), and update records that can go to your oledb command for updates. You can split the flow using a merge-join or a lookup.</p>\n" }, { "answer_id": 323115, "author": "Dale Wright", "author_id": 11523, "author_profile": "https://Stackoverflow.com/users/11523", "pm_score": 1, "selected": false, "text": "<p>The warnings in your pipeline are caused by columns being selected in your data source that aren't being used in any subsequent Tasks.</p>\n\n<p>The easy fix to this is double click on your data source. In your case (OLEDB Source task: |\n| read staging table) Then click on columns and deselect any columns that you don't need in any of your future task items.</p>\n\n<p>This will remove those warnings from your progress log.</p>\n\n<p>However reading your item above and as explained by other answers you aren't using the columns from the Source Task in the subsequent items so it can simply be removed.</p>\n" }, { "answer_id": 43402775, "author": "Ardalan Shahgholi", "author_id": 2063547, "author_profile": "https://Stackoverflow.com/users/2063547", "pm_score": 1, "selected": false, "text": "<p>I have the same question. I have received a good answer. You can find it <a href=\"https://stackoverflow.com/questions/42680747/how-can-i-delete-the-columns-in-dataflow-task-in-ssis\">here</a>. </p>\n\n<p>As \"<a href=\"https://stackoverflow.com/users/2568521/mark-wojciechowicz\">Mark Wojciechowicz</a>\" said : </p>\n\n<p>Here are some recommendations for reducing complexity, which will, in turn, improve performance: </p>\n\n<ul>\n<li><strong>Reduce the columns at the source.</strong> If you are selecting columns that\nare not subsequently used in any way, then remove them from the query\nor uncheck them from the source component. Removing columns in this way removes them from the buffer, which will occupy less memory.</li>\n<li><strong>Reduce the number of components in the dataflow</strong>. Very long dataflows are easy to create, a pain to test and even harder to maintain. Dataflows are expecting a <em>unit of work</em>, i.e. a data stream from here to there with a few things in the middle. This is where dataflows shine, in fact, they protect themselves from complexity with memory limitations and a max number of threads. It is better to divide the work into separate dataflows or stored procs. You could stage the data into a table and read it twice, rather than use a multicast, for example.</li>\n<li><strong>Use the database.</strong> SSIS is as much an orchestration tool as it is a data-moving tool. I have often found that using simple dataflows to <em>stage the data</em>, followed by calls to stored procedures to <em>process the data</em>, always out-performs an all-in-one dataflow.</li>\n<li><strong>Increase the number of times you write the data</strong>. This is completely counter intuitive, but if you process data in smaller sets of operations, it is faster running and easier to test. Given a clean slate, I will often design an ETL to write data from the source to a staging table, perform a cleansing step from the stage table to another, optionally, add a conforming step to combine data from different sources to yet another table and, finally, a last step to load a target table. Note that each source is pushed to its own target table and later combined, leveraging the database. The first and last steps are set up to run fast and avoid locking or blocking at either end. </li>\n<li><strong>Bulk Load</strong>. The prior step really does well, when you insure that bulk loading is happening. This can be a tricky thing, but generally you can get there by using \"fast load\" in the OLEDB destination and by <em>never</em> using the oledb command. Removing indexes and re-adding them is faster than loading in place (with few exceptions). </li>\n</ul>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34861/" ]
I'm trying to get rid of some spurious warnings in my SSIS Progress log. I'm getting a bunch of warnings about unused columns in tasks that use raw SQL to do their work. I have a Data Flow responsible for archiving data in a staging table prior to loading new data. The Data Flow looks like this: ``` +--------------------+ | OLEDB Source task: | | read staging table | +--------------------+ | | +---------------------------+ | OLEDB Command task: | | upsert into history table | +---------------------------+ | | +---------------------------+ | OLEDB Command task: | | delete from staging table | +---------------------------+ ``` my 'upsert' task is something like: ``` -------------------------------------- -- update existing rows first... update history set field1 = s.field1 ... from history h inner join staging s on h.id = s.id where h.last_edit_date <> s.last_edit_date -- only update changed records -- ... then insert new rows insert into history select s.* from staging s join history h on h.id = s.id where h.id is null -------------------------------------- ``` The cleanup task is also a SQL command: ``` -------------------------------------- delete from staging -------------------------------------- ``` Since the upsert task doesn't have any output column definitions, I'm getting a bunch of warnings in the log: ``` [DTS.Pipeline] Warning: The output column "product_id" (693) on output "OLE DB Source Output" (692) and component "read Piv_product staging table" (681) is not subsequently used in the Data Flow task. Removing this unused output column can increase Data Flow task performance. ``` How can I eliminate the references to those columns? I've tried dropping in a few different tasks, but none of them seem to let me 'swallow' the input columns and suppress them from the task's output. I'd like to keep my logs clean so I only see real problems. Any ideas? Thanks!
Union All - select only the columns you want to pass through - delete any others. I thought they were going to address this in the 2008 version to allow columns to be trimmed/suppressed from the pipeline.
266,806
<p>Is there any performance reason to declare method parameters final in Java?</p> <p>As in:</p> <pre><code>public void foo(int bar) { ... } </code></pre> <p>Versus:</p> <pre><code>public void foo(final int bar) { ... } </code></pre> <p>Assuming that <code>bar</code> is only read and never modified in <code>foo()</code>.</p>
[ { "answer_id": 266830, "author": "branchgabriel", "author_id": 30807, "author_profile": "https://Stackoverflow.com/users/30807", "pm_score": -1, "selected": false, "text": "<p>Compilers that operate after class loading, such as JIT compilers, can take advantage of final methods. Consequently, methods declared final could have some performance benefit. </p>\n\n<p><a href=\"http://www.javaperformancetuning.com/tips/final.shtml\" rel=\"nofollow noreferrer\">http://www.javaperformancetuning.com/tips/final.shtml</a></p>\n\n<p>Oh and another good resource</p>\n\n<p><a href=\"http://mindprod.com/jgloss/final.html\" rel=\"nofollow noreferrer\">http://mindprod.com/jgloss/final.html</a></p>\n" }, { "answer_id": 266887, "author": "Dobes Vandermeer", "author_id": 399738, "author_profile": "https://Stackoverflow.com/users/399738", "pm_score": 4, "selected": false, "text": "<p>The only benefit to a final parameter is that it can be used in anonymous nested classes. If a parameter is never changed, the compiler will already detect that as part of it's normal operation even without the final modifier. It's pretty rare that bugs are caused by a parameter being unexpectedly assigned - if your methods are big enough to need this level of engineering, make them smaller - methods you call can't change your parameters.</p>\n" }, { "answer_id": 266981, "author": "Robin", "author_id": 21925, "author_profile": "https://Stackoverflow.com/users/21925", "pm_score": 8, "selected": true, "text": "<p>The final keyword does not appear in the class file for local variables and parameters, thus it cannot impact the runtime performance. It's only use is to clarify the coders intent that the variable not be changed (which many consider dubious reason for its usage), and dealing with anonymous inner classes.</p>\n\n<p>There is a lot of argument over whether the final modifier on the method itself has any performance gain since the methods will be inlined by the optimizing compiler at runtime anyway, regardless of the modifier. In this case it should also only be used to restrict the overriding of the method.</p>\n" }, { "answer_id": 10649202, "author": "user1402866", "author_id": 1402866, "author_profile": "https://Stackoverflow.com/users/1402866", "pm_score": -1, "selected": false, "text": "<p>I assume the compiler could possibly remove all private static final variables that has a primitive type, such as int, and inline them directly in the code just like with a C++ macro.</p>\n\n<p>However, i have no clue if this is done in practice, but it could be done in order to save some memory. </p>\n" }, { "answer_id": 29977871, "author": "user666", "author_id": 1334305, "author_profile": "https://Stackoverflow.com/users/1334305", "pm_score": 0, "selected": false, "text": "<p>Just one more point that to above that using non-final local variables declared within the method—the inner class instance may outlive the stack frame, so the local variable might vanish while the inner object is still alive</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18511/" ]
Is there any performance reason to declare method parameters final in Java? As in: ``` public void foo(int bar) { ... } ``` Versus: ``` public void foo(final int bar) { ... } ``` Assuming that `bar` is only read and never modified in `foo()`.
The final keyword does not appear in the class file for local variables and parameters, thus it cannot impact the runtime performance. It's only use is to clarify the coders intent that the variable not be changed (which many consider dubious reason for its usage), and dealing with anonymous inner classes. There is a lot of argument over whether the final modifier on the method itself has any performance gain since the methods will be inlined by the optimizing compiler at runtime anyway, regardless of the modifier. In this case it should also only be used to restrict the overriding of the method.
266,818
<p>I need to see if a string value matches with an object value, but why won't this work?</p> <pre><code>public int countPacks(String flavour) { int counter = 0; for(int index = 0; index &lt; packets.size(); index++) { if (packets.equals(flavour)) { counter ++; } else { System.out.println("You have not entered a correct flavour"); } } return counter; } </code></pre>
[ { "answer_id": 266827, "author": "micro", "author_id": 23275, "author_profile": "https://Stackoverflow.com/users/23275", "pm_score": 2, "selected": false, "text": "<p>You probably mean something like </p>\n\n<pre><code>if (packets.get(index).equals(flavour)) {\n ...\n</code></pre>\n" }, { "answer_id": 266831, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "<p>What is \"packets\"? It's not going to be a string - so how would it equal a string?</p>\n\n<p>I suspect you meant your test to be:</p>\n\n<pre><code>if (packets.get(index).equals(flavour))\n</code></pre>\n\n<p>However you're still going to print out \"You have not entered a correct flavour\" for every packet of the \"wrong\" flavour even if there's one with the right flavour!</p>\n\n<p>I suspect you want to move the error reporting to the end of the method, after the loop, and only execute it if <code>counter == 0</code></p>\n" }, { "answer_id": 266873, "author": "branchgabriel", "author_id": 30807, "author_profile": "https://Stackoverflow.com/users/30807", "pm_score": 0, "selected": false, "text": "<p>You should do it this way to be certian you really are comparing strings in the most foolproof way possible.</p>\n\n<p>I also fixed your loop </p>\n\n<pre><code>public int countPacks(String flavour, List packets)\n {\n int counter = 0;\n for (Iterator iter = packets.iterator(); iter.hasNext();) {\n Map packet = (Map) iter.next();\n\n if (packet.get(\"flavour\").toString().equalsIgnoreCase(flavour)) {\n counter ++;\n }\n else {\n System.out.println(\"You have not entered a correct flavour\");\n }\n } \n return counter; \n }\n</code></pre>\n" }, { "answer_id": 266985, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Assuming packets is a Collection (and you're using JDK 1.5 or greater), you could also just make the method:</p>\n\n<pre><code>public int countPacks(String flavor) {\n int numOccurrences = java.util.Collections.frequency(packets, flavor);\n if(numOccurrences == 0) {\n System.out.println(\"You have not entered a correct flavor\");\n }\n return numOccurrences;\n}\n</code></pre>\n" }, { "answer_id": 269347, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 2, "selected": false, "text": "<p>A problem with methods declared in Object is that there is a lack of static type checking in their use. The same applies to synchronized, where it is common to lock the wrong object.</p>\n\n<p>In this case Object.equals(Object) works with any two objects. You have used the collection, packets, instead of getting an element from it. The important question is not how did this particular bug come about, but how can we prevent it from occurring in the first place.</p>\n\n<p>First of all, use generics and get assign each element for the iteration to a statically typed local:</p>\n\n<pre><code>public int countPacks(String flavour) {\n // [ The field represents a count. ]\n int count = 0;\n for(int index=0; index&lt;packets.size(); ++index) {\n String packet = packets.get(index);\n if (packet.equals(flavour)) {\n ++count;\n }\n } \n // [The error mesage was printed for each non-match.\n // Even this is probably wrong,\n // as it should be valid to have no packs of a valid flavour.\n // Having the message in this method is actually a bit confused.]\n if (count == 0) {\n System.out.println(\"You have not entered a correct flavour\");\n }\n return count; \n}\n</code></pre>\n\n<p>We can further tidy this up using the enhanced for loop.</p>\n\n<pre><code>public int countPacks(String flavour) {\n int count = 0;\n for(String packet : packets) {\n if (packet.equals(flavour)) {\n ++count;\n }\n } \n if (count == 0) {\n System.out.println(\"You have not entered a correct flavour\");\n }\n return count; \n}\n</code></pre>\n\n<p>That looks clearer, but a good programmer knows his/her libraries.</p>\n\n<pre><code>public int countPacks(String flavour) {\n int count = Collections.frequency(packets, flavour);\n if (count == 0) {\n System.out.println(\"You have not entered a correct flavour\");\n }\n return count; \n}\n</code></pre>\n\n<p>You might also consider a <code>Map&lt;String,Integer&gt;</code> instead of the collection.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need to see if a string value matches with an object value, but why won't this work? ``` public int countPacks(String flavour) { int counter = 0; for(int index = 0; index < packets.size(); index++) { if (packets.equals(flavour)) { counter ++; } else { System.out.println("You have not entered a correct flavour"); } } return counter; } ```
What is "packets"? It's not going to be a string - so how would it equal a string? I suspect you meant your test to be: ``` if (packets.get(index).equals(flavour)) ``` However you're still going to print out "You have not entered a correct flavour" for every packet of the "wrong" flavour even if there's one with the right flavour! I suspect you want to move the error reporting to the end of the method, after the loop, and only execute it if `counter == 0`
266,819
<p>Where is the best place to add a method to the integer class in Rails? I'd like to add a <code>to_meters</code> and <code>to_miles</code> methods.</p>
[ { "answer_id": 266840, "author": "Zak", "author_id": 2112692, "author_profile": "https://Stackoverflow.com/users/2112692", "pm_score": 2, "selected": false, "text": "<p>Normally (and logically), integers can't be converted to miles or to meters. It sounds like you may want to create a new class like \"Feet\" or \"inches\" that is initialized with an integer, then contains methods like size_in_miles or size_in_meters. For convenience those methods could return decimal or float types, but you might also want to write a miles class or a meters class.</p>\n\n<p>As an alternate method, you might want to create a static method in your new class that would have a signature like this:</p>\n\n<p><code>Float feetToMiles(integer I)</code></p>\n\n<p>that you would call </p>\n\n<p><code>miles = Feet.feetToMiles(5280);</code></p>\n\n<p>and get <code>miles = 1.0</code></p>\n" }, { "answer_id": 266845, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": "<p>Create your own module/library which you include into scope when you need it to perform this task. </p>\n\n<p>Such as \"requre 'unitCoversions' \" </p>\n\n<p>And Chances are, somebody has already done this if you look hard enough :)</p>\n\n<p>However <em>DONT</em> try modifying the native core class, that will only end in Misery. </p>\n\n<p>( Also, the class you want to extend is 'numeric' , that will apply to both Integers and Floats :) ) </p>\n\n<blockquote>\n <p>Not entirely clear why I shouldn't do this... Rails does this to the string class to great success. </p>\n</blockquote>\n\n<p>Because it <em>can</em> be done doesn't mean it <em>should</em> be done. 'Monkey Patching' as it is known can have all sorts of odd side effects, and they can be an epic failure when done wrong. </p>\n\n<p>Do it when there is no good alternative. </p>\n\n<p>Because if you really wanted to do something daft, you could build an entire framework that <em>ALL</em> it did was monkey patch the core classes. </p>\n\n<p>Just for example, flip databasing on its head. </p>\n\n<pre><code>5.getArtist(); \n10.getEvent(); \n100.getTrack(); \n</code></pre>\n\n<p>etc etc. there is no limit to how many bad ways there are to do that. </p>\n\n<pre><code>\"Bob\".createUser(); \n</code></pre>\n\n<p>misery in a cup. </p>\n\n<p>If you want to do something practical, have a Convert class or function, </p>\n\n<pre><code>convert( 3 , { :from=&gt;:miles, :to=&gt;:meters }); \n</code></pre>\n\n<p>at least you're not polluting the global namespace and core functions that way and it makes more coherent sense. </p>\n" }, { "answer_id": 266867, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": -1, "selected": false, "text": "<p>If you were going to do this, which you shouldn't, then you would put your code into:</p>\n\n<pre><code>config/initializers/add_methods_that_are_naughty_to_numeric.rb\n</code></pre>\n\n<p>Rails would automatically run these for you.</p>\n" }, { "answer_id": 267325, "author": "Cameron Booth", "author_id": 14873, "author_profile": "https://Stackoverflow.com/users/14873", "pm_score": 2, "selected": false, "text": "<p>Why not just:</p>\n\n<pre><code>class Feet\n def self.in_miles(feet)\n feet/5280\n end\nend\n</code></pre>\n\n<p>usage:</p>\n\n<pre><code>Feet.in_miles 2313\n</code></pre>\n\n<p>Or maybe look at it the other way:</p>\n\n<pre><code>class Miles\n def self.from_feet(feet)\n feet/5280\n end\nend\n\nMiles.from_feet 2313\n</code></pre>\n" }, { "answer_id": 270115, "author": "danmayer", "author_id": 27738, "author_profile": "https://Stackoverflow.com/users/27738", "pm_score": 2, "selected": false, "text": "<p>I agree monkey patching should be used with care, but occasionally it just make sense. I really like the helpers that allow you to type 5.days.ago which are part of the active_support library</p>\n\n<p>So some of the other answers might be better in this case, but if you are extending ruby classes we keep all our extensions in lib/extensions/class_name.rb</p>\n\n<p>this way when working on a project it is quick and easy to find and see anything that might be out of the ordinary with standard classes.</p>\n" }, { "answer_id": 271621, "author": "dennisjbell", "author_id": 35394, "author_profile": "https://Stackoverflow.com/users/35394", "pm_score": 5, "selected": true, "text": "<p>If you have your heart set on mucking with the Numeric (or integer, etc) class to get unit conversion, then at least do it logically and with some real value. </p>\n\n<p>First, create a Unit class that stores the unit type (meters,feet, cubits, etc.) and the value on creation. Then add a bunch of methods to Numeric that correspond to the valid values unit can have: these methods will return a Unit object with it's type recorded as the method name. The Unit class would support a bunch of to_* methods that would convert to another unit type with the corresponding unit value. That way, you can do the following command:</p>\n\n<pre><code>&gt;&gt; x = 47.feet.to_meters\n=&gt; 14.3256\n&gt;&gt; x.inspect\n=&gt; #&lt;Unit 0xb795efb8 @value=14.3256, @type=:meter&gt;\n</code></pre>\n\n<p>The best way to handle it would probably be a matrix of conversion types and expressions in the Unit class, then use method_missing to check if a given type can be converted to another type. In the numeric class, use method_missing to ask Unit if it supports the given method as a unit type, and if so, return a unit object of the requested type using the numeric as its value. You could then support adding units and conversions at runtime by adding a register_type and register_conversion class method to Unit that extended the conversion matrix and Numeric would \"automagically\" pick up the ability.</p>\n\n<p>As for where to put it, create a lib/units.rb file, which would also contain the monkey_patch to Numeric, then initialize it in config/environment.rb bu requiring the lib/units.rb file.</p>\n" }, { "answer_id": 15269518, "author": "AJcodez", "author_id": 824377, "author_profile": "https://Stackoverflow.com/users/824377", "pm_score": 0, "selected": false, "text": "<p>Realize the question is old, but I think the clearest way would be to make a Distance class with two attributes <code>@length</code> and <code>@unit</code>. </p>\n\n<p>You'd just need a conversion hash, probably as a class variable of Distance:</p>\n\n<pre><code>class Distance\n\n @@conversion_rates = {\n meters: {\n feet: 3.28084,\n meters: 1.0\n }\n }\n\n def to(new_unit)\n new_length = @length * @@conversion_rates[@unit][new_unit]\n Distance.new( new_length, new_unit ) \n end\n\nend\n</code></pre>\n\n<p>And it would look kinda like:</p>\n\n<pre><code>Distance.new(3, :meters).to(:feet)\n</code></pre>\n\n<p>which i honestly think looks better than</p>\n\n<pre><code>3.meters.to_feet\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6705/" ]
Where is the best place to add a method to the integer class in Rails? I'd like to add a `to_meters` and `to_miles` methods.
If you have your heart set on mucking with the Numeric (or integer, etc) class to get unit conversion, then at least do it logically and with some real value. First, create a Unit class that stores the unit type (meters,feet, cubits, etc.) and the value on creation. Then add a bunch of methods to Numeric that correspond to the valid values unit can have: these methods will return a Unit object with it's type recorded as the method name. The Unit class would support a bunch of to\_\* methods that would convert to another unit type with the corresponding unit value. That way, you can do the following command: ``` >> x = 47.feet.to_meters => 14.3256 >> x.inspect => #<Unit 0xb795efb8 @value=14.3256, @type=:meter> ``` The best way to handle it would probably be a matrix of conversion types and expressions in the Unit class, then use method\_missing to check if a given type can be converted to another type. In the numeric class, use method\_missing to ask Unit if it supports the given method as a unit type, and if so, return a unit object of the requested type using the numeric as its value. You could then support adding units and conversions at runtime by adding a register\_type and register\_conversion class method to Unit that extended the conversion matrix and Numeric would "automagically" pick up the ability. As for where to put it, create a lib/units.rb file, which would also contain the monkey\_patch to Numeric, then initialize it in config/environment.rb bu requiring the lib/units.rb file.
266,825
<p>I'd like to format a duration in seconds using a pattern like H:MM:SS. The current utilities in java are designed to format a time but not a duration.</p>
[ { "answer_id": 266846, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 8, "selected": true, "text": "<p>If you're using a version of Java prior to 8... you can use <a href=\"http://joda-time.sourceforge.net/\" rel=\"noreferrer\">Joda Time</a> and <a href=\"http://joda-time.sourceforge.net/api-release/org/joda/time/format/PeriodFormatter.html\" rel=\"noreferrer\"><code>PeriodFormatter</code></a>. If you've really got a duration (i.e. an elapsed amount of time, with no reference to a calendar system) then you should probably be using <code>Duration</code> for the most part - you can then call <code>toPeriod</code> (specifying whatever <code>PeriodType</code> you want to reflect whether 25 hours becomes 1 day and 1 hour or not, etc) to get a <code>Period</code> which you can format.</p>\n\n<p>If you're using Java 8 or later: I'd normally suggest using <code>java.time.Duration</code> to represent the duration. You can then call <code>getSeconds()</code> or the like to obtain an integer for standard string formatting as per bobince's answer if you need to - although you should be careful of the situation where the duration is negative, as you probably want a <em>single</em> negative sign in the output string. So something like:</p>\n\n<pre><code>public static String formatDuration(Duration duration) {\n long seconds = duration.getSeconds();\n long absSeconds = Math.abs(seconds);\n String positive = String.format(\n \"%d:%02d:%02d\",\n absSeconds / 3600,\n (absSeconds % 3600) / 60,\n absSeconds % 60);\n return seconds &lt; 0 ? \"-\" + positive : positive;\n}\n</code></pre>\n\n<p>Formatting this way is <em>reasonably</em> simple, if annoyingly manual. For <em>parsing</em> it becomes a harder matter in general... You could still use Joda Time even with Java 8 if you want to, of course.</p>\n" }, { "answer_id": 266970, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 8, "selected": false, "text": "<p>If you don't want to drag in libraries, it's simple enough to do yourself using a Formatter, or related shortcut eg. given integer number of seconds s:</p>\n\n<pre><code> String.format(\"%d:%02d:%02d\", s / 3600, (s % 3600) / 60, (s % 60));\n</code></pre>\n" }, { "answer_id": 6090189, "author": "Mihai Vasilache", "author_id": 453178, "author_profile": "https://Stackoverflow.com/users/453178", "pm_score": 5, "selected": false, "text": "<pre><code>long duration = 4 * 60 * 60 * 1000;\nSimpleDateFormat sdf = new SimpleDateFormat(\"HH:mm:ss.SSS\", Locale.getDefault());\nlog.info(\"Duration: \" + sdf.format(new Date(duration - TimeZone.getDefault().getRawOffset())));\n</code></pre>\n" }, { "answer_id": 18633466, "author": "Gili Nachum", "author_id": 121956, "author_profile": "https://Stackoverflow.com/users/121956", "pm_score": 7, "selected": false, "text": "<p>I use Apache common's <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-3.0/org/apache/commons/lang3/time/DurationFormatUtils.html\" rel=\"noreferrer\">DurationFormatUtils</a> like so: </p>\n\n<pre><code>DurationFormatUtils.formatDuration(millis, \"**H:mm:ss**\", true);\n</code></pre>\n" }, { "answer_id": 22776038, "author": "sbclint", "author_id": 3483443, "author_profile": "https://Stackoverflow.com/users/3483443", "pm_score": 2, "selected": false, "text": "<p>This is a working option.</p>\n\n<pre><code>public static String showDuration(LocalTime otherTime){ \n DateTimeFormatter df = DateTimeFormatter.ISO_LOCAL_TIME;\n LocalTime now = LocalTime.now();\n System.out.println(\"now: \" + now);\n System.out.println(\"otherTime: \" + otherTime);\n System.out.println(\"otherTime: \" + otherTime.format(df));\n\n Duration span = Duration.between(otherTime, now);\n LocalTime fTime = LocalTime.ofNanoOfDay(span.toNanos());\n String output = fTime.format(df);\n\n System.out.println(output);\n return output;\n}\n</code></pre>\n\n<p>Call the method with</p>\n\n<pre><code>System.out.println(showDuration(LocalTime.of(9, 30, 0, 0)));\n</code></pre>\n\n<p>Produces something like:</p>\n\n<pre><code>otherTime: 09:30\notherTime: 09:30:00\n11:31:27.463\n11:31:27.463\n</code></pre>\n" }, { "answer_id": 28131899, "author": "patrick", "author_id": 2263885, "author_profile": "https://Stackoverflow.com/users/2263885", "pm_score": 3, "selected": false, "text": "<p>This might be kind of hacky, but it is a good solution if one is bent on accomplishing this using Java 8's <code>java.time</code>:</p>\n\n<pre><code>import java.time.Duration;\nimport java.time.LocalDateTime;\nimport java.time.format.DateTimeFormatter;\nimport java.time.format.DateTimeFormatterBuilder;\nimport java.time.temporal.ChronoField;\nimport java.time.temporal.Temporal;\nimport java.time.temporal.TemporalAccessor;\nimport java.time.temporal.TemporalField;\nimport java.time.temporal.UnsupportedTemporalTypeException;\n\npublic class TemporalDuration implements TemporalAccessor {\n private static final Temporal BASE_TEMPORAL = LocalDateTime.of(0, 1, 1, 0, 0);\n\n private final Duration duration;\n private final Temporal temporal;\n\n public TemporalDuration(Duration duration) {\n this.duration = duration;\n this.temporal = duration.addTo(BASE_TEMPORAL);\n }\n\n @Override\n public boolean isSupported(TemporalField field) {\n if(!temporal.isSupported(field)) return false;\n long value = temporal.getLong(field)-BASE_TEMPORAL.getLong(field);\n return value!=0L;\n }\n\n @Override\n public long getLong(TemporalField field) {\n if(!isSupported(field)) throw new UnsupportedTemporalTypeException(new StringBuilder().append(field.toString()).toString());\n return temporal.getLong(field)-BASE_TEMPORAL.getLong(field);\n }\n\n public Duration getDuration() {\n return duration;\n }\n\n @Override\n public String toString() {\n return dtf.format(this);\n }\n\n private static final DateTimeFormatter dtf = new DateTimeFormatterBuilder()\n .optionalStart()//second\n .optionalStart()//minute\n .optionalStart()//hour\n .optionalStart()//day\n .optionalStart()//month\n .optionalStart()//year\n .appendValue(ChronoField.YEAR).appendLiteral(\" Years \").optionalEnd()\n .appendValue(ChronoField.MONTH_OF_YEAR).appendLiteral(\" Months \").optionalEnd()\n .appendValue(ChronoField.DAY_OF_MONTH).appendLiteral(\" Days \").optionalEnd()\n .appendValue(ChronoField.HOUR_OF_DAY).appendLiteral(\" Hours \").optionalEnd()\n .appendValue(ChronoField.MINUTE_OF_HOUR).appendLiteral(\" Minutes \").optionalEnd()\n .appendValue(ChronoField.SECOND_OF_MINUTE).appendLiteral(\" Seconds\").optionalEnd()\n .toFormatter();\n\n}\n</code></pre>\n" }, { "answer_id": 39344834, "author": "Pavel_H", "author_id": 1682715, "author_profile": "https://Stackoverflow.com/users/1682715", "pm_score": 3, "selected": false, "text": "<p>Here is one more sample how to format duration.\nNote that this sample shows both positive and negative duration as positive duration.</p>\n\n<pre><code>import static java.time.temporal.ChronoUnit.DAYS;\nimport static java.time.temporal.ChronoUnit.HOURS;\nimport static java.time.temporal.ChronoUnit.MINUTES;\nimport static java.time.temporal.ChronoUnit.SECONDS;\n\nimport java.time.Duration;\n\npublic class DurationSample {\n public static void main(String[] args) {\n //Let's say duration of 2days 3hours 12minutes and 46seconds\n Duration d = Duration.ZERO.plus(2, DAYS).plus(3, HOURS).plus(12, MINUTES).plus(46, SECONDS);\n\n //in case of negative duration\n if(d.isNegative()) d = d.negated();\n\n //format DAYS HOURS MINUTES SECONDS \n System.out.printf(\"Total duration is %sdays %shrs %smin %ssec.\\n\", d.toDays(), d.toHours() % 24, d.toMinutes() % 60, d.getSeconds() % 60);\n\n //or format HOURS MINUTES SECONDS \n System.out.printf(\"Or total duration is %shrs %smin %sec.\\n\", d.toHours(), d.toMinutes() % 60, d.getSeconds() % 60);\n\n //or format MINUTES SECONDS \n System.out.printf(\"Or total duration is %smin %ssec.\\n\", d.toMinutes(), d.getSeconds() % 60);\n\n //or format SECONDS only \n System.out.printf(\"Or total duration is %ssec.\\n\", d.getSeconds());\n }\n}\n</code></pre>\n" }, { "answer_id": 40594963, "author": "Meno Hochschild", "author_id": 2491410, "author_profile": "https://Stackoverflow.com/users/2491410", "pm_score": 0, "selected": false, "text": "<p>My library <a href=\"https://github.com/MenoData/Time4J\" rel=\"nofollow noreferrer\">Time4J</a> offers a pattern-based solution (similar to <code>Apache DurationFormatUtils</code>, but more flexible):</p>\n\n<pre><code>Duration&lt;ClockUnit&gt; duration =\n Duration.of(-573421, ClockUnit.SECONDS) // input in seconds only\n .with(Duration.STD_CLOCK_PERIOD); // performs normalization to h:mm:ss-structure\nString fs = Duration.formatter(ClockUnit.class, \"+##h:mm:ss\").format(duration);\nSystem.out.println(fs); // output =&gt; -159:17:01\n</code></pre>\n\n<p>This code demonstrates the capabilities to handle hour overflow and sign handling, see also the API of duration-formatter <a href=\"http://time4j.net/javadoc-en/net/time4j/Duration.Formatter.html#ofPattern-java.lang.Class-java.lang.String-\" rel=\"nofollow noreferrer\">based on pattern</a>.</p>\n" }, { "answer_id": 43578628, "author": "Bax", "author_id": 868975, "author_profile": "https://Stackoverflow.com/users/868975", "pm_score": 2, "selected": false, "text": "<pre><code>String duration(Temporal from, Temporal to) {\n final StringBuilder builder = new StringBuilder();\n for (ChronoUnit unit : new ChronoUnit[]{YEARS, MONTHS, WEEKS, DAYS, HOURS, MINUTES, SECONDS}) {\n long amount = unit.between(from, to);\n if (amount == 0) {\n continue;\n }\n builder.append(' ')\n .append(amount)\n .append(' ')\n .append(unit.name().toLowerCase());\n from = from.plus(amount, unit);\n }\n return builder.toString().trim();\n}\n</code></pre>\n" }, { "answer_id": 44343699, "author": "Ole V.V.", "author_id": 5772882, "author_profile": "https://Stackoverflow.com/users/5772882", "pm_score": 6, "selected": false, "text": "<p>This is easier since Java 9. A <code>Duration</code> still isn’t formattable, but methods for getting the hours, minutes and seconds are added, which makes the task somewhat more straightforward:</p>\n\n<pre><code> LocalDateTime start = LocalDateTime.of(2019, Month.JANUARY, 17, 15, 24, 12);\n LocalDateTime end = LocalDateTime.of(2019, Month.JANUARY, 18, 15, 43, 33);\n Duration diff = Duration.between(start, end);\n String hms = String.format(\"%d:%02d:%02d\", \n diff.toHours(), \n diff.toMinutesPart(), \n diff.toSecondsPart());\n System.out.println(hms);\n</code></pre>\n\n<p>The output from this snippet is:</p>\n\n<blockquote>\n <p>24:19:21</p>\n</blockquote>\n" }, { "answer_id": 44797053, "author": "mksteve", "author_id": 5129715, "author_profile": "https://Stackoverflow.com/users/5129715", "pm_score": 3, "selected": false, "text": "<p>How about the following function, which returns either \n+H:MM:SS\nor\n+H:MM:SS.sss</p>\n\n<pre><code>public static String formatInterval(final long interval, boolean millisecs )\n{\n final long hr = TimeUnit.MILLISECONDS.toHours(interval);\n final long min = TimeUnit.MILLISECONDS.toMinutes(interval) %60;\n final long sec = TimeUnit.MILLISECONDS.toSeconds(interval) %60;\n final long ms = TimeUnit.MILLISECONDS.toMillis(interval) %1000;\n if( millisecs ) {\n return String.format(\"%02d:%02d:%02d.%03d\", hr, min, sec, ms);\n } else {\n return String.format(\"%02d:%02d:%02d\", hr, min, sec );\n }\n}\n</code></pre>\n" }, { "answer_id": 49628638, "author": "YourBestBet", "author_id": 571856, "author_profile": "https://Stackoverflow.com/users/571856", "pm_score": -1, "selected": false, "text": "<p>in scala, no library needed:</p>\n\n<pre><code>def prettyDuration(str:List[String],seconds:Long):List[String]={\n seconds match {\n case t if t &lt; 60 =&gt; str:::List(s\"${t} seconds\")\n case t if (t &gt;= 60 &amp;&amp; t&lt; 3600 ) =&gt; List(s\"${t / 60} minutes\"):::prettyDuration(str, t%60)\n case t if (t &gt;= 3600 &amp;&amp; t&lt; 3600*24 ) =&gt; List(s\"${t / 3600} hours\"):::prettyDuration(str, t%3600)\n case t if (t&gt;= 3600*24 ) =&gt; List(s\"${t / (3600*24)} days\"):::prettyDuration(str, t%(3600*24))\n }\n}\nval dur = prettyDuration(List.empty[String], 12345).mkString(\"\")\n</code></pre>\n" }, { "answer_id": 51091602, "author": "lauhub", "author_id": 1011366, "author_profile": "https://Stackoverflow.com/users/1011366", "pm_score": 4, "selected": false, "text": "<p>This answer only uses <code>Duration</code> methods and works with Java 8 :</p>\n<pre><code>public static String format(Duration d) {\n long days = d.toDays();\n d = d.minusDays(days);\n long hours = d.toHours();\n d = d.minusHours(hours);\n long minutes = d.toMinutes();\n d = d.minusMinutes(minutes);\n long seconds = d.getSeconds() ;\n return \n (days == 0?&quot;&quot;:days+&quot; days,&quot;)+ \n (hours == 0?&quot;&quot;:hours+&quot; hours,&quot;)+ \n (minutes == 0?&quot;&quot;:minutes+&quot; minutes,&quot;)+ \n (seconds == 0?&quot;&quot;:seconds+&quot; seconds,&quot;);\n}\n</code></pre>\n" }, { "answer_id": 52992235, "author": "dpoetzsch", "author_id": 3594403, "author_profile": "https://Stackoverflow.com/users/3594403", "pm_score": -1, "selected": false, "text": "<p>In Scala, building up on YourBestBet's solution but simplified:</p>\n\n<pre><code>def prettyDuration(seconds: Long): List[String] = seconds match {\n case t if t &lt; 60 =&gt; List(s\"${t} seconds\")\n case t if t &lt; 3600 =&gt; s\"${t / 60} minutes\" :: prettyDuration(t % 60)\n case t if t &lt; 3600*24 =&gt; s\"${t / 3600} hours\" :: prettyDuration(t % 3600)\n case t =&gt; s\"${t / (3600*24)} days\" :: prettyDuration(t % (3600*24))\n}\n\nval dur = prettyDuration(12345).mkString(\", \") // =&gt; 3 hours, 25 minutes, 45 seconds\n</code></pre>\n" }, { "answer_id": 54794030, "author": "ctg", "author_id": 6157999, "author_profile": "https://Stackoverflow.com/users/6157999", "pm_score": 4, "selected": false, "text": "<p>There's a fairly simple and (IMO) elegant approach, at least for durations of less than 24 hours:</p>\n\n<p><code>DateTimeFormatter.ISO_LOCAL_TIME.format(value.addTo(LocalTime.of(0, 0)))</code></p>\n\n<p>Formatters need a temporal object to format, so you can create one by adding the duration to a LocalTime of 00:00 (i.e. midnight). This will give you a LocalTime representing the duration from midnight to that time, which is then easy to format in standard HH:mm:ss notation. This has the advantage of not needing an external library, and uses the java.time library to do the calculation, rather than manually calculating the hours, minutes and seconds.</p>\n" }, { "answer_id": 62466864, "author": "Stephen", "author_id": 37193, "author_profile": "https://Stackoverflow.com/users/37193", "pm_score": -1, "selected": false, "text": "<p>In scala (I saw some other attempts, and wasn't impressed):</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>def formatDuration(duration: Duration): String = {\n import duration._ // get access to all the members ;)\n f\"$toDaysPart $toHoursPart%02d:$toMinutesPart%02d:$toSecondsPart%02d:$toMillisPart%03d\"\n}\n</code></pre>\n\n<p>Looks horrible yes? Well that's why we use IDEs to write this stuff so that the method calls (<code>$toHoursPart</code> etc) are a different color.</p>\n\n<p>The <code>f\"...\"</code> is a <code>printf</code>/<code>String.format</code> style string interpolator (which is what allows the <code>$</code> code injection to work)\nGiven an output of <code>1 14:06:32.583</code>, the <code>f</code> interpolated string would be equivalent to <code>String.format(\"1 %02d:%02d:%02d.%03d\", 14, 6, 32, 583)</code></p>\n" }, { "answer_id": 62702984, "author": "ipserc", "author_id": 12701130, "author_profile": "https://Stackoverflow.com/users/12701130", "pm_score": 1, "selected": false, "text": "<p>using this func</p>\n<pre><code>private static String strDuration(long duration) {\n int ms, s, m, h, d;\n double dec;\n double time = duration * 1.0;\n\n time = (time / 1000.0);\n dec = time % 1;\n time = time - dec;\n ms = (int)(dec * 1000);\n\n time = (time / 60.0);\n dec = time % 1;\n time = time - dec;\n s = (int)(dec * 60);\n\n time = (time / 60.0);\n dec = time % 1;\n time = time - dec;\n m = (int)(dec * 60);\n\n time = (time / 24.0);\n dec = time % 1;\n time = time - dec;\n h = (int)(dec * 24);\n \n d = (int)time;\n \n return (String.format(&quot;%d d - %02d:%02d:%02d.%03d&quot;, d, h, m, s, ms));\n}\n</code></pre>\n" }, { "answer_id": 63711661, "author": "Sergei Maleev", "author_id": 12761967, "author_profile": "https://Stackoverflow.com/users/12761967", "pm_score": 3, "selected": false, "text": "<p>I'm not sure that is you want, but check this Android helper class</p>\n<pre><code>import android.text.format.DateUtils\n</code></pre>\n<p>For example: <code>DateUtils.formatElapsedTime()</code></p>\n<p><a href=\"/questions/tagged/android\" class=\"post-tag\" title=\"show questions tagged &#39;android&#39;\" rel=\"tag\">android</a> <a href=\"/questions/tagged/date\" class=\"post-tag\" title=\"show questions tagged &#39;date&#39;\" rel=\"tag\">date</a> <a href=\"/questions/tagged/duration\" class=\"post-tag\" title=\"show questions tagged &#39;duration&#39;\" rel=\"tag\">duration</a> <a href=\"/questions/tagged/elapsedtime\" class=\"post-tag\" title=\"show questions tagged &#39;elapsedtime&#39;\" rel=\"tag\">elapsedtime</a></p>\n" }, { "answer_id": 65501046, "author": "Arvind Kumar Avinash", "author_id": 10819573, "author_profile": "https://Stackoverflow.com/users/10819573", "pm_score": 3, "selected": false, "text": "<p>You can use <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html\" rel=\"noreferrer\"><code>java.time.Duration</code></a> which is modelled on <a href=\"https://en.wikipedia.org/wiki/ISO_8601\" rel=\"noreferrer\">ISO-8601 standards</a> and was introduced with <em>Java-8</em> as part of <a href=\"https://jcp.org/aboutJava/communityprocess/pfd/jsr310/JSR-310-guide.html\" rel=\"noreferrer\">JSR-310 implementation</a>. With <em>Java-9</em> some more convenience methods were introduced.</p>\n<p><strong>Demo:</strong></p>\n<pre><code>import java.time.Duration;\nimport java.time.LocalDateTime;\nimport java.time.Month;\n\npublic class Main {\n public static void main(String[] args) {\n LocalDateTime startDateTime = LocalDateTime.of(2020, Month.DECEMBER, 10, 15, 20, 25);\n LocalDateTime endDateTime = LocalDateTime.of(2020, Month.DECEMBER, 10, 18, 24, 30);\n\n Duration duration = Duration.between(startDateTime, endDateTime);\n // Default format\n System.out.println(duration);\n\n // Custom format\n // ####################################Java-8####################################\n String formattedElapsedTime = String.format(&quot;%02d:%02d:%02d&quot;, duration.toHours() % 24,\n duration.toMinutes() % 60, duration.toSeconds() % 60);\n System.out.println(formattedElapsedTime);\n // ##############################################################################\n\n // ####################################Java-9####################################\n formattedElapsedTime = String.format(&quot;%02d:%02d:%02d&quot;, duration.toHoursPart(), duration.toMinutesPart(),\n duration.toSecondsPart());\n System.out.println(formattedElapsedTime);\n // ##############################################################################\n }\n}\n</code></pre>\n<p><strong>Output:</strong></p>\n<pre><code>PT3H4M5S\n03:04:05\n03:04:05\n</code></pre>\n<p>Learn about the modern date-time API from <strong><a href=\"https://docs.oracle.com/javase/tutorial/datetime/index.html\" rel=\"noreferrer\">Trail: Date Time</a></strong>.</p>\n<ul>\n<li>For any reason, if you have to stick to Java 6 or Java 7, you can use <a href=\"http://www.threeten.org/threetenbp/\" rel=\"noreferrer\"><em><strong>ThreeTen-Backport</strong></em></a> which backports most of the <em>java.time</em> functionality to Java 6 &amp; 7.</li>\n<li>If you are working for an Android project and your Android API level is still not compliant with Java-8, check <a href=\"https://developer.android.com/studio/write/java8-support-table\" rel=\"noreferrer\">Java 8+ APIs available through desugaring</a> and <a href=\"https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project\">How to use ThreeTenABP in Android Project</a>.</li>\n</ul>\n" }, { "answer_id": 65586659, "author": "stanley", "author_id": 14947476, "author_profile": "https://Stackoverflow.com/users/14947476", "pm_score": 3, "selected": false, "text": "<p>There is yet another way to make it for java8. But it works if duration is no longer than 24 hours</p>\n<pre><code>public String formatDuration(Duration duration) {\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(&quot;h:mm.SSS&quot;);\n return LocalTime.ofNanoOfDay(duration.toNanos()).format(formatter);\n}\n</code></pre>\n" }, { "answer_id": 66066413, "author": "sschrass", "author_id": 1087479, "author_profile": "https://Stackoverflow.com/users/1087479", "pm_score": 0, "selected": false, "text": "<p>Looking at all those calculations, it may is helpful that most of the Units (Hours, Minutes, etc.) have a <code>.toFooPart()</code> convenience method.</p>\n<p>E.g.</p>\n<pre><code>Duration.ofMinutes(110L).toMinutesPart() == 50\n</code></pre>\n<p>Read: the minutes elapsed to the next value of the parent unit (Hour).</p>\n" }, { "answer_id": 69717677, "author": "Graham Lea", "author_id": 243104, "author_profile": "https://Stackoverflow.com/users/243104", "pm_score": 2, "selected": false, "text": "<p>Here's a one-liner for converting a <code>java.time.Duration</code> to a nice string in Kotlin:</p>\n<pre><code>duration.run {\n &quot;%d:%02d:%02d.%03d&quot;.format(toHours(), toMinutesPart(), toSecondsPart(), toMillisPart())\n}\n</code></pre>\n<p>Example output:\n<code>120:56:03.004</code></p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'd like to format a duration in seconds using a pattern like H:MM:SS. The current utilities in java are designed to format a time but not a duration.
If you're using a version of Java prior to 8... you can use [Joda Time](http://joda-time.sourceforge.net/) and [`PeriodFormatter`](http://joda-time.sourceforge.net/api-release/org/joda/time/format/PeriodFormatter.html). If you've really got a duration (i.e. an elapsed amount of time, with no reference to a calendar system) then you should probably be using `Duration` for the most part - you can then call `toPeriod` (specifying whatever `PeriodType` you want to reflect whether 25 hours becomes 1 day and 1 hour or not, etc) to get a `Period` which you can format. If you're using Java 8 or later: I'd normally suggest using `java.time.Duration` to represent the duration. You can then call `getSeconds()` or the like to obtain an integer for standard string formatting as per bobince's answer if you need to - although you should be careful of the situation where the duration is negative, as you probably want a *single* negative sign in the output string. So something like: ``` public static String formatDuration(Duration duration) { long seconds = duration.getSeconds(); long absSeconds = Math.abs(seconds); String positive = String.format( "%d:%02d:%02d", absSeconds / 3600, (absSeconds % 3600) / 60, absSeconds % 60); return seconds < 0 ? "-" + positive : positive; } ``` Formatting this way is *reasonably* simple, if annoyingly manual. For *parsing* it becomes a harder matter in general... You could still use Joda Time even with Java 8 if you want to, of course.
266,849
<p>I'm conducting experiments regarding e-mail spam. One of these experiments require sending mail thru Tor. Since I'm using Python and smtplib for my experiments, I'm looking for a way to use the Tor proxy (or other method) to perform that mail sending. Ideas how this can be done?</p>
[ { "answer_id": 266846, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 8, "selected": true, "text": "<p>If you're using a version of Java prior to 8... you can use <a href=\"http://joda-time.sourceforge.net/\" rel=\"noreferrer\">Joda Time</a> and <a href=\"http://joda-time.sourceforge.net/api-release/org/joda/time/format/PeriodFormatter.html\" rel=\"noreferrer\"><code>PeriodFormatter</code></a>. If you've really got a duration (i.e. an elapsed amount of time, with no reference to a calendar system) then you should probably be using <code>Duration</code> for the most part - you can then call <code>toPeriod</code> (specifying whatever <code>PeriodType</code> you want to reflect whether 25 hours becomes 1 day and 1 hour or not, etc) to get a <code>Period</code> which you can format.</p>\n\n<p>If you're using Java 8 or later: I'd normally suggest using <code>java.time.Duration</code> to represent the duration. You can then call <code>getSeconds()</code> or the like to obtain an integer for standard string formatting as per bobince's answer if you need to - although you should be careful of the situation where the duration is negative, as you probably want a <em>single</em> negative sign in the output string. So something like:</p>\n\n<pre><code>public static String formatDuration(Duration duration) {\n long seconds = duration.getSeconds();\n long absSeconds = Math.abs(seconds);\n String positive = String.format(\n \"%d:%02d:%02d\",\n absSeconds / 3600,\n (absSeconds % 3600) / 60,\n absSeconds % 60);\n return seconds &lt; 0 ? \"-\" + positive : positive;\n}\n</code></pre>\n\n<p>Formatting this way is <em>reasonably</em> simple, if annoyingly manual. For <em>parsing</em> it becomes a harder matter in general... You could still use Joda Time even with Java 8 if you want to, of course.</p>\n" }, { "answer_id": 266970, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 8, "selected": false, "text": "<p>If you don't want to drag in libraries, it's simple enough to do yourself using a Formatter, or related shortcut eg. given integer number of seconds s:</p>\n\n<pre><code> String.format(\"%d:%02d:%02d\", s / 3600, (s % 3600) / 60, (s % 60));\n</code></pre>\n" }, { "answer_id": 6090189, "author": "Mihai Vasilache", "author_id": 453178, "author_profile": "https://Stackoverflow.com/users/453178", "pm_score": 5, "selected": false, "text": "<pre><code>long duration = 4 * 60 * 60 * 1000;\nSimpleDateFormat sdf = new SimpleDateFormat(\"HH:mm:ss.SSS\", Locale.getDefault());\nlog.info(\"Duration: \" + sdf.format(new Date(duration - TimeZone.getDefault().getRawOffset())));\n</code></pre>\n" }, { "answer_id": 18633466, "author": "Gili Nachum", "author_id": 121956, "author_profile": "https://Stackoverflow.com/users/121956", "pm_score": 7, "selected": false, "text": "<p>I use Apache common's <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-3.0/org/apache/commons/lang3/time/DurationFormatUtils.html\" rel=\"noreferrer\">DurationFormatUtils</a> like so: </p>\n\n<pre><code>DurationFormatUtils.formatDuration(millis, \"**H:mm:ss**\", true);\n</code></pre>\n" }, { "answer_id": 22776038, "author": "sbclint", "author_id": 3483443, "author_profile": "https://Stackoverflow.com/users/3483443", "pm_score": 2, "selected": false, "text": "<p>This is a working option.</p>\n\n<pre><code>public static String showDuration(LocalTime otherTime){ \n DateTimeFormatter df = DateTimeFormatter.ISO_LOCAL_TIME;\n LocalTime now = LocalTime.now();\n System.out.println(\"now: \" + now);\n System.out.println(\"otherTime: \" + otherTime);\n System.out.println(\"otherTime: \" + otherTime.format(df));\n\n Duration span = Duration.between(otherTime, now);\n LocalTime fTime = LocalTime.ofNanoOfDay(span.toNanos());\n String output = fTime.format(df);\n\n System.out.println(output);\n return output;\n}\n</code></pre>\n\n<p>Call the method with</p>\n\n<pre><code>System.out.println(showDuration(LocalTime.of(9, 30, 0, 0)));\n</code></pre>\n\n<p>Produces something like:</p>\n\n<pre><code>otherTime: 09:30\notherTime: 09:30:00\n11:31:27.463\n11:31:27.463\n</code></pre>\n" }, { "answer_id": 28131899, "author": "patrick", "author_id": 2263885, "author_profile": "https://Stackoverflow.com/users/2263885", "pm_score": 3, "selected": false, "text": "<p>This might be kind of hacky, but it is a good solution if one is bent on accomplishing this using Java 8's <code>java.time</code>:</p>\n\n<pre><code>import java.time.Duration;\nimport java.time.LocalDateTime;\nimport java.time.format.DateTimeFormatter;\nimport java.time.format.DateTimeFormatterBuilder;\nimport java.time.temporal.ChronoField;\nimport java.time.temporal.Temporal;\nimport java.time.temporal.TemporalAccessor;\nimport java.time.temporal.TemporalField;\nimport java.time.temporal.UnsupportedTemporalTypeException;\n\npublic class TemporalDuration implements TemporalAccessor {\n private static final Temporal BASE_TEMPORAL = LocalDateTime.of(0, 1, 1, 0, 0);\n\n private final Duration duration;\n private final Temporal temporal;\n\n public TemporalDuration(Duration duration) {\n this.duration = duration;\n this.temporal = duration.addTo(BASE_TEMPORAL);\n }\n\n @Override\n public boolean isSupported(TemporalField field) {\n if(!temporal.isSupported(field)) return false;\n long value = temporal.getLong(field)-BASE_TEMPORAL.getLong(field);\n return value!=0L;\n }\n\n @Override\n public long getLong(TemporalField field) {\n if(!isSupported(field)) throw new UnsupportedTemporalTypeException(new StringBuilder().append(field.toString()).toString());\n return temporal.getLong(field)-BASE_TEMPORAL.getLong(field);\n }\n\n public Duration getDuration() {\n return duration;\n }\n\n @Override\n public String toString() {\n return dtf.format(this);\n }\n\n private static final DateTimeFormatter dtf = new DateTimeFormatterBuilder()\n .optionalStart()//second\n .optionalStart()//minute\n .optionalStart()//hour\n .optionalStart()//day\n .optionalStart()//month\n .optionalStart()//year\n .appendValue(ChronoField.YEAR).appendLiteral(\" Years \").optionalEnd()\n .appendValue(ChronoField.MONTH_OF_YEAR).appendLiteral(\" Months \").optionalEnd()\n .appendValue(ChronoField.DAY_OF_MONTH).appendLiteral(\" Days \").optionalEnd()\n .appendValue(ChronoField.HOUR_OF_DAY).appendLiteral(\" Hours \").optionalEnd()\n .appendValue(ChronoField.MINUTE_OF_HOUR).appendLiteral(\" Minutes \").optionalEnd()\n .appendValue(ChronoField.SECOND_OF_MINUTE).appendLiteral(\" Seconds\").optionalEnd()\n .toFormatter();\n\n}\n</code></pre>\n" }, { "answer_id": 39344834, "author": "Pavel_H", "author_id": 1682715, "author_profile": "https://Stackoverflow.com/users/1682715", "pm_score": 3, "selected": false, "text": "<p>Here is one more sample how to format duration.\nNote that this sample shows both positive and negative duration as positive duration.</p>\n\n<pre><code>import static java.time.temporal.ChronoUnit.DAYS;\nimport static java.time.temporal.ChronoUnit.HOURS;\nimport static java.time.temporal.ChronoUnit.MINUTES;\nimport static java.time.temporal.ChronoUnit.SECONDS;\n\nimport java.time.Duration;\n\npublic class DurationSample {\n public static void main(String[] args) {\n //Let's say duration of 2days 3hours 12minutes and 46seconds\n Duration d = Duration.ZERO.plus(2, DAYS).plus(3, HOURS).plus(12, MINUTES).plus(46, SECONDS);\n\n //in case of negative duration\n if(d.isNegative()) d = d.negated();\n\n //format DAYS HOURS MINUTES SECONDS \n System.out.printf(\"Total duration is %sdays %shrs %smin %ssec.\\n\", d.toDays(), d.toHours() % 24, d.toMinutes() % 60, d.getSeconds() % 60);\n\n //or format HOURS MINUTES SECONDS \n System.out.printf(\"Or total duration is %shrs %smin %sec.\\n\", d.toHours(), d.toMinutes() % 60, d.getSeconds() % 60);\n\n //or format MINUTES SECONDS \n System.out.printf(\"Or total duration is %smin %ssec.\\n\", d.toMinutes(), d.getSeconds() % 60);\n\n //or format SECONDS only \n System.out.printf(\"Or total duration is %ssec.\\n\", d.getSeconds());\n }\n}\n</code></pre>\n" }, { "answer_id": 40594963, "author": "Meno Hochschild", "author_id": 2491410, "author_profile": "https://Stackoverflow.com/users/2491410", "pm_score": 0, "selected": false, "text": "<p>My library <a href=\"https://github.com/MenoData/Time4J\" rel=\"nofollow noreferrer\">Time4J</a> offers a pattern-based solution (similar to <code>Apache DurationFormatUtils</code>, but more flexible):</p>\n\n<pre><code>Duration&lt;ClockUnit&gt; duration =\n Duration.of(-573421, ClockUnit.SECONDS) // input in seconds only\n .with(Duration.STD_CLOCK_PERIOD); // performs normalization to h:mm:ss-structure\nString fs = Duration.formatter(ClockUnit.class, \"+##h:mm:ss\").format(duration);\nSystem.out.println(fs); // output =&gt; -159:17:01\n</code></pre>\n\n<p>This code demonstrates the capabilities to handle hour overflow and sign handling, see also the API of duration-formatter <a href=\"http://time4j.net/javadoc-en/net/time4j/Duration.Formatter.html#ofPattern-java.lang.Class-java.lang.String-\" rel=\"nofollow noreferrer\">based on pattern</a>.</p>\n" }, { "answer_id": 43578628, "author": "Bax", "author_id": 868975, "author_profile": "https://Stackoverflow.com/users/868975", "pm_score": 2, "selected": false, "text": "<pre><code>String duration(Temporal from, Temporal to) {\n final StringBuilder builder = new StringBuilder();\n for (ChronoUnit unit : new ChronoUnit[]{YEARS, MONTHS, WEEKS, DAYS, HOURS, MINUTES, SECONDS}) {\n long amount = unit.between(from, to);\n if (amount == 0) {\n continue;\n }\n builder.append(' ')\n .append(amount)\n .append(' ')\n .append(unit.name().toLowerCase());\n from = from.plus(amount, unit);\n }\n return builder.toString().trim();\n}\n</code></pre>\n" }, { "answer_id": 44343699, "author": "Ole V.V.", "author_id": 5772882, "author_profile": "https://Stackoverflow.com/users/5772882", "pm_score": 6, "selected": false, "text": "<p>This is easier since Java 9. A <code>Duration</code> still isn’t formattable, but methods for getting the hours, minutes and seconds are added, which makes the task somewhat more straightforward:</p>\n\n<pre><code> LocalDateTime start = LocalDateTime.of(2019, Month.JANUARY, 17, 15, 24, 12);\n LocalDateTime end = LocalDateTime.of(2019, Month.JANUARY, 18, 15, 43, 33);\n Duration diff = Duration.between(start, end);\n String hms = String.format(\"%d:%02d:%02d\", \n diff.toHours(), \n diff.toMinutesPart(), \n diff.toSecondsPart());\n System.out.println(hms);\n</code></pre>\n\n<p>The output from this snippet is:</p>\n\n<blockquote>\n <p>24:19:21</p>\n</blockquote>\n" }, { "answer_id": 44797053, "author": "mksteve", "author_id": 5129715, "author_profile": "https://Stackoverflow.com/users/5129715", "pm_score": 3, "selected": false, "text": "<p>How about the following function, which returns either \n+H:MM:SS\nor\n+H:MM:SS.sss</p>\n\n<pre><code>public static String formatInterval(final long interval, boolean millisecs )\n{\n final long hr = TimeUnit.MILLISECONDS.toHours(interval);\n final long min = TimeUnit.MILLISECONDS.toMinutes(interval) %60;\n final long sec = TimeUnit.MILLISECONDS.toSeconds(interval) %60;\n final long ms = TimeUnit.MILLISECONDS.toMillis(interval) %1000;\n if( millisecs ) {\n return String.format(\"%02d:%02d:%02d.%03d\", hr, min, sec, ms);\n } else {\n return String.format(\"%02d:%02d:%02d\", hr, min, sec );\n }\n}\n</code></pre>\n" }, { "answer_id": 49628638, "author": "YourBestBet", "author_id": 571856, "author_profile": "https://Stackoverflow.com/users/571856", "pm_score": -1, "selected": false, "text": "<p>in scala, no library needed:</p>\n\n<pre><code>def prettyDuration(str:List[String],seconds:Long):List[String]={\n seconds match {\n case t if t &lt; 60 =&gt; str:::List(s\"${t} seconds\")\n case t if (t &gt;= 60 &amp;&amp; t&lt; 3600 ) =&gt; List(s\"${t / 60} minutes\"):::prettyDuration(str, t%60)\n case t if (t &gt;= 3600 &amp;&amp; t&lt; 3600*24 ) =&gt; List(s\"${t / 3600} hours\"):::prettyDuration(str, t%3600)\n case t if (t&gt;= 3600*24 ) =&gt; List(s\"${t / (3600*24)} days\"):::prettyDuration(str, t%(3600*24))\n }\n}\nval dur = prettyDuration(List.empty[String], 12345).mkString(\"\")\n</code></pre>\n" }, { "answer_id": 51091602, "author": "lauhub", "author_id": 1011366, "author_profile": "https://Stackoverflow.com/users/1011366", "pm_score": 4, "selected": false, "text": "<p>This answer only uses <code>Duration</code> methods and works with Java 8 :</p>\n<pre><code>public static String format(Duration d) {\n long days = d.toDays();\n d = d.minusDays(days);\n long hours = d.toHours();\n d = d.minusHours(hours);\n long minutes = d.toMinutes();\n d = d.minusMinutes(minutes);\n long seconds = d.getSeconds() ;\n return \n (days == 0?&quot;&quot;:days+&quot; days,&quot;)+ \n (hours == 0?&quot;&quot;:hours+&quot; hours,&quot;)+ \n (minutes == 0?&quot;&quot;:minutes+&quot; minutes,&quot;)+ \n (seconds == 0?&quot;&quot;:seconds+&quot; seconds,&quot;);\n}\n</code></pre>\n" }, { "answer_id": 52992235, "author": "dpoetzsch", "author_id": 3594403, "author_profile": "https://Stackoverflow.com/users/3594403", "pm_score": -1, "selected": false, "text": "<p>In Scala, building up on YourBestBet's solution but simplified:</p>\n\n<pre><code>def prettyDuration(seconds: Long): List[String] = seconds match {\n case t if t &lt; 60 =&gt; List(s\"${t} seconds\")\n case t if t &lt; 3600 =&gt; s\"${t / 60} minutes\" :: prettyDuration(t % 60)\n case t if t &lt; 3600*24 =&gt; s\"${t / 3600} hours\" :: prettyDuration(t % 3600)\n case t =&gt; s\"${t / (3600*24)} days\" :: prettyDuration(t % (3600*24))\n}\n\nval dur = prettyDuration(12345).mkString(\", \") // =&gt; 3 hours, 25 minutes, 45 seconds\n</code></pre>\n" }, { "answer_id": 54794030, "author": "ctg", "author_id": 6157999, "author_profile": "https://Stackoverflow.com/users/6157999", "pm_score": 4, "selected": false, "text": "<p>There's a fairly simple and (IMO) elegant approach, at least for durations of less than 24 hours:</p>\n\n<p><code>DateTimeFormatter.ISO_LOCAL_TIME.format(value.addTo(LocalTime.of(0, 0)))</code></p>\n\n<p>Formatters need a temporal object to format, so you can create one by adding the duration to a LocalTime of 00:00 (i.e. midnight). This will give you a LocalTime representing the duration from midnight to that time, which is then easy to format in standard HH:mm:ss notation. This has the advantage of not needing an external library, and uses the java.time library to do the calculation, rather than manually calculating the hours, minutes and seconds.</p>\n" }, { "answer_id": 62466864, "author": "Stephen", "author_id": 37193, "author_profile": "https://Stackoverflow.com/users/37193", "pm_score": -1, "selected": false, "text": "<p>In scala (I saw some other attempts, and wasn't impressed):</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>def formatDuration(duration: Duration): String = {\n import duration._ // get access to all the members ;)\n f\"$toDaysPart $toHoursPart%02d:$toMinutesPart%02d:$toSecondsPart%02d:$toMillisPart%03d\"\n}\n</code></pre>\n\n<p>Looks horrible yes? Well that's why we use IDEs to write this stuff so that the method calls (<code>$toHoursPart</code> etc) are a different color.</p>\n\n<p>The <code>f\"...\"</code> is a <code>printf</code>/<code>String.format</code> style string interpolator (which is what allows the <code>$</code> code injection to work)\nGiven an output of <code>1 14:06:32.583</code>, the <code>f</code> interpolated string would be equivalent to <code>String.format(\"1 %02d:%02d:%02d.%03d\", 14, 6, 32, 583)</code></p>\n" }, { "answer_id": 62702984, "author": "ipserc", "author_id": 12701130, "author_profile": "https://Stackoverflow.com/users/12701130", "pm_score": 1, "selected": false, "text": "<p>using this func</p>\n<pre><code>private static String strDuration(long duration) {\n int ms, s, m, h, d;\n double dec;\n double time = duration * 1.0;\n\n time = (time / 1000.0);\n dec = time % 1;\n time = time - dec;\n ms = (int)(dec * 1000);\n\n time = (time / 60.0);\n dec = time % 1;\n time = time - dec;\n s = (int)(dec * 60);\n\n time = (time / 60.0);\n dec = time % 1;\n time = time - dec;\n m = (int)(dec * 60);\n\n time = (time / 24.0);\n dec = time % 1;\n time = time - dec;\n h = (int)(dec * 24);\n \n d = (int)time;\n \n return (String.format(&quot;%d d - %02d:%02d:%02d.%03d&quot;, d, h, m, s, ms));\n}\n</code></pre>\n" }, { "answer_id": 63711661, "author": "Sergei Maleev", "author_id": 12761967, "author_profile": "https://Stackoverflow.com/users/12761967", "pm_score": 3, "selected": false, "text": "<p>I'm not sure that is you want, but check this Android helper class</p>\n<pre><code>import android.text.format.DateUtils\n</code></pre>\n<p>For example: <code>DateUtils.formatElapsedTime()</code></p>\n<p><a href=\"/questions/tagged/android\" class=\"post-tag\" title=\"show questions tagged &#39;android&#39;\" rel=\"tag\">android</a> <a href=\"/questions/tagged/date\" class=\"post-tag\" title=\"show questions tagged &#39;date&#39;\" rel=\"tag\">date</a> <a href=\"/questions/tagged/duration\" class=\"post-tag\" title=\"show questions tagged &#39;duration&#39;\" rel=\"tag\">duration</a> <a href=\"/questions/tagged/elapsedtime\" class=\"post-tag\" title=\"show questions tagged &#39;elapsedtime&#39;\" rel=\"tag\">elapsedtime</a></p>\n" }, { "answer_id": 65501046, "author": "Arvind Kumar Avinash", "author_id": 10819573, "author_profile": "https://Stackoverflow.com/users/10819573", "pm_score": 3, "selected": false, "text": "<p>You can use <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html\" rel=\"noreferrer\"><code>java.time.Duration</code></a> which is modelled on <a href=\"https://en.wikipedia.org/wiki/ISO_8601\" rel=\"noreferrer\">ISO-8601 standards</a> and was introduced with <em>Java-8</em> as part of <a href=\"https://jcp.org/aboutJava/communityprocess/pfd/jsr310/JSR-310-guide.html\" rel=\"noreferrer\">JSR-310 implementation</a>. With <em>Java-9</em> some more convenience methods were introduced.</p>\n<p><strong>Demo:</strong></p>\n<pre><code>import java.time.Duration;\nimport java.time.LocalDateTime;\nimport java.time.Month;\n\npublic class Main {\n public static void main(String[] args) {\n LocalDateTime startDateTime = LocalDateTime.of(2020, Month.DECEMBER, 10, 15, 20, 25);\n LocalDateTime endDateTime = LocalDateTime.of(2020, Month.DECEMBER, 10, 18, 24, 30);\n\n Duration duration = Duration.between(startDateTime, endDateTime);\n // Default format\n System.out.println(duration);\n\n // Custom format\n // ####################################Java-8####################################\n String formattedElapsedTime = String.format(&quot;%02d:%02d:%02d&quot;, duration.toHours() % 24,\n duration.toMinutes() % 60, duration.toSeconds() % 60);\n System.out.println(formattedElapsedTime);\n // ##############################################################################\n\n // ####################################Java-9####################################\n formattedElapsedTime = String.format(&quot;%02d:%02d:%02d&quot;, duration.toHoursPart(), duration.toMinutesPart(),\n duration.toSecondsPart());\n System.out.println(formattedElapsedTime);\n // ##############################################################################\n }\n}\n</code></pre>\n<p><strong>Output:</strong></p>\n<pre><code>PT3H4M5S\n03:04:05\n03:04:05\n</code></pre>\n<p>Learn about the modern date-time API from <strong><a href=\"https://docs.oracle.com/javase/tutorial/datetime/index.html\" rel=\"noreferrer\">Trail: Date Time</a></strong>.</p>\n<ul>\n<li>For any reason, if you have to stick to Java 6 or Java 7, you can use <a href=\"http://www.threeten.org/threetenbp/\" rel=\"noreferrer\"><em><strong>ThreeTen-Backport</strong></em></a> which backports most of the <em>java.time</em> functionality to Java 6 &amp; 7.</li>\n<li>If you are working for an Android project and your Android API level is still not compliant with Java-8, check <a href=\"https://developer.android.com/studio/write/java8-support-table\" rel=\"noreferrer\">Java 8+ APIs available through desugaring</a> and <a href=\"https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project\">How to use ThreeTenABP in Android Project</a>.</li>\n</ul>\n" }, { "answer_id": 65586659, "author": "stanley", "author_id": 14947476, "author_profile": "https://Stackoverflow.com/users/14947476", "pm_score": 3, "selected": false, "text": "<p>There is yet another way to make it for java8. But it works if duration is no longer than 24 hours</p>\n<pre><code>public String formatDuration(Duration duration) {\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(&quot;h:mm.SSS&quot;);\n return LocalTime.ofNanoOfDay(duration.toNanos()).format(formatter);\n}\n</code></pre>\n" }, { "answer_id": 66066413, "author": "sschrass", "author_id": 1087479, "author_profile": "https://Stackoverflow.com/users/1087479", "pm_score": 0, "selected": false, "text": "<p>Looking at all those calculations, it may is helpful that most of the Units (Hours, Minutes, etc.) have a <code>.toFooPart()</code> convenience method.</p>\n<p>E.g.</p>\n<pre><code>Duration.ofMinutes(110L).toMinutesPart() == 50\n</code></pre>\n<p>Read: the minutes elapsed to the next value of the parent unit (Hour).</p>\n" }, { "answer_id": 69717677, "author": "Graham Lea", "author_id": 243104, "author_profile": "https://Stackoverflow.com/users/243104", "pm_score": 2, "selected": false, "text": "<p>Here's a one-liner for converting a <code>java.time.Duration</code> to a nice string in Kotlin:</p>\n<pre><code>duration.run {\n &quot;%d:%02d:%02d.%03d&quot;.format(toHours(), toMinutesPart(), toSecondsPart(), toMillisPart())\n}\n</code></pre>\n<p>Example output:\n<code>120:56:03.004</code></p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9941/" ]
I'm conducting experiments regarding e-mail spam. One of these experiments require sending mail thru Tor. Since I'm using Python and smtplib for my experiments, I'm looking for a way to use the Tor proxy (or other method) to perform that mail sending. Ideas how this can be done?
If you're using a version of Java prior to 8... you can use [Joda Time](http://joda-time.sourceforge.net/) and [`PeriodFormatter`](http://joda-time.sourceforge.net/api-release/org/joda/time/format/PeriodFormatter.html). If you've really got a duration (i.e. an elapsed amount of time, with no reference to a calendar system) then you should probably be using `Duration` for the most part - you can then call `toPeriod` (specifying whatever `PeriodType` you want to reflect whether 25 hours becomes 1 day and 1 hour or not, etc) to get a `Period` which you can format. If you're using Java 8 or later: I'd normally suggest using `java.time.Duration` to represent the duration. You can then call `getSeconds()` or the like to obtain an integer for standard string formatting as per bobince's answer if you need to - although you should be careful of the situation where the duration is negative, as you probably want a *single* negative sign in the output string. So something like: ``` public static String formatDuration(Duration duration) { long seconds = duration.getSeconds(); long absSeconds = Math.abs(seconds); String positive = String.format( "%d:%02d:%02d", absSeconds / 3600, (absSeconds % 3600) / 60, absSeconds % 60); return seconds < 0 ? "-" + positive : positive; } ``` Formatting this way is *reasonably* simple, if annoyingly manual. For *parsing* it becomes a harder matter in general... You could still use Joda Time even with Java 8 if you want to, of course.
266,854
<p>I frequently run into large, non-template classes in C++ where simple methods are defined directly in the class body in the header file instead of separately in the implementation file. For example:</p> <pre><code>class Foo { int getBar() const { return bar; } ... }; </code></pre> <p>Why do this? It seems like there are disadvantages. The implementation is not as hidden as it should be, the code is less readable, and there would also be an increased burden on the compiler if the class's header file is included in many different places.</p> <p>My guess is that people intend for these functions to be inlined in other modules, which could improve performance significantly. However, I've heard newer compilers can do inlining (and other interprocedural optimizations) at link-time across modules. How broad is the support for this kind of link-time optimization, and does it actually make these kind of definitions unnecessary? Are there any other good reasons for these definitions?</p>
[ { "answer_id": 266858, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 2, "selected": false, "text": "<p>You answered your own question, they are indeed inline methods.</p>\n\n<p>Reasons to use them are performance. </p>\n" }, { "answer_id": 266868, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 5, "selected": true, "text": "<p>The C++ standard says that methods defined inside the class definition are <code>inline</code> by default. This results in obvious performance gains for simplistic functions such as getters and setters. Link-time cross-module optimization is harder, although some compilers can do it.</p>\n" }, { "answer_id": 266890, "author": "Gerald", "author_id": 19404, "author_profile": "https://Stackoverflow.com/users/19404", "pm_score": 3, "selected": false, "text": "<p>Often there's no reason other than it's just easier and saves time. It also saves a little clutter in the implementation file, while taking up the same number of lines in the header file. And being less readable is quite a stretch if it's limited to things like getters and setters.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1891/" ]
I frequently run into large, non-template classes in C++ where simple methods are defined directly in the class body in the header file instead of separately in the implementation file. For example: ``` class Foo { int getBar() const { return bar; } ... }; ``` Why do this? It seems like there are disadvantages. The implementation is not as hidden as it should be, the code is less readable, and there would also be an increased burden on the compiler if the class's header file is included in many different places. My guess is that people intend for these functions to be inlined in other modules, which could improve performance significantly. However, I've heard newer compilers can do inlining (and other interprocedural optimizations) at link-time across modules. How broad is the support for this kind of link-time optimization, and does it actually make these kind of definitions unnecessary? Are there any other good reasons for these definitions?
The C++ standard says that methods defined inside the class definition are `inline` by default. This results in obvious performance gains for simplistic functions such as getters and setters. Link-time cross-module optimization is harder, although some compilers can do it.
266,857
<p>I'm writing a Rails plugin that includes some partials. I'd like to test the partials, but I'm having a hard time setting up a test that will render them. There's no associated controller, so I'm just faking one:</p> <pre><code>require 'action_controller' require 'active_support' require 'action_pack' require 'action_view' class MyTest &lt; Test::Unit::TestCase def setup @renderer = ActionController::Base.new @renderer.append_view_path File.expand_path(File.join(File.dirname(__FILE__), '..', 'views')) end def test_renders_link result = @renderer.render(:partial =&gt; '/something') assert ... end end </code></pre> <p>But that <code>:render</code> call always blows up. I've tried using an <code>ActionView::Base</code> instead of an <code>ActionController::Base</code>, but that gets even less far.</p> <p>Has anyone had any success?</p>
[ { "answer_id": 266876, "author": "danpickett", "author_id": 21788, "author_profile": "https://Stackoverflow.com/users/21788", "pm_score": 2, "selected": false, "text": "<p>checkout ActionView::TestCase - <a href=\"http://api.rubyonrails.org/classes/ActionView/TestCase.html\" rel=\"nofollow noreferrer\">http://api.rubyonrails.org/classes/ActionView/TestCase.html</a></p>\n\n<p>You can also use these to test helpers, which I've found extremely helpful.</p>\n\n<p>RSpec also has a way to test views: <a href=\"http://rspec.info/documentation/rails/writing/views.html\" rel=\"nofollow noreferrer\">http://rspec.info/documentation/rails/writing/views.html</a></p>\n\n<p>Hope that helps!</p>\n" }, { "answer_id": 267055, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 0, "selected": false, "text": "<p>The closest I've gotten is</p>\n\n<pre><code>require 'action_controller'\nrequire 'active_support'\nrequire 'action_pack'\nrequire 'action_view'\nrequire 'action_controller/test_case'\n\nclass StubController &lt; ActionController::Base\n append_view_path '...'\n def _renderizer; render params[:args]; end\n def rescue_action(e) raise e end;\nend\n\nclass MyTest &lt; ActionController::TestCase\n self.controller_class = StubController\n def render(args); get :_renderizer, :args =&gt; args; end \n def test_xxx\n render :partial =&gt; ...\n end\nend\n</code></pre>\n\n<p>But I get a routing error now: <code>ActionController::RoutingError: No route matches {:action=&gt;\"_renderizer\", :controller=&gt;\"\", :args=&gt;{:locals=&gt;{:...}, :partial=&gt;\"/my_partial\"}}</code></p>\n" }, { "answer_id": 267121, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 2, "selected": true, "text": "<p>The final answer:</p>\n\n<pre><code>require 'action_controller'\nrequire 'active_support'\nrequire 'action_pack'\nrequire 'action_view'\nrequire 'action_controller/test_case'\n\nclass StubController &lt; ActionController::Base\n helper MyHelper\n append_view_path '...'\n attr_accessor :thing\n def my_partial\n render :partial =&gt; '/my_partial', :locals =&gt; { :thing =&gt; thing }\n end\n def rescue_action(e) raise e end;\nend\n\nclass MyTestCase &lt; ActionController::TestCase\n self.controller_class = StubController\n def setup\n @controller.thing = ...\n get :my_partial\n assert ...\n end\nend\n</code></pre>\n" }, { "answer_id": 267489, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 0, "selected": false, "text": "<p>I suggest you look at the code for the <a href=\"http://github.com/giraffesoft/resource_controller\" rel=\"nofollow noreferrer\">resource_controller plugin</a>. I've also seen the approach in a few other plugins.</p>\n\n<p>The answer is simple, in the <strong>test</strong> directory, you create an app that uses your plugin. From there, you simply use the common tools to test Rails views.</p>\n\n<p>The test app can be extremely simple if there aren't many different use cases for your plugin. In the case of more complex plugins, like resource_controller, you'll probably have to create quite a few different controllers and so on.</p>\n\n<p>To trick your test app into loading your plugin, the simplest way is to create a link to the root of the r_c directory inside the test app's plugin directory. This isn't gonna work on Windows, only POSIX OSes.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190/" ]
I'm writing a Rails plugin that includes some partials. I'd like to test the partials, but I'm having a hard time setting up a test that will render them. There's no associated controller, so I'm just faking one: ``` require 'action_controller' require 'active_support' require 'action_pack' require 'action_view' class MyTest < Test::Unit::TestCase def setup @renderer = ActionController::Base.new @renderer.append_view_path File.expand_path(File.join(File.dirname(__FILE__), '..', 'views')) end def test_renders_link result = @renderer.render(:partial => '/something') assert ... end end ``` But that `:render` call always blows up. I've tried using an `ActionView::Base` instead of an `ActionController::Base`, but that gets even less far. Has anyone had any success?
The final answer: ``` require 'action_controller' require 'active_support' require 'action_pack' require 'action_view' require 'action_controller/test_case' class StubController < ActionController::Base helper MyHelper append_view_path '...' attr_accessor :thing def my_partial render :partial => '/my_partial', :locals => { :thing => thing } end def rescue_action(e) raise e end; end class MyTestCase < ActionController::TestCase self.controller_class = StubController def setup @controller.thing = ... get :my_partial assert ... end end ```
266,874
<p>I'm setting the below variables in my vimrc to control how windows get split when I bring up the file explorer plugin for vim. But it appears these variables are not being read because they have no effect on how the file explorer window is displayed. I'm new to vim. I know the vimrc file is being read because I can make other setting changes and they get picked up but these don't work. What am I missing?</p> <p><code>let g:explWinSize=10</code></p> <p><code>let g:explSplitBelow=1</code></p> <p><code>let g:explDetailedHelp=0</code></p>
[ { "answer_id": 266904, "author": "grieve", "author_id": 34329, "author_profile": "https://Stackoverflow.com/users/34329", "pm_score": 0, "selected": false, "text": "<p>Create a gvimrc right beside your vimrc file and add those settings in there.</p>\n" }, { "answer_id": 269952, "author": "Zathrus", "author_id": 16220, "author_profile": "https://Stackoverflow.com/users/16220", "pm_score": 2, "selected": true, "text": "<p>Wherever you got those settings from is outdated. They were valid in vim 6.x, but not 7.x.</p>\n\n<p>For 7.x, use the following settings instead:</p>\n\n<pre><code>let g:netrw_winsize=10\nlet g:netrw_alto=1\n</code></pre>\n\n<p>There is no option for disabling \"detailed help\" that I can find, but the help provided by netrw in v6 vs v7 is quite different anyway. Read :h netrw for additional info.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16973/" ]
I'm setting the below variables in my vimrc to control how windows get split when I bring up the file explorer plugin for vim. But it appears these variables are not being read because they have no effect on how the file explorer window is displayed. I'm new to vim. I know the vimrc file is being read because I can make other setting changes and they get picked up but these don't work. What am I missing? `let g:explWinSize=10` `let g:explSplitBelow=1` `let g:explDetailedHelp=0`
Wherever you got those settings from is outdated. They were valid in vim 6.x, but not 7.x. For 7.x, use the following settings instead: ``` let g:netrw_winsize=10 let g:netrw_alto=1 ``` There is no option for disabling "detailed help" that I can find, but the help provided by netrw in v6 vs v7 is quite different anyway. Read :h netrw for additional info.
266,877
<p>I have a very specific html table construct that seems to reveal a Gecko bug.</p> <p>Here's a distilled version of the problem. Observe the following table in a gecko-based browser (FF, for example): (you'll have to copy and paste this into a new file)</p> <pre><code>&lt;style&gt; table.example{ border-collapse:collapse; } table.example td { border:1px solid red; } &lt;/style&gt; &lt;table class="example"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;1&lt;/th&gt; &lt;th&gt;2&lt;/th&gt; &lt;th&gt;3&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;1&lt;/td&gt; &lt;td&gt;2&lt;/td&gt; &lt;td rowspan="3"&gt;3&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;1&lt;/td&gt; &lt;td&gt;2&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;1&lt;/td&gt; &lt;td rowspan="2"&gt;2&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;1&lt;/td&gt; &lt;td&gt;3&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>There's a line missing over the "3" in the bottom-right cell -- view it in any other browser and the line will appear as expected. Interestingly, ditch the thead section of the table and look what we get:</p> <pre><code>&lt;style&gt; table.example{ border-collapse:collapse; } table.example td { border:1px solid red; } &lt;/style&gt; &lt;table class="example"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;1&lt;/td&gt; &lt;td&gt;2&lt;/td&gt; &lt;td rowspan="3"&gt;3&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;1&lt;/td&gt; &lt;td&gt;2&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;1&lt;/td&gt; &lt;td rowspan="2"&gt;2&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;1&lt;/td&gt; &lt;td&gt;3&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>Doing that makes it work. Has anyone seen this? I suppose I'll just get rid of my thead section for now as a workaround though it makes the table rather less accessible.</p>
[ { "answer_id": 266906, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 4, "selected": true, "text": "<p>Strange... definitely a painting bug. If you right-click to get the context menu to appear over <em>part</em> of where the line should be, then when you dismiss the context menu, the line has been redrawn underneath.</p>\n\n<p>Edit: Workaround - if you put <code>style=\"border-color: ...;\"</code> on the <code>&lt;td rowspan=\"3\"&gt;</code> you can get the border to appear, but it has to be a <em>different</em> colour - just use one that's as close to the others as possible. For example, if the table is #ff0000 use #ff0001</p>\n" }, { "answer_id": 3118551, "author": "Simon", "author_id": 376321, "author_profile": "https://Stackoverflow.com/users/376321", "pm_score": 0, "selected": false, "text": "<p>i have also found this bug but it's not on my PC but another. If i resize the browser window after a certain resolution the lines will disappear. once i maximise the window the all pop back.\nyou can fix this permanently by setting border-collapse:separate; this gives each boreder of each cell its own width. It's not what i want to do but it works.</p>\n\n<p>It can also be caused by using border-collapse:collapse; then setting aligning borders to 1px and then 0px. Because it collapses the borders it seems to prioritise the 0px over the 1px width.</p>\n\n<p>either way it's firefox only and it's yet another reason to move away from it.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34832/" ]
I have a very specific html table construct that seems to reveal a Gecko bug. Here's a distilled version of the problem. Observe the following table in a gecko-based browser (FF, for example): (you'll have to copy and paste this into a new file) ``` <style> table.example{ border-collapse:collapse; } table.example td { border:1px solid red; } </style> <table class="example"> <thead> <tr> <th>1</th> <th>2</th> <th>3</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2</td> <td rowspan="3">3</td> </tr> <tr> <td>1</td> <td>2</td> </tr> <tr> <td>1</td> <td rowspan="2">2</td> </tr> <tr> <td>1</td> <td>3</td> </tr> </tbody> </table> ``` There's a line missing over the "3" in the bottom-right cell -- view it in any other browser and the line will appear as expected. Interestingly, ditch the thead section of the table and look what we get: ``` <style> table.example{ border-collapse:collapse; } table.example td { border:1px solid red; } </style> <table class="example"> <tbody> <tr> <td>1</td> <td>2</td> <td rowspan="3">3</td> </tr> <tr> <td>1</td> <td>2</td> </tr> <tr> <td>1</td> <td rowspan="2">2</td> </tr> <tr> <td>1</td> <td>3</td> </tr> </tbody> </table> ``` Doing that makes it work. Has anyone seen this? I suppose I'll just get rid of my thead section for now as a workaround though it makes the table rather less accessible.
Strange... definitely a painting bug. If you right-click to get the context menu to appear over *part* of where the line should be, then when you dismiss the context menu, the line has been redrawn underneath. Edit: Workaround - if you put `style="border-color: ...;"` on the `<td rowspan="3">` you can get the border to appear, but it has to be a *different* colour - just use one that's as close to the others as possible. For example, if the table is #ff0000 use #ff0001
266,888
<p>I have a situation where I want to copy the output assembly from one project into the output directory of my target application using MSBuild, without hard-coding paths in my MSBuild Copy task. Here's the scenario:</p> <ul> <li>Project A - Web Application Project</li> <li>Project B - Dal Interface Project</li> <li>Project C - Dal Implementation Project</li> </ul> <p>There is a Business layer too, but has no relevance for the MSBuild problem I'm looking to solve.</p> <p>My business layer has a reference to my Dal.Interface project. My web project has a reference to the Business layer and as it stands, doing a build will pull the business layer and Dal.Interface projects into the output. So far, so good. Now in order for the web app to run, it needs the Dal implementation. I don't want the implementation referenced anywhere since I want to enforce coding to the interface and not having a reference means it won't show up in intellisense, etc.</p> <p>So I figured I could handle this through the MSBuild copy operation as an AfterBuild task (I have the Dal Implementation setup to build when the web project builds, just not referenced). I don't want to hard code paths or anything else in the MSBuild params, so I'm trying to figure out how to reference the output of the Dal project from the Web Application Project's MSBuild file.</p> <p>So based on the projects mentioned above this is what I want to see happen:</p> <ol> <li>Web app build is kicked off</li> <li>All required projects build (already configured, so this is done)</li> <li>MSBuild "AfterBuild" task kicks off and the output from Project C (Dal Implementation) is copied to the Bin directory of Project A (web app)</li> </ol> <p>Part 3 is where I'm stuck. </p> <p>I'm sure this can be done, I'm just not finding a good reference to help out. Thanks in advance for any help.</p>
[ { "answer_id": 266956, "author": "Andrew Van Slaars", "author_id": 8087, "author_profile": "https://Stackoverflow.com/users/8087", "pm_score": 4, "selected": true, "text": "<p>I have made this work, though I would love to find a cleaner solution that takes advanctage of the built-in parameters within MSBuild (like $(TargetDir), etc but to point at the project I want to grab the output for). Anyway, here is what I've done:</p>\n\n<pre><code>&lt;Target Name=\"AfterBuild\"&gt;\n&lt;Copy SourceFiles=\"$(SolutionDir)MyProject.Dal.Linq\\bin\\$(Configuration)\\MyProject.Dal.Linq.dll\" DestinationFolder=\"$(TargetDir)\"/&gt;\n&lt;/Target&gt;\n</code></pre>\n\n<p>I would love to see a cleaner solution, but this should do for now.</p>\n" }, { "answer_id": 21377647, "author": "Jonathan", "author_id": 552510, "author_profile": "https://Stackoverflow.com/users/552510", "pm_score": 2, "selected": false, "text": "<p>So, you want to have a reference, but not have it visible in VS. So you want it built if needed, and copied to output like any other <code>Content</code> file. Here's how you'd do it:</p>\n\n<pre><code>&lt;Target Name=\"IncludeDALImplementation\" BeforeTargets=\"AfterBuild\"&gt;\n &lt;MSBuild Projects=\"..\\DalImplementation\\DAL.csproj\" BuildInParallel=\"$(BuildInParallel)\" Targets=\"Build\"&gt;\n &lt;Output TaskParameter=\"TargetOutputs\" ItemName=\"DalImplementationOutput\" /&gt;\n &lt;/MSBuild&gt;\n\n &lt;ItemGroup&gt;\n &lt;Content Include=\"@(DalImplementationOutput)\" /&gt;\n &lt;/ItemGroup&gt;\n&lt;/Target&gt;\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8087/" ]
I have a situation where I want to copy the output assembly from one project into the output directory of my target application using MSBuild, without hard-coding paths in my MSBuild Copy task. Here's the scenario: * Project A - Web Application Project * Project B - Dal Interface Project * Project C - Dal Implementation Project There is a Business layer too, but has no relevance for the MSBuild problem I'm looking to solve. My business layer has a reference to my Dal.Interface project. My web project has a reference to the Business layer and as it stands, doing a build will pull the business layer and Dal.Interface projects into the output. So far, so good. Now in order for the web app to run, it needs the Dal implementation. I don't want the implementation referenced anywhere since I want to enforce coding to the interface and not having a reference means it won't show up in intellisense, etc. So I figured I could handle this through the MSBuild copy operation as an AfterBuild task (I have the Dal Implementation setup to build when the web project builds, just not referenced). I don't want to hard code paths or anything else in the MSBuild params, so I'm trying to figure out how to reference the output of the Dal project from the Web Application Project's MSBuild file. So based on the projects mentioned above this is what I want to see happen: 1. Web app build is kicked off 2. All required projects build (already configured, so this is done) 3. MSBuild "AfterBuild" task kicks off and the output from Project C (Dal Implementation) is copied to the Bin directory of Project A (web app) Part 3 is where I'm stuck. I'm sure this can be done, I'm just not finding a good reference to help out. Thanks in advance for any help.
I have made this work, though I would love to find a cleaner solution that takes advanctage of the built-in parameters within MSBuild (like $(TargetDir), etc but to point at the project I want to grab the output for). Anyway, here is what I've done: ``` <Target Name="AfterBuild"> <Copy SourceFiles="$(SolutionDir)MyProject.Dal.Linq\bin\$(Configuration)\MyProject.Dal.Linq.dll" DestinationFolder="$(TargetDir)"/> </Target> ``` I would love to see a cleaner solution, but this should do for now.
266,901
<p>Just wondering if there is any way to do the following:</p> <pre><code>public Interface IDataField { object GetValue(); } public Interface IComplexDataField : IDataField { object GetDefaultValue(); } public class MyBase { private IDataField _DataField; public MyBase() { this._DataField = this.CreateDataField(); } public virtual IDataField CreateDataField() { return new DataField(); //Implements IDataField } **public virtual IDataField GetDataField()** { return this._DataField; } public void SomeMethod() { this.GetDataField().GetValue(); } } public class MyComplexBase : MyBase { public override IDataField CreateDataField() { return new ComplexDataField(); //Implements IComplexDataField which Implements IDataField } **public override IComplexDataField GetDataField()** { return (IComplexDataField)base.GetDataField(); } public void SomeComplexSpecificMethod() { this.GetDataField().GetValue(); this.GetDataField().GetDefaultValue(); } } </code></pre> <p>Cheers Anthony</p>
[ { "answer_id": 266911, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>What you want is <em>covariance of return types</em>. This doesn't exist in C#.</p>\n\n<p>Could you perhaps make <code>MyBase</code> generic:</p>\n\n<pre><code>public class MyBase&lt;T&gt; where T : IDataField\n{\n public virtual T CreateDataField()\n {\n ... etc ...\n }\n}\n</code></pre>\n\n<p>Alternatively, you can redeclare the method with \"new\" and shadow the base class method. Neither is particularly appealing...</p>\n" }, { "answer_id": 266915, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "<p>The closest you can get in C# 3.0 is to have a separate <code>virtual</code> method (like your <code>CreateDataField</code> method) that does the actual work and can be overridden, then use <code>new</code> to re-declare the public method. i.e. in the base:</p>\n\n<pre><code>public IDataField GetDataField()\n{\n return GetDataFieldImpl();\n}\nprotected virtual IDataField GetDataFieldImpl()\n{\n // return a basic version\n}\n</code></pre>\n\n<p>and in the subclass:</p>\n\n<pre><code>protected override IDataField GetDataFieldImpl()\n{\n // do something more fun\n}\npublic new IComplexDataField GetDataField()\n{\n return (IComplexDataField)GetDataFieldImpl();\n}\n</code></pre>\n" }, { "answer_id": 266941, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>What you're trying to do is called Covariant return types. They don't exist in the the current version C#, but there's talk of it being introduced for the next version.</p>\n\n<p>Your best approach explained here: <a href=\"http://srtsolutions.com/blogs/billwagner/archive/2005/06/17/covaraint-return-types-in-c.aspx\" rel=\"nofollow noreferrer\">covariant return types</a></p>\n\n<pre><code>public class MyBase&lt;T&gt; where T : IDataField, new()\n{\n public virtual T CreateDataField()\n {\n return new T();\n }\n\n public virtual T GetDataField()\n {\n return this._DataField;\n }\n\n}\n\npublic class MyComplexBase : MyBase&lt;ComplexDataField&gt;\n{\n ...\n}\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30572/" ]
Just wondering if there is any way to do the following: ``` public Interface IDataField { object GetValue(); } public Interface IComplexDataField : IDataField { object GetDefaultValue(); } public class MyBase { private IDataField _DataField; public MyBase() { this._DataField = this.CreateDataField(); } public virtual IDataField CreateDataField() { return new DataField(); //Implements IDataField } **public virtual IDataField GetDataField()** { return this._DataField; } public void SomeMethod() { this.GetDataField().GetValue(); } } public class MyComplexBase : MyBase { public override IDataField CreateDataField() { return new ComplexDataField(); //Implements IComplexDataField which Implements IDataField } **public override IComplexDataField GetDataField()** { return (IComplexDataField)base.GetDataField(); } public void SomeComplexSpecificMethod() { this.GetDataField().GetValue(); this.GetDataField().GetDefaultValue(); } } ``` Cheers Anthony
What you want is *covariance of return types*. This doesn't exist in C#. Could you perhaps make `MyBase` generic: ``` public class MyBase<T> where T : IDataField { public virtual T CreateDataField() { ... etc ... } } ``` Alternatively, you can redeclare the method with "new" and shadow the base class method. Neither is particularly appealing...
266,903
<p>How can I create an instance of the following annotation (with all fields set to their default value).</p> <pre><code> @Retention( RetentionPolicy.RUNTIME ) public @interface Settings { String a() default "AAA"; String b() default "BBB"; String c() default "CCC"; } </code></pre> <p>I tried <code>new Settings()</code>, but that does not seem to work...</p>
[ { "answer_id": 266945, "author": "Florin", "author_id": 34565, "author_profile": "https://Stackoverflow.com/users/34565", "pm_score": 1, "selected": false, "text": "<p>If used with a method:</p>\n\n<pre><code>@Settings\npublic void myMethod() {\n}\n</code></pre>\n\n<p>Now your annotation is initialized with default values.</p>\n" }, { "answer_id": 613469, "author": "akuhn", "author_id": 24468, "author_profile": "https://Stackoverflow.com/users/24468", "pm_score": 6, "selected": true, "text": "<p>You cannot create an instance, but at least get the default values</p>\n\n<pre><code>Settings.class.getMethod(\"a\").getDefaultValue()\nSettings.class.getMethod(\"b\").getDefaultValue()\nSettings.class.getMethod(\"c\").getDefaultValue()\n</code></pre>\n\n<p>And then, a dynamic proxy could be used to return the default values. Which is, as far as I can tell, the way annotations are handled by Java itself also.</p>\n\n<pre><code>class Defaults implements InvocationHandler {\n public static &lt;A extends Annotation&gt; A of(Class&lt;A&gt; annotation) {\n return (A) Proxy.newProxyInstance(annotation.getClassLoader(),\n new Class[] {annotation}, new Defaults());\n }\n public Object invoke(Object proxy, Method method, Object[] args)\n throws Throwable {\n return method.getDefaultValue();\n }\n}\n\nSettings s = Defaults.of(Settings.class);\nSystem.out.printf(\"%s\\n%s\\n%s\\n\", s.a(), s.b(), s.c());\n</code></pre>\n" }, { "answer_id": 2909984, "author": "emory", "author_id": 348975, "author_profile": "https://Stackoverflow.com/users/348975", "pm_score": 5, "selected": false, "text": "<p>I compile and ran below with satisfactory results.</p>\n\n<pre><code>class GetSettings {\n public static void main (String[] args){\n @Settings final class c { }\n Settings settings = c.class.getAnnotation(Settings.class);\n System.out.println(settings.aaa());\n }\n}\n</code></pre>\n" }, { "answer_id": 7067833, "author": "Ralph", "author_id": 280244, "author_profile": "https://Stackoverflow.com/users/280244", "pm_score": 5, "selected": false, "text": "<p>To create an instance you need to create a class that implements:</p>\n\n<ul>\n<li><a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/annotation/Annotation.html\" rel=\"nofollow noreferrer\"><code>java.lang.annotation.Annotation</code></a></li>\n<li>and the annotation you want to \"simulate\"</li>\n</ul>\n\n<p>For example:\n <code>public class MySettings implements Annotation, Settings</code></p>\n\n<p>But you need to pay special attention to the <strong>correct</strong> implementation of <code>equals</code> and <code>hashCode</code> according to the <code>Annotation</code> interface.\n<a href=\"http://download.oracle.com/javase/1.5.0/docs/api/java/lang/annotation/Annotation.html\" rel=\"nofollow noreferrer\">http://download.oracle.com/javase/1.5.0/docs/api/java/lang/annotation/Annotation.html</a></p>\n\n<p>If you do not want to implement this again and again then have a look at the <a href=\"http://docs.jboss.org/cdi/api/1.0/javax/enterprise/util/AnnotationLiteral.html\" rel=\"nofollow noreferrer\">javax.enterprise.util.AnnotationLiteral</a> class.\nThat is part of the CDI(Context Dependency Injection)-API.\n<a href=\"http://grepcode.com/file/repo1.maven.org/maven2/javax.enterprise/cdi-api/1.0/javax/enterprise/util/AnnotationLiteral.java\" rel=\"nofollow noreferrer\">(@see code)</a></p>\n\n<p>To get the default values you can use the way that is described by akuhn (former known as: Adrian).\n<code>Settings.class.getMethod(\"a\").getDefaultValue()</code></p>\n" }, { "answer_id": 17088810, "author": "ex0b1t", "author_id": 1031007, "author_profile": "https://Stackoverflow.com/users/1031007", "pm_score": 2, "selected": false, "text": "<p>had the same issue, i solved it as follows.</p>\n\n<pre><code>public static FieldGroup getDefaultFieldGroup() {\n @FieldGroup\n class settring {\n }\n return settring.class.getAnnotation(FieldGroup.class);\n}\n</code></pre>\n" }, { "answer_id": 29694223, "author": "Thomas Darimont", "author_id": 2123680, "author_profile": "https://Stackoverflow.com/users/2123680", "pm_score": 0, "selected": false, "text": "<p>This works with Sun/Oracle Java 5,6,7,8: (but could potentially break with Java 9 due to the sun classes involved). \n//edit Just verified that this still works with OpenJDK 9b59.</p>\n\n<pre><code>package demo;\n\nimport sun.reflect.annotation.AnnotationParser;\n\nimport java.lang.annotation.*;\nimport java.lang.reflect.Method;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class AnnotationProxyExample\n{\n\n public static void main(String[] args)\n {\n\n System.out.printf(\"Custom annotation creation: %s%n\", \n createAnnotationInstance(Collections.singletonMap(\"value\", \"required\"), Example.class));\n\n System.out.printf(\"Traditional annotation creation: %s%n\", \n X.class.getAnnotation(Example.class));\n }\n\n private static &lt;A extends Annotation&gt; A createAnnotationInstance(Map&lt;String, Object&gt; customValues, Class&lt;A&gt; annotationType)\n {\n\n Map&lt;String, Object&gt; values = new HashMap&lt;&gt;();\n\n //Extract default values from annotation\n for (Method method : annotationType.getDeclaredMethods())\n {\n values.put(method.getName(), method.getDefaultValue());\n }\n\n //Populate required values\n values.putAll(customValues);\n\n return (A) AnnotationParser.annotationForMap(annotationType, values);\n }\n\n @Example(\"required\")\n static class X\n {\n }\n\n @Retention(RetentionPolicy.RUNTIME)\n @Target(ElementType.TYPE)\n @interface Example\n {\n String value();\n int foo() default 42;\n boolean bar() default true;\n }\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Custom annotation creation: @demo.AnnotationProxyExample$Example(bar=true, foo=42, value=required)\nTraditional annotation creation: @demo.AnnotationProxyExample$Example(bar=true, foo=42, value=required)\n</code></pre>\n" }, { "answer_id": 38311677, "author": "mindas", "author_id": 7345, "author_profile": "https://Stackoverflow.com/users/7345", "pm_score": 1, "selected": false, "text": "<p>There is alternative solution, if you can afford to change the body of <code>Settings</code> class:</p>\n\n<pre><code>@Retention( RetentionPolicy.RUNTIME )\npublic @interface Settings {\n String DEFAULT_A = \"AAA\";\n String DEFAULT_B = \"BBB\";\n String DEFAULT_C = \"CCC\";\n\n String a() default DEFAULT_A;\n String b() default DEFAULT_B;\n String c() default DEFAULT_C;\n}\n</code></pre>\n\n<p>Then you can simply reference <code>Settings.DEFAULT_A</code> (yes, a better name would help!).</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24468/" ]
How can I create an instance of the following annotation (with all fields set to their default value). ``` @Retention( RetentionPolicy.RUNTIME ) public @interface Settings { String a() default "AAA"; String b() default "BBB"; String c() default "CCC"; } ``` I tried `new Settings()`, but that does not seem to work...
You cannot create an instance, but at least get the default values ``` Settings.class.getMethod("a").getDefaultValue() Settings.class.getMethod("b").getDefaultValue() Settings.class.getMethod("c").getDefaultValue() ``` And then, a dynamic proxy could be used to return the default values. Which is, as far as I can tell, the way annotations are handled by Java itself also. ``` class Defaults implements InvocationHandler { public static <A extends Annotation> A of(Class<A> annotation) { return (A) Proxy.newProxyInstance(annotation.getClassLoader(), new Class[] {annotation}, new Defaults()); } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.getDefaultValue(); } } Settings s = Defaults.of(Settings.class); System.out.printf("%s\n%s\n%s\n", s.a(), s.b(), s.c()); ```
266,923
<p>In C# which is more memory efficient: Option #1 or Option #2?</p> <pre><code>public void TestStringBuilder() { //potentially a collection with several hundred items: string[] outputStrings = new string[] { "test1", "test2", "test3" }; //Option #1 StringBuilder formattedOutput = new StringBuilder(); foreach (string outputString in outputStrings) { formattedOutput.Append("prefix "); formattedOutput.Append(outputString); formattedOutput.Append(" postfix"); string output = formattedOutput.ToString(); ExistingOutputMethodThatOnlyTakesAString(output); //Clear existing string to make ready for next iteration: formattedOutput.Remove(0, output.Length); } //Option #2 foreach (string outputString in outputStrings) { StringBuilder formattedOutputInsideALoop = new StringBuilder(); formattedOutputInsideALoop.Append("prefix "); formattedOutputInsideALoop.Append(outputString); formattedOutputInsideALoop.Append(" postfix"); ExistingOutputMethodThatOnlyTakesAString( formattedOutputInsideALoop.ToString()); } } private void ExistingOutputMethodThatOnlyTakesAString(string output) { //This method actually writes out to a file. System.Console.WriteLine(output); } </code></pre>
[ { "answer_id": 266929, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 0, "selected": false, "text": "<p>I'd say option #2 if definitely more straightforward. In terms of performance, sounds like something you'd just need to test and see. I'd guess that it doesn't make enough difference to choose the less straightforward option.</p>\n" }, { "answer_id": 266936, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>Option 2 should (I believe) actually outperform option 1. The act of calling <code>Remove</code> \"forces\" the StringBuilder to take a copy of the string it's already returned. The string is actually mutable within StringBuilder, and StringBuilder doesn't take a copy unless it needs to. With option 1 it copies before basically clearing the array out - with option 2 no copy is required.</p>\n\n<p>The only downside of option 2 is that if the string ends up being long, there will be multiple copies made while appending - whereas option 1 keeps the original size of buffer. If this is going to be the case, however, specify an initial capacity to avoid the extra copying. (In your sample code, the string will end up being bigger than the default 16 characters - initializing it with a capacity of, say, 32 will reduce the extra strings required.)</p>\n\n<p>Aside from the performance, however, option 2 is just cleaner.</p>\n" }, { "answer_id": 266944, "author": "Joel Lucsy", "author_id": 645, "author_profile": "https://Stackoverflow.com/users/645", "pm_score": 1, "selected": false, "text": "<p>Hate to say it, but how about just testing it?</p>\n" }, { "answer_id": 266965, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 1, "selected": false, "text": "<p>This stuff is easy to find out by yourself. Run Perfmon.exe and add a counter for .NET Memory + Gen 0 Collections. Run the test code a million times. You'll see that option #1 requires half of the number of collections option #2 needs.</p>\n" }, { "answer_id": 266983, "author": "Robert Wagner", "author_id": 10784, "author_profile": "https://Stackoverflow.com/users/10784", "pm_score": 0, "selected": false, "text": "<p>I think option 1 would be slightly more <strong>memory</strong> efficient as a new object isn't created everytime. Having said that, the GC does a pretty good job of cleaning up resources like in option 2. </p>\n\n<p>I think you may be falling into the trap of premature optimization (<a href=\"http://en.wikipedia.org/wiki/Code_optimization#Quotes\" rel=\"nofollow noreferrer\">the root of all evil --Knuth</a>). Your IO is going to take much more resources than the string builder.</p>\n\n<p>I tend go with the clearer/cleaner option, in this case option 2.</p>\n\n<p>Rob</p>\n" }, { "answer_id": 266991, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 1, "selected": false, "text": "<p>We've <a href=\"https://stackoverflow.com/questions/242438/java-performance-of-stringbuilder-in-a-loop\">talked about this before with Java</a>, here's the [Release] results of the C# version:</p>\n\n<pre><code>Option #1 (10000000 iterations): 11264ms\nOption #2 (10000000 iterations): 12779ms\n</code></pre>\n\n<p>Update: In my non-scientific analysis allowing the two methods to execute while monitoring all the memory performance counters in perfmon did not result in any sort of discernible difference with either method (other than having some counters spike only while either test was executing). </p>\n\n<p>And here's what I used to test:</p>\n\n<pre><code>class Program\n{\n const int __iterations = 10000000;\n\n static void Main(string[] args)\n {\n TestStringBuilder();\n Console.ReadLine();\n }\n\n public static void TestStringBuilder()\n {\n //potentially a collection with several hundred items:\n var outputStrings = new [] { \"test1\", \"test2\", \"test3\" };\n\n var stopWatch = new Stopwatch();\n\n //Option #1\n stopWatch.Start();\n var formattedOutput = new StringBuilder();\n\n for (var i = 0; i &lt; __iterations; i++)\n {\n foreach (var outputString in outputStrings)\n {\n formattedOutput.Append(\"prefix \");\n formattedOutput.Append(outputString);\n formattedOutput.Append(\" postfix\");\n\n var output = formattedOutput.ToString();\n ExistingOutputMethodThatOnlyTakesAString(output);\n\n //Clear existing string to make ready for next iteration:\n formattedOutput.Remove(0, output.Length);\n }\n }\n stopWatch.Stop();\n\n Console.WriteLine(\"Option #1 ({1} iterations): {0}ms\", stopWatch.ElapsedMilliseconds, __iterations);\n Console.ReadLine();\n stopWatch.Reset();\n\n //Option #2\n stopWatch.Start();\n for (var i = 0; i &lt; __iterations; i++)\n {\n foreach (var outputString in outputStrings)\n {\n StringBuilder formattedOutputInsideALoop = new StringBuilder();\n\n formattedOutputInsideALoop.Append(\"prefix \");\n formattedOutputInsideALoop.Append(outputString);\n formattedOutputInsideALoop.Append(\" postfix\");\n\n ExistingOutputMethodThatOnlyTakesAString(\n formattedOutputInsideALoop.ToString());\n }\n }\n stopWatch.Stop();\n\n Console.WriteLine(\"Option #2 ({1} iterations): {0}ms\", stopWatch.ElapsedMilliseconds, __iterations);\n }\n\n private static void ExistingOutputMethodThatOnlyTakesAString(string s)\n {\n // do nothing\n }\n} \n</code></pre>\n\n<p>Option 1 in this scenario is marginally faster though option 2 is easier to read and maintain. Unless you happen to be performing this operation millions of times back to back I would stick with Option 2 because I suspect that option 1 and 2 are about the same when running in a single iteration.</p>\n" }, { "answer_id": 267169, "author": "Jason Hernandez", "author_id": 34863, "author_profile": "https://Stackoverflow.com/users/34863", "pm_score": 2, "selected": false, "text": "<p>Since you are concerned only with memory I would suggest:</p>\n\n<pre><code>foreach (string outputString in outputStrings)\n { \n string output = \"prefix \" + outputString + \" postfix\";\n ExistingOutputMethodThatOnlyTakesAString(output) \n }\n</code></pre>\n\n<p>The variable named output is the same size in your original implementation, but no other objects are needed. StringBuilder uses strings and other objects internally and you will be created many objects that need to be GC'd.</p>\n\n<p>Both the line from option 1:</p>\n\n<pre><code>string output = formattedOutput.ToString();\n</code></pre>\n\n<p>And the line from option 2:</p>\n\n<pre><code>ExistingOutputMethodThatOnlyTakesAString(\n formattedOutputInsideALoop.ToString());\n</code></pre>\n\n<p>will create an <em>immutable</em> object with the value of the prefix + outputString + postfix. This string is the same size no matter how you create it. What you are really asking is which is more memory efficient:</p>\n\n<pre><code> StringBuilder formattedOutput = new StringBuilder(); \n // create new string builder\n</code></pre>\n\n<p>or </p>\n\n<pre><code> formattedOutput.Remove(0, output.Length); \n // reuse existing string builder\n</code></pre>\n\n<p>Skipping the StringBuilder entirely will be more memory efficient than either of the above.</p>\n\n<p>If you really need to know which of the two is more efficient in your application (this will probably vary based on the size of your list, prefix, and outputStrings) I would recommend red-gate ANTS Profiler <a href=\"http://www.red-gate.com/products/ants_profiler/index.htm\" rel=\"nofollow noreferrer\" title=\"http://www.red-gate.com/products/ants_profiler/index.htm\">http://www.red-gate.com/products/ants_profiler/index.htm</a></p>\n\n<p>Jason</p>\n" }, { "answer_id": 267189, "author": "Ty.", "author_id": 16948, "author_profile": "https://Stackoverflow.com/users/16948", "pm_score": 2, "selected": false, "text": "<p>While your profiling, you could also try just setting the length of the StringBuilder to zero when you enter the loop.</p>\n\n<pre><code>formattedOutput.Length = 0;\n</code></pre>\n" }, { "answer_id": 269220, "author": "Adam Straughan", "author_id": 14019, "author_profile": "https://Stackoverflow.com/users/14019", "pm_score": 0, "selected": false, "text": "<ol>\n<li>Measure it</li>\n<li>Pre-allocate as close as possible to how much memory you think you'll need</li>\n<li>If speed is your preference, then consider a fairly straight forward multi-threaded front to middle, middle to end concurrent approach (expand division of labour as required)</li>\n<li>measure it again</li>\n</ol>\n\n<p>what's more important to you?</p>\n\n<ol>\n<li><p>memory</p></li>\n<li><p>speed</p></li>\n<li><p>clarity</p></li>\n</ol>\n" }, { "answer_id": 273750, "author": "Sixto Saez", "author_id": 9711, "author_profile": "https://Stackoverflow.com/users/9711", "pm_score": 4, "selected": true, "text": "<p>Several of the answers gently suggested that I get off my duff and figure out it myself so below are my results. I think that sentiment generally goes against the grain of this site but if you want something done right, you might as well do.... :)</p>\n\n<p>I modified option #1 to take advantage of @Ty suggestion to use StringBuilder.Length = 0 instead of the Remove method. This made the code of the two options more similar. The two differences are now whether the constructor for the StringBuilder is in or out of the loop and option #1 now uses the the Length method to clear the StringBuilder. Both options were set to run over an outputStrings array with 100,000 elements to make the garbage collector do some work.</p>\n\n<p>A couple answers offered hints to look at the various PerfMon counters &amp; such and use the results to pick an option. I did some research and ended up using the built-in Performance Explorer of the Visual Studio Team Systems Developer edition that I have at work. I found the second blog entry of a multipart series that explained how to set it up <a href=\"http://blogs.msdn.com/ianhu/archive/2005/02/11/371418.aspx\" rel=\"noreferrer\">here</a>. Basically, you wire up a unit test to point at the code you want to profile; go through a wizard &amp; some configurations; and launch the unit test profiling. I enabled the .NET object allocation &amp; lifetime metrics. The results of the profiling where difficult to format for this answer so I placed them at the end. If you copy and paste the text into Excel and massage them a bit, they'll be readable.</p>\n\n<p>Option #1 is the most memory efficiency because it makes the garbage collector do a little less work and it allocates half the memory and instances to the StringBuilder object than Option #2. For everyday coding, picking option #2 is perfectly fine.</p>\n\n<p>If you're still reading, I asked this question because Option #2 will make the memory leak detectors of an experience C/C++ developer go ballistic. A huge memory leak will occur if the StringBuilder instance is not released before being reassigned. Of course, we C# developers don't worry about such things (until they jump up and bite us). Thanks to all!!</p>\n\n<hr>\n\n<pre><code>ClassName Instances TotalBytesAllocated Gen0_InstancesCollected Gen0BytesCollected Gen1InstancesCollected Gen1BytesCollected\n=======Option #1 \nSystem.Text.StringBuilder 100,001 2,000,020 100,016 2,000,320 2 40\nSystem.String 301,020 32,587,168 201,147 11,165,268 3 246\nSystem.Char[] 200,000 8,977,780 200,022 8,979,678 2 90\nSystem.String[] 1 400,016 26 1,512 0 0\nSystem.Int32 100,000 1,200,000 100,061 1,200,732 2 24\nSystem.Object[] 100,000 2,000,000 100,070 2,004,092 2 40\n======Option #2 \nSystem.Text.StringBuilder 200,000 4,000,000 200,011 4,000,220 4 80\nSystem.String 401,018 37,587,036 301,127 16,164,318 3 214\nSystem.Char[] 200,000 9,377,780 200,024 9,379,768 0 0\nSystem.String[] 1 400,016 20 1,208 0 0\nSystem.Int32 100,000 1,200,000 100,051 1,200,612 1 12\nSystem.Object[] 100,000 2,000,000 100,058 2,003,004 1 20\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9711/" ]
In C# which is more memory efficient: Option #1 or Option #2? ``` public void TestStringBuilder() { //potentially a collection with several hundred items: string[] outputStrings = new string[] { "test1", "test2", "test3" }; //Option #1 StringBuilder formattedOutput = new StringBuilder(); foreach (string outputString in outputStrings) { formattedOutput.Append("prefix "); formattedOutput.Append(outputString); formattedOutput.Append(" postfix"); string output = formattedOutput.ToString(); ExistingOutputMethodThatOnlyTakesAString(output); //Clear existing string to make ready for next iteration: formattedOutput.Remove(0, output.Length); } //Option #2 foreach (string outputString in outputStrings) { StringBuilder formattedOutputInsideALoop = new StringBuilder(); formattedOutputInsideALoop.Append("prefix "); formattedOutputInsideALoop.Append(outputString); formattedOutputInsideALoop.Append(" postfix"); ExistingOutputMethodThatOnlyTakesAString( formattedOutputInsideALoop.ToString()); } } private void ExistingOutputMethodThatOnlyTakesAString(string output) { //This method actually writes out to a file. System.Console.WriteLine(output); } ```
Several of the answers gently suggested that I get off my duff and figure out it myself so below are my results. I think that sentiment generally goes against the grain of this site but if you want something done right, you might as well do.... :) I modified option #1 to take advantage of @Ty suggestion to use StringBuilder.Length = 0 instead of the Remove method. This made the code of the two options more similar. The two differences are now whether the constructor for the StringBuilder is in or out of the loop and option #1 now uses the the Length method to clear the StringBuilder. Both options were set to run over an outputStrings array with 100,000 elements to make the garbage collector do some work. A couple answers offered hints to look at the various PerfMon counters & such and use the results to pick an option. I did some research and ended up using the built-in Performance Explorer of the Visual Studio Team Systems Developer edition that I have at work. I found the second blog entry of a multipart series that explained how to set it up [here](http://blogs.msdn.com/ianhu/archive/2005/02/11/371418.aspx). Basically, you wire up a unit test to point at the code you want to profile; go through a wizard & some configurations; and launch the unit test profiling. I enabled the .NET object allocation & lifetime metrics. The results of the profiling where difficult to format for this answer so I placed them at the end. If you copy and paste the text into Excel and massage them a bit, they'll be readable. Option #1 is the most memory efficiency because it makes the garbage collector do a little less work and it allocates half the memory and instances to the StringBuilder object than Option #2. For everyday coding, picking option #2 is perfectly fine. If you're still reading, I asked this question because Option #2 will make the memory leak detectors of an experience C/C++ developer go ballistic. A huge memory leak will occur if the StringBuilder instance is not released before being reassigned. Of course, we C# developers don't worry about such things (until they jump up and bite us). Thanks to all!! --- ``` ClassName Instances TotalBytesAllocated Gen0_InstancesCollected Gen0BytesCollected Gen1InstancesCollected Gen1BytesCollected =======Option #1 System.Text.StringBuilder 100,001 2,000,020 100,016 2,000,320 2 40 System.String 301,020 32,587,168 201,147 11,165,268 3 246 System.Char[] 200,000 8,977,780 200,022 8,979,678 2 90 System.String[] 1 400,016 26 1,512 0 0 System.Int32 100,000 1,200,000 100,061 1,200,732 2 24 System.Object[] 100,000 2,000,000 100,070 2,004,092 2 40 ======Option #2 System.Text.StringBuilder 200,000 4,000,000 200,011 4,000,220 4 80 System.String 401,018 37,587,036 301,127 16,164,318 3 214 System.Char[] 200,000 9,377,780 200,024 9,379,768 0 0 System.String[] 1 400,016 20 1,208 0 0 System.Int32 100,000 1,200,000 100,051 1,200,612 1 12 System.Object[] 100,000 2,000,000 100,058 2,003,004 1 20 ```
266,924
<p>I am trying to convert a date with individual parts such as 12, 1, 2007 into a datetime in SQL Server 2005. I have tried the following:</p> <pre><code>CAST(DATEPART(year, DATE)+'-'+ DATEPART(month, DATE) +'-'+ DATEPART(day, DATE) AS DATETIME) </code></pre> <p>but this results in the wrong date. What is the correct way to turn the three date values into a proper datetime format.</p>
[ { "answer_id": 266934, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 4, "selected": false, "text": "<p>Try CONVERT instead of CAST.</p>\n\n<p>CONVERT allows a third parameter indicating the date format.</p>\n\n<p>List of formats is here: <a href=\"http://msdn.microsoft.com/en-us/library/ms187928.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms187928.aspx</a></p>\n\n<p>Update after another answer has been selected as the \"correct\" answer:</p>\n\n<p>I don't really understand why an answer is selected that clearly depends on the NLS settings on your server, without indicating this restriction.</p>\n" }, { "answer_id": 266940, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 8, "selected": true, "text": "<p>Assuming <code>y, m, d</code> are all <code>int</code>, how about:</p>\n\n<pre><code>CAST(CAST(y AS varchar) + '-' + CAST(m AS varchar) + '-' + CAST(d AS varchar) AS DATETIME)\n</code></pre>\n\n<p>Please see <a href=\"https://stackoverflow.com/a/10142966/18255\">my other answer</a> for SQL Server 2012 and above</p>\n" }, { "answer_id": 266955, "author": "Robert Wagner", "author_id": 10784, "author_profile": "https://Stackoverflow.com/users/10784", "pm_score": 3, "selected": false, "text": "<p>If you don't want to keep strings out of it, this works as well (Put it into a function):</p>\n\n<pre><code>DECLARE @Day int, @Month int, @Year int\nSELECT @Day = 1, @Month = 2, @Year = 2008\n\nSELECT DateAdd(dd, @Day-1, DateAdd(mm, @Month -1, DateAdd(yy, @Year - 2000, '20000101')))\n</code></pre>\n" }, { "answer_id": 267016, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 8, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>Declare @DayOfMonth TinyInt Set @DayOfMonth = 13\nDeclare @Month TinyInt Set @Month = 6\nDeclare @Year Integer Set @Year = 2006\n-- ------------------------------------\nSelect DateAdd(day, @DayOfMonth - 1, \n DateAdd(month, @Month - 1, \n DateAdd(Year, @Year-1900, 0)))\n</code></pre>\n\n<p>It works as well, has added benefit of not doing any string conversions, so it's pure arithmetic processing (very fast) and it's not dependent on any date format\nThis capitalizes on the fact that SQL Server's internal representation for datetime and smalldatetime values is a two part value the first part of which is an integer representing the number of days since 1 Jan 1900, and the second part is a decimal fraction representing the fractional portion of one day (for the time) --- So the integer value 0 (zero) always translates directly into Midnight morning of 1 Jan 1900... </p>\n\n<p>or, thanks to suggestion from @brinary,</p>\n\n<pre><code>Select DateAdd(yy, @Year-1900, \n DateAdd(m, @Month - 1, @DayOfMonth - 1)) \n</code></pre>\n\n<p>Edited October 2014. As Noted by @cade Roux, SQL 2012 now has a built-in function:<br>\n<code>DATEFROMPARTS(year, month, day)</code><br>\nthat does the same thing.</p>\n\n<p>Edited 3 Oct 2016, (Thanks to @bambams for noticing this, and @brinary for fixing it), The last solution, proposed by @brinary. does not appear to work for leap years unless years addition is performed first </p>\n\n<pre><code>select dateadd(month, @Month - 1, \n dateadd(year, @Year-1900, @DayOfMonth - 1)); \n</code></pre>\n" }, { "answer_id": 5189789, "author": "Shrike", "author_id": 644128, "author_profile": "https://Stackoverflow.com/users/644128", "pm_score": 7, "selected": false, "text": "<p>Or using just a single dateadd function:</p>\n\n<pre><code>DECLARE @day int, @month int, @year int\nSELECT @day = 4, @month = 3, @year = 2011\n\nSELECT dateadd(mm, (@year - 1900) * 12 + @month - 1 , @day - 1)\n</code></pre>\n" }, { "answer_id": 10142966, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 8, "selected": false, "text": "<p>SQL Server 2012 has a wonderful and long-awaited new DATEFROMPARTS function (which will raise an error if the date is invalid - my main objection to a DATEADD-based solution to this problem):</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/hh213228.aspx\">http://msdn.microsoft.com/en-us/library/hh213228.aspx</a></p>\n\n<pre><code>DATEFROMPARTS(ycolumn, mcolumn, dcolumn)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>DATEFROMPARTS(@y, @m, @d)\n</code></pre>\n" }, { "answer_id": 11187436, "author": "Jack", "author_id": 794594, "author_profile": "https://Stackoverflow.com/users/794594", "pm_score": 3, "selected": false, "text": "<p>It is safer and neater to use an explicit starting point '19000101'</p>\n\n<pre><code>create function dbo.fnDateTime2FromParts(@Year int, @Month int, @Day int, @Hour int, @Minute int, @Second int, @Nanosecond int)\nreturns datetime2\nas\nbegin\n -- Note! SQL Server 2012 includes datetime2fromparts() function\n declare @output datetime2 = '19000101'\n set @output = dateadd(year , @Year - 1900 , @output)\n set @output = dateadd(month , @Month - 1 , @output)\n set @output = dateadd(day , @Day - 1 , @output)\n set @output = dateadd(hour , @Hour , @output)\n set @output = dateadd(minute , @Minute , @output)\n set @output = dateadd(second , @Second , @output)\n set @output = dateadd(ns , @Nanosecond , @output)\n return @output\nend\n</code></pre>\n" }, { "answer_id": 13051395, "author": "Saul Guerra", "author_id": 1771520, "author_profile": "https://Stackoverflow.com/users/1771520", "pm_score": 2, "selected": false, "text": "<p>Try </p>\n\n<pre><code>CAST(STR(DATEPART(year, DATE))+'-'+ STR(DATEPART(month, DATE)) +'-'+ STR(DATEPART(day, DATE)) AS DATETIME)\n</code></pre>\n" }, { "answer_id": 19192012, "author": "Brian", "author_id": 320, "author_profile": "https://Stackoverflow.com/users/320", "pm_score": 4, "selected": false, "text": "<p>Sql Server 2012 has a function that will create the date based on the parts (<a href=\"http://technet.microsoft.com/en-us/library/hh213228.aspx\">DATEFROMPARTS</a>). For the rest of us, here is a db function I created that will determine the date from the parts (thanks @Charles)...</p>\n\n<pre><code>IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[func_DateFromParts]'))\n DROP FUNCTION [dbo].[func_DateFromParts]\nGO\n\nCREATE FUNCTION [dbo].[func_DateFromParts]\n(\n @Year INT,\n @Month INT,\n @DayOfMonth INT,\n @Hour INT = 0, -- based on 24 hour clock (add 12 for PM :)\n @Min INT = 0,\n @Sec INT = 0\n)\nRETURNS DATETIME\nAS\nBEGIN\n\n RETURN DATEADD(second, @Sec, \n DATEADD(minute, @Min, \n DATEADD(hour, @Hour,\n DATEADD(day, @DayOfMonth - 1, \n DATEADD(month, @Month - 1, \n DATEADD(Year, @Year-1900, 0))))))\n\nEND\n\nGO\n</code></pre>\n\n<p>You can call it like this...</p>\n\n<pre><code>SELECT dbo.func_DateFromParts(2013, 10, 4, 15, 50, DEFAULT)\n</code></pre>\n\n<p>Returns...</p>\n\n<pre><code>2013-10-04 15:50:00.000\n</code></pre>\n" }, { "answer_id": 21482283, "author": "bluish", "author_id": 505893, "author_profile": "https://Stackoverflow.com/users/505893", "pm_score": 2, "selected": false, "text": "<p>I add a one-line solution if you need a datetime <strong>from both date and time parts</strong>:</p>\n\n<pre><code>select dateadd(month, (@Year -1900)*12 + @Month -1, @DayOfMonth -1) + dateadd(ss, @Hour*3600 + @Minute*60 + @Second, 0) + dateadd(ms, @Millisecond, 0)\n</code></pre>\n" }, { "answer_id": 27355251, "author": "Konstantin", "author_id": 1665649, "author_profile": "https://Stackoverflow.com/users/1665649", "pm_score": 2, "selected": false, "text": "<p>For SQL Server versions below 12 i can recommend use of <code>CAST</code> in combination with <code>SET DATEFORMAT</code></p>\n\n<pre><code>-- 26 February 2015\nSET DATEFORMAT dmy\nSELECT CAST('26-2-2015' AS DATE)\n\nSET DATEFORMAT ymd\nSELECT CAST('2015-2-26' AS DATE)\n</code></pre>\n\n<p>how you create those strings is up to you</p>\n" }, { "answer_id": 28923195, "author": "user3141962", "author_id": 3141962, "author_profile": "https://Stackoverflow.com/users/3141962", "pm_score": 1, "selected": false, "text": "<p>Try this query:</p>\n\n<pre><code> SELECT SUBSTRING(CONVERT(VARCHAR,JOINGDATE,103),7,4)AS\n YEAR,SUBSTRING(CONVERT(VARCHAR,JOINGDATE,100),1,2)AS\nMONTH,SUBSTRING(CONVERT(VARCHAR,JOINGDATE,100),4,3)AS DATE FROM EMPLOYEE1\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>2014 Ja 1\n2015 Ja 1\n2014 Ja 1\n2015 Ja 1\n2012 Ja 1\n2010 Ja 1\n2015 Ja 1\n</code></pre>\n" }, { "answer_id": 36937904, "author": "Gouri Shankar Aechoor", "author_id": 3849742, "author_profile": "https://Stackoverflow.com/users/3849742", "pm_score": 0, "selected": false, "text": "<p>I personally Prefer Substring as it provide cleansing options and ability to split the string as needed. The assumption is that the data is of the format 'dd, mm, yyyy'.</p>\n\n<pre><code>--2012 and above\nSELECT CONCAT (\n RIGHT(REPLACE(@date, ' ', ''), 4)\n ,'-'\n ,RIGHT(CONCAT('00',SUBSTRING(REPLACE(@date, ' ', ''), CHARINDEX(',', REPLACE(@date, ' ', '')) + 1, LEN(REPLACE(@date, ' ', '')) - CHARINDEX(',', REPLACE(@date, ' ', '')) - 5)),2)\n ,'-'\n ,RIGHT(CONCAT('00',SUBSTRING(REPLACE(@date, ' ', ''), 1, CHARINDEX(',', REPLACE(@date, ' ', '')) - 1)),2)\n )\n\n--2008 and below\nSELECT RIGHT(REPLACE(@date, ' ', ''), 4)\n +'-'\n +RIGHT('00'+SUBSTRING(REPLACE(@date, ' ', ''), CHARINDEX(',', REPLACE(@date, ' ', '')) + 1, LEN(REPLACE(@date, ' ', '')) - CHARINDEX(',', REPLACE(@date, ' ', '')) - 5),2)\n +'-'\n +RIGHT('00'+SUBSTRING(REPLACE(@date, ' ', ''), 1, CHARINDEX(',', REPLACE(@date, ' ', '')) - 1),2)\n</code></pre>\n\n<p>Here is a demonstration of how it can be sued if the data is stored in a column. Needless to say, its ideal to check the result-set before applying to the column</p>\n\n<pre><code>DECLARE @Table TABLE (ID INT IDENTITY(1000,1), DateString VARCHAR(50), DateColumn DATE)\n\nINSERT INTO @Table\nSELECT'12, 1, 2007',NULL\nUNION\nSELECT'15,3, 2007',NULL\nUNION\nSELECT'18, 11 , 2007',NULL\nUNION\nSELECT'22 , 11, 2007',NULL\nUNION\nSELECT'30, 12, 2007 ',NULL\n\nUPDATE @Table\nSET DateColumn = CONCAT (\n RIGHT(REPLACE(DateString, ' ', ''), 4)\n ,'-'\n ,RIGHT(CONCAT('00',SUBSTRING(REPLACE(DateString, ' ', ''), CHARINDEX(',', REPLACE(DateString, ' ', '')) + 1, LEN(REPLACE(DateString, ' ', '')) - CHARINDEX(',', REPLACE(DateString, ' ', '')) - 5)),2)\n ,'-'\n ,RIGHT(CONCAT('00',SUBSTRING(REPLACE(DateString, ' ', ''), 1, CHARINDEX(',', REPLACE(DateString, ' ', '')) - 1)),2)\n ) \n\nSELECT ID,DateString,DateColumn\nFROM @Table\n</code></pre>\n" }, { "answer_id": 37063697, "author": "Marcelo Lujan", "author_id": 1303723, "author_profile": "https://Stackoverflow.com/users/1303723", "pm_score": 4, "selected": false, "text": "<p>You can also use </p>\n\n<pre><code>select DATEFROMPARTS(year, month, day) as ColDate, Col2, Col3 \nFrom MyTable Where DATEFROMPARTS(year, month, day) Between @DateIni and @DateEnd\n</code></pre>\n\n<p>Works in SQL since ver.2012 and AzureSQL</p>\n" }, { "answer_id": 56779214, "author": "Peter Bojanczyk", "author_id": 11467549, "author_profile": "https://Stackoverflow.com/users/11467549", "pm_score": 2, "selected": false, "text": "<p>I know the OP is asking for SQL 2005 answer but the question is pretty old so if you're running SQL 2012 or above you can use the following:</p>\n\n<pre><code>SELECT DATEADD(DAY, 1, EOMONTH(@somedate, -1))\n</code></pre>\n\n<p>Reference:\n<a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/eomonth-transact-sql?view=sql-server-2017&amp;viewFallbackFrom=sql-server-previousversions\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/sql/t-sql/functions/eomonth-transact-sql?view=sql-server-2017&amp;viewFallbackFrom=sql-server-previousversions</a></p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23133/" ]
I am trying to convert a date with individual parts such as 12, 1, 2007 into a datetime in SQL Server 2005. I have tried the following: ``` CAST(DATEPART(year, DATE)+'-'+ DATEPART(month, DATE) +'-'+ DATEPART(day, DATE) AS DATETIME) ``` but this results in the wrong date. What is the correct way to turn the three date values into a proper datetime format.
Assuming `y, m, d` are all `int`, how about: ``` CAST(CAST(y AS varchar) + '-' + CAST(m AS varchar) + '-' + CAST(d AS varchar) AS DATETIME) ``` Please see [my other answer](https://stackoverflow.com/a/10142966/18255) for SQL Server 2012 and above
266,927
<p>I receive an error message when exposing an ADO.NET Data Service using an Entity Framework data model that contains an entity (called "Case") with an internal setter on a property. If I modify the setter to be public (using the entity designer), the data services works fine.</p> <p>I don’t need the entity "Case" exposed in the data service, so I tried to limit which entities are exposed using SetEntitySetAccessRule. This didn’t work, and service end point fails with the same error.</p> <pre><code>public static void InitializeService(IDataServiceConfiguration config) { config.SetEntitySetAccessRule("User", EntitySetRights.AllRead); } </code></pre> <p>The error message is reported in a browser when the .svc endpoint is called. It is very generic, and reads “Request Error. The server encountered an error processing the request. See server logs for more details.” Unfortunately, there are no entries in the System and Application event logs.</p> <p>I found this <a href="https://stackoverflow.com/questions/54380/problem-rolling-out-adonet-data-service-application-to-iis">stackoverflow question</a> that shows how to configure tracing on the service. After doing so, the following NullReferenceExceptoin error was reported in the trace log.</p> <p>Does anyone know how to avoid this exception when including an entity with an internal setter?</p> <pre><code>&lt;E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent"&gt; &lt;System xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system"&gt; &lt;EventID&gt;131076&lt;/EventID&gt; &lt;Type&gt;3&lt;/Type&gt; &lt;SubType Name="Error"&gt;0&lt;/SubType&gt; &lt;Level&gt;2&lt;/Level&gt; &lt;TimeCreated SystemTime="2008-11-05T22:30:44.1523578Z" /&gt; &lt;Source Name="System.ServiceModel" /&gt; &lt;Correlation ActivityID="{da77ee97-960f-4275-a5e7-a181c0b024b1}" /&gt; &lt;Execution ProcessName="WebDev.WebServer" ProcessID="6388" ThreadID="8" /&gt; &lt;Channel /&gt; &lt;Computer&gt;MOTOJIM&lt;/Computer&gt; &lt;/System&gt; &lt;ApplicationData&gt; &lt;TraceData&gt; &lt;DataItem&gt; &lt;TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Error"&gt; &lt;TraceIdentifier&gt;http://msdn.microsoft.com/en-US/library/System.ServiceModel.Diagnostics.TraceHandledException.aspx&lt;/TraceIdentifier&gt; &lt;Description&gt;Handling an exception.&lt;/Description&gt; &lt;AppDomain&gt;685a2910-19-128703978432492675&lt;/AppDomain&gt; &lt;Exception&gt; &lt;ExceptionType&gt;System.NullReferenceException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089&lt;/ExceptionType&gt; &lt;Message&gt;Object reference not set to an instance of an object.&lt;/Message&gt; &lt;StackTrace&gt; at System.Data.Services.Providers.ObjectContextServiceProvider.PopulateMemberMetadata(ResourceType resourceType, MetadataWorkspace workspace, IDictionary`2 entitySets, IDictionary`2 knownTypes) at System.Data.Services.Providers.ObjectContextServiceProvider.PopulateMetadata(IDictionary`2 knownTypes, IDictionary`2 entitySets) at System.Data.Services.Providers.BaseServiceProvider.PopulateMetadata() at System.Data.Services.DataService`1.CreateProvider(Type dataServiceType, Object dataSourceInstance, DataServiceConfiguration&amp;amp; configuration) at System.Data.Services.DataService`1.EnsureProviderAndConfigForRequest() at System.Data.Services.DataService`1.ProcessRequestForMessage(Stream messageBody) at SyncInvokeProcessRequestForMessage(Object , Object[] , Object[] ) at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]&amp;amp; outputs) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp;amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp;amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc&amp;amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc&amp;amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc&amp;amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc&amp;amp; rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet) &lt;/StackTrace&gt; &lt;ExceptionString&gt;System.NullReferenceException: Object reference not set to an instance of an object. at System.Data.Services.Providers.ObjectContextServiceProvider.PopulateMemberMetadata(ResourceType resourceType, MetadataWorkspace workspace, IDictionary`2 entitySets, IDictionary`2 knownTypes) at System.Data.Services.Providers.ObjectContextServiceProvider.PopulateMetadata(IDictionary`2 knownTypes, IDictionary`2 entitySets) at System.Data.Services.Providers.BaseServiceProvider.PopulateMetadata() at System.Data.Services.DataService`1.CreateProvider(Type dataServiceType, Object dataSourceInstance, DataServiceConfiguration&amp;amp; configuration) at System.Data.Services.DataService`1.EnsureProviderAndConfigForRequest() at System.Data.Services.DataService`1.ProcessRequestForMessage(Stream messageBody) at SyncInvokeProcessRequestForMessage(Object , Object[] , Object[] ) at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]&amp;amp; outputs) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp;amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp;amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc&amp;amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc&amp;amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc&amp;amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc&amp;amp; rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)&lt;/ExceptionString&gt; &lt;/Exception&gt; &lt;/TraceRecord&gt; &lt;/DataItem&gt; &lt;/TraceData&gt; &lt;/ApplicationData&gt; &lt;/E2ETraceEvent&gt; </code></pre>
[ { "answer_id": 421500, "author": "ggponti", "author_id": 6840, "author_profile": "https://Stackoverflow.com/users/6840", "pm_score": 0, "selected": false, "text": "<p>I had a similar problem, and it was caused by passing the wrong class to DataService. You need to pass the data entities class of the data model.</p>\n\n<pre><code>public class WebDataService : DataService&lt; DataModel.DataEntities &gt;\n</code></pre>\n" }, { "answer_id": 3090364, "author": "Jakob Gade", "author_id": 10932, "author_profile": "https://Stackoverflow.com/users/10932", "pm_score": 2, "selected": false, "text": "<p>I recently ran into a similar issue, and the fix in my case was changinghe the name of the EntitySetAccessRule to \"*\", like this:</p>\n\n<pre><code>public static void InitializeService(DataServiceConfiguration config)\n{\n config.SetEntitySetAccessRule(\"*\", EntitySetRights.All);\n config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;\n}\n</code></pre>\n" }, { "answer_id": 6018883, "author": "Peter", "author_id": 563744, "author_profile": "https://Stackoverflow.com/users/563744", "pm_score": 0, "selected": false, "text": "<p>I had the same problem, and the solution turned out to be very simple: although my table name and the generated entity object is the singular \"Order\", I need to refer to it in this context as \"Orders\". Still getting my head around that. just EDM standard.</p>\n\n<pre><code>config.SetEntitySetAccessRule(\"Orders\", EntitySetRights.All);\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 21870792, "author": "Jakub Kuszneruk", "author_id": 1565454, "author_profile": "https://Stackoverflow.com/users/1565454", "pm_score": 0, "selected": false, "text": "<p>I've had similar issue caused by EF6.</p>\n\n<p>According to <a href=\"http://blogs.msdn.com/b/odatateam/archive/2013/10/02/using-wcf-data-services-5-6-0-with-entity-framework-6.aspx\" rel=\"nofollow\">this article</a> changing</p>\n\n<pre><code>public class WebDataService : DataService&lt; DataModel.DataEntities &gt;\n</code></pre>\n\n<p>to</p>\n\n<pre><code>public class WebDataService : EntityFrameworkDataService&lt; DataModel.DataEntities &gt;\n</code></pre>\n\n<p>should help</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33496/" ]
I receive an error message when exposing an ADO.NET Data Service using an Entity Framework data model that contains an entity (called "Case") with an internal setter on a property. If I modify the setter to be public (using the entity designer), the data services works fine. I don’t need the entity "Case" exposed in the data service, so I tried to limit which entities are exposed using SetEntitySetAccessRule. This didn’t work, and service end point fails with the same error. ``` public static void InitializeService(IDataServiceConfiguration config) { config.SetEntitySetAccessRule("User", EntitySetRights.AllRead); } ``` The error message is reported in a browser when the .svc endpoint is called. It is very generic, and reads “Request Error. The server encountered an error processing the request. See server logs for more details.” Unfortunately, there are no entries in the System and Application event logs. I found this [stackoverflow question](https://stackoverflow.com/questions/54380/problem-rolling-out-adonet-data-service-application-to-iis) that shows how to configure tracing on the service. After doing so, the following NullReferenceExceptoin error was reported in the trace log. Does anyone know how to avoid this exception when including an entity with an internal setter? ``` <E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent"> <System xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system"> <EventID>131076</EventID> <Type>3</Type> <SubType Name="Error">0</SubType> <Level>2</Level> <TimeCreated SystemTime="2008-11-05T22:30:44.1523578Z" /> <Source Name="System.ServiceModel" /> <Correlation ActivityID="{da77ee97-960f-4275-a5e7-a181c0b024b1}" /> <Execution ProcessName="WebDev.WebServer" ProcessID="6388" ThreadID="8" /> <Channel /> <Computer>MOTOJIM</Computer> </System> <ApplicationData> <TraceData> <DataItem> <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Error"> <TraceIdentifier>http://msdn.microsoft.com/en-US/library/System.ServiceModel.Diagnostics.TraceHandledException.aspx</TraceIdentifier> <Description>Handling an exception.</Description> <AppDomain>685a2910-19-128703978432492675</AppDomain> <Exception> <ExceptionType>System.NullReferenceException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType> <Message>Object reference not set to an instance of an object.</Message> <StackTrace> at System.Data.Services.Providers.ObjectContextServiceProvider.PopulateMemberMetadata(ResourceType resourceType, MetadataWorkspace workspace, IDictionary`2 entitySets, IDictionary`2 knownTypes) at System.Data.Services.Providers.ObjectContextServiceProvider.PopulateMetadata(IDictionary`2 knownTypes, IDictionary`2 entitySets) at System.Data.Services.Providers.BaseServiceProvider.PopulateMetadata() at System.Data.Services.DataService`1.CreateProvider(Type dataServiceType, Object dataSourceInstance, DataServiceConfiguration&amp; configuration) at System.Data.Services.DataService`1.EnsureProviderAndConfigForRequest() at System.Data.Services.DataService`1.ProcessRequestForMessage(Stream messageBody) at SyncInvokeProcessRequestForMessage(Object , Object[] , Object[] ) at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]&amp; outputs) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet) </StackTrace> <ExceptionString>System.NullReferenceException: Object reference not set to an instance of an object. at System.Data.Services.Providers.ObjectContextServiceProvider.PopulateMemberMetadata(ResourceType resourceType, MetadataWorkspace workspace, IDictionary`2 entitySets, IDictionary`2 knownTypes) at System.Data.Services.Providers.ObjectContextServiceProvider.PopulateMetadata(IDictionary`2 knownTypes, IDictionary`2 entitySets) at System.Data.Services.Providers.BaseServiceProvider.PopulateMetadata() at System.Data.Services.DataService`1.CreateProvider(Type dataServiceType, Object dataSourceInstance, DataServiceConfiguration&amp; configuration) at System.Data.Services.DataService`1.EnsureProviderAndConfigForRequest() at System.Data.Services.DataService`1.ProcessRequestForMessage(Stream messageBody) at SyncInvokeProcessRequestForMessage(Object , Object[] , Object[] ) at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]&amp; outputs) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</ExceptionString> </Exception> </TraceRecord> </DataItem> </TraceData> </ApplicationData> </E2ETraceEvent> ```
I recently ran into a similar issue, and the fix in my case was changinghe the name of the EntitySetAccessRule to "\*", like this: ``` public static void InitializeService(DataServiceConfiguration config) { config.SetEntitySetAccessRule("*", EntitySetRights.All); config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; } ```
266,931
<p>It seems that nginx is used with php, ruby and python. </p> <p>Anyone has an example of how to setup nginx to work with jetty/tomcat in backend? </p> <p>Thanks.</p>
[ { "answer_id": 267072, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 4, "selected": true, "text": "<p>nginx can forward via HTTP protocol, so just point it to the correct port and you're set:</p>\n\n<pre><code>server {\n location /anything {\n proxy_pass http://localhost:8080/whatever;\n }\n}\n</code></pre>\n" }, { "answer_id": 267077, "author": "Florin", "author_id": 34565, "author_profile": "https://Stackoverflow.com/users/34565", "pm_score": 4, "selected": false, "text": "<p>Right. I guess I qualify as a self learner, don't I.</p>\n\n<p>Just add these lines within the http { } scope of the nginx.conf file:</p>\n\n<pre><code>server {\n listen 80;\n server_name mydomain.com www.mydomain.com;\n access_log /var/log/nginx_67_log main;\n location / {\n proxy_pass http://127.0.0.1:8080;\n proxy_redirect off;\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n }\n}\n</code></pre>\n\n<p>I have to try now gzip, SSL and dojo cometd and see if I can upgrade to nginx.\nAny clues are welcome.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34565/" ]
It seems that nginx is used with php, ruby and python. Anyone has an example of how to setup nginx to work with jetty/tomcat in backend? Thanks.
nginx can forward via HTTP protocol, so just point it to the correct port and you're set: ``` server { location /anything { proxy_pass http://localhost:8080/whatever; } } ```
266,988
<p>I'm working on a Facebook FBML controls library and would like to create my FBML controls somewhat patterned like the ASP.NET WebControls library. I have a base class that handles rendering by default; here's my render method:</p> <pre><code> protected override void Render(HtmlTextWriter writer) { AddAttributesToRender(writer); if (UseXfbmlSemantics) { writer.RenderBeginTag(ElementName); writer.EndRender(); writer.RenderEndTag(); } else { writer.RenderBeginTag(ElementName); writer.RenderEndTag(); } } </code></pre> <p>What I would like is for the rendering to be modified based on UseXfbmlSemantics - if it's true, it should render, for instance:</p> <pre><code>&lt;fb:name uid="10300399458"&gt;&lt;/fb:name&gt;</code></pre> <p>When it's false, it should render with a self-closing tag:</p> <pre><code>&lt;fb:name uid="10300399458" /&gt;</code></pre> <p>I can get the "true" condition to work almost correctly, but the self-closing tag seems to be incompatible with the Render- set of methods. Unfortunately if that's the case it also means that the AddAttributesToRender pattern wouldn't work, either. What it's actually producing is this:</p> <pre><code> &lt;fb:name uid="10300399458"&gt; &lt;/fb:name&gt; </code></pre> <p>How can I get HtmlTextWriter (or which HtmlTextWriter do I need to use) to make it render a self-closing tag? Or, at the very least, how can I make it not render that interim space (so that the opening and closing tags are immediately next to one another)?</p>
[ { "answer_id": 270417, "author": "Jason Hernandez", "author_id": 34863, "author_profile": "https://Stackoverflow.com/users/34863", "pm_score": 4, "selected": true, "text": "<p>This should get you going - it will render as <code>&lt;fb:name uid=\"00101010101\"/&gt;</code>. You could also override the RenderBeginTag, RenderContents, RenderEndTag. Depending on what you are doing there may be some other things going on in RenderControl that you need. You could also look into using a ControlAdapter, this may give you better separation of control functionality VS control html writing. </p>\n\n<pre><code>public class FbName:System.Web.UI.WebControls.WebControl\n{\n\n protected override string TagName\n {\n get\n {\n return \"fb:name\";\n }\n }\n\n public override void RenderControl(HtmlTextWriter writer)\n { \n RenderBeginTag(writer);// render only the begin tag.\n //base.RenderContents(writer);\n //base.RenderEndTag(writer);\n }\n\n public override void RenderBeginTag(HtmlTextWriter writer)\n {\n writer.Write(\"&lt;\" + this.TagName);\n writer.WriteAttribute(\"uid\", \"00101010101\");\n writer.Write(\"/&gt;\");\n\n }\n}\n</code></pre>\n\n<p>-Jason</p>\n" }, { "answer_id": 7230207, "author": "user917829", "author_id": 917829, "author_profile": "https://Stackoverflow.com/users/917829", "pm_score": 2, "selected": false, "text": "<p>I'd recommend to use HtmlTextWriter constants:</p>\n\n<pre><code> protected override void Render(HtmlTextWriter writer)\n {\n AddAttributesToRender(writer);\n writer.Write(HtmlTextWriter.TagLeftChar); // '&lt;'\n writer.Write(this.TagName);\n writer.Write(HtmlTextWriter.SpaceChar); // ' '\n writer.WriteAttribute(\"uid\", \"00101010101\");\n writer.Write(HtmlTextWriter.SpaceChar); // ' '\n writer.Write(HtmlTextWriter.SelfClosingTagEnd); // \"/&gt;\"\n }\n</code></pre>\n" }, { "answer_id": 25813598, "author": "Tony", "author_id": 1985479, "author_profile": "https://Stackoverflow.com/users/1985479", "pm_score": 3, "selected": false, "text": "<p>Since this is the top SO question that comes up when searching for \"HtmlTextWriter self closing tag\", this is for anyone coming here that wants to know how to do it:</p>\n\n<pre><code>writer.WriteBeginTag(\"tag\");\nwriter.WriteAttribute(\"attribute\", \"attribute value\");\n// ... add other attributes here ...\nwriter.Write(HtmlTextWriter.SelfClosingTagEnd);\n</code></pre>\n" }, { "answer_id": 28737729, "author": "Med.Amine.Touil", "author_id": 3252679, "author_profile": "https://Stackoverflow.com/users/3252679", "pm_score": -1, "selected": false, "text": "<p>if you use Visual studio go by these steps:</p>\n\n<blockquote>\n <p>Tools ---> Options ---> Text Editor ---> HTML ----> Formatting --->\n remove Auto insert close tag</p>\n</blockquote>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34224/" ]
I'm working on a Facebook FBML controls library and would like to create my FBML controls somewhat patterned like the ASP.NET WebControls library. I have a base class that handles rendering by default; here's my render method: ``` protected override void Render(HtmlTextWriter writer) { AddAttributesToRender(writer); if (UseXfbmlSemantics) { writer.RenderBeginTag(ElementName); writer.EndRender(); writer.RenderEndTag(); } else { writer.RenderBeginTag(ElementName); writer.RenderEndTag(); } } ``` What I would like is for the rendering to be modified based on UseXfbmlSemantics - if it's true, it should render, for instance: ``` <fb:name uid="10300399458"></fb:name> ``` When it's false, it should render with a self-closing tag: ``` <fb:name uid="10300399458" /> ``` I can get the "true" condition to work almost correctly, but the self-closing tag seems to be incompatible with the Render- set of methods. Unfortunately if that's the case it also means that the AddAttributesToRender pattern wouldn't work, either. What it's actually producing is this: ``` <fb:name uid="10300399458"> </fb:name> ``` How can I get HtmlTextWriter (or which HtmlTextWriter do I need to use) to make it render a self-closing tag? Or, at the very least, how can I make it not render that interim space (so that the opening and closing tags are immediately next to one another)?
This should get you going - it will render as `<fb:name uid="00101010101"/>`. You could also override the RenderBeginTag, RenderContents, RenderEndTag. Depending on what you are doing there may be some other things going on in RenderControl that you need. You could also look into using a ControlAdapter, this may give you better separation of control functionality VS control html writing. ``` public class FbName:System.Web.UI.WebControls.WebControl { protected override string TagName { get { return "fb:name"; } } public override void RenderControl(HtmlTextWriter writer) { RenderBeginTag(writer);// render only the begin tag. //base.RenderContents(writer); //base.RenderEndTag(writer); } public override void RenderBeginTag(HtmlTextWriter writer) { writer.Write("<" + this.TagName); writer.WriteAttribute("uid", "00101010101"); writer.Write("/>"); } } ``` -Jason
266,997
<p>I'm trying to extract all matches from a EBML definition, which is something like this:</p> <pre><code>| + A track | + Track number: 3 | + Track UID: 724222477 | + Track type: subtitles ... | + Language: eng ... | + A track | + Track number: 4 | + Track UID: 745646561 | + Track type: subtitles ... | + Language: jpn ... </code></pre> <p>I want all occurrences of "Language: ???" when preceded by "Track type: subtitles". I tried several variations of this:</p> <pre><code>Track type: subtitles.*Language: (\w\w\w) </code></pre> <p>I'm using the multi-line modifier in Ruby so it matches newlines (like the 's' modifier in other languages).</p> <p>This works to get the <strong>last</strong> occurrence, which in the example above, would be 'jpn', for example:</p> <pre><code>string.scan(/Track type: subtitles.*Language: (\w\w\w)/m) =&gt; [["jpn"]] </code></pre> <p>The result I'd like:</p> <pre><code>=&gt; [["eng"], ["jpn"]] </code></pre> <p>What would be a correct regex to accomplish this?</p>
[ { "answer_id": 267007, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 2, "selected": false, "text": "<p>You need to use a lazy quantifier instead of <code>.*</code>. Try this:</p>\n\n<pre><code>/Track type: subtitles.*?Language: (\\w\\w\\w)/m\n</code></pre>\n\n<p>This should get you the first occurrence of \"<code>Language: ???</code>\" after each \"<code>Track type: subtitles:</code>\". But it would get confused if some track (of type <code>subtitles</code>) would be missing the <code>Language</code> field.</p>\n\n<hr>\n\n<p>Another way to do this would be:</p>\n\n<pre><code>/^\\| \\+ (?:(?!^\\| \\+).)*?\\+ Track type: subtitles$(?:(?!^\\| \\+).)*?^\\| \\+ Language: (\\w+)$/m\n</code></pre>\n\n<p>Looks somewhat messy, but should take care of the problem with the previous one.</p>\n\n<hr>\n\n<p>A cleaner way would be to tokenize the string:</p>\n\n<pre><code>/^\\| \\+ ([^\\r\\n]+)|^\\| \\+ Track type: (subtitles)|^\\| \\+ Language: (\\w+)/m\n</code></pre>\n\n<p><em>(Take note of the number of spaces)</em></p>\n\n<p>For each match, you check which of the capture groups that are defined. Only one group will have any value for any single match.</p>\n\n<ul>\n<li>If it is the <strong>first</strong> group, a new track has started. Discard any stored information about the previous track.</li>\n<li>If it is the <strong>second</strong> group, the current track is of type <code>subtitles</code>.</li>\n<li>If it is the <strong>third</strong> group, the language of this track is found.</li>\n<li>Whenever you know the language of a track, and that it is of type <code>subtitles</code>, report it.</li>\n</ul>\n" }, { "answer_id": 267012, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 4, "selected": true, "text": "<p>You need to make your regex non-greedy by changing this:</p>\n\n<pre><code>.*\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code>.*?\n</code></pre>\n\n<p>Your regex is matching from the first occurence of <code>Track type: subtitles</code> to the last occurence of <code>Language: (\\w\\w\\w)</code>. Making it non-greedy will work because it matches as few characters as possible. </p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/266997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16957/" ]
I'm trying to extract all matches from a EBML definition, which is something like this: ``` | + A track | + Track number: 3 | + Track UID: 724222477 | + Track type: subtitles ... | + Language: eng ... | + A track | + Track number: 4 | + Track UID: 745646561 | + Track type: subtitles ... | + Language: jpn ... ``` I want all occurrences of "Language: ???" when preceded by "Track type: subtitles". I tried several variations of this: ``` Track type: subtitles.*Language: (\w\w\w) ``` I'm using the multi-line modifier in Ruby so it matches newlines (like the 's' modifier in other languages). This works to get the **last** occurrence, which in the example above, would be 'jpn', for example: ``` string.scan(/Track type: subtitles.*Language: (\w\w\w)/m) => [["jpn"]] ``` The result I'd like: ``` => [["eng"], ["jpn"]] ``` What would be a correct regex to accomplish this?
You need to make your regex non-greedy by changing this: ``` .* ``` To this: ``` .*? ``` Your regex is matching from the first occurence of `Track type: subtitles` to the last occurence of `Language: (\w\w\w)`. Making it non-greedy will work because it matches as few characters as possible.
267,001
<p>I'm trying to save the output of an vector image drawin in Java2D to an SWF file. There are great libraries for saving java2D output as things like SVG (BATIK) and PDF(itext) but I can't find one for SWF. Any ideas?</p>
[ { "answer_id": 267023, "author": "rmeador", "author_id": 10861, "author_profile": "https://Stackoverflow.com/users/10861", "pm_score": 1, "selected": false, "text": "<p>Flash generally uses SVG as its native format. You could export to SVG and then write a trivial Flash program to embed and display the image. But why use Flash at all? Most browsers are capable of displaying SVG nowadays.</p>\n\n<p><strong>Edit</strong>: I don't know why I was downvoted for a clearly correct answer. I can understand not being upvoted for not having the best answer (I fully acknowledge that this soltuion isn't ideal), but I really don't think it deserves a downvote. You can consult the section in the middle of <a href=\"http://livedocs.adobe.com/flex/3/html/help.html?content=embed_4.html\" rel=\"nofollow noreferrer\">this page</a> about embedding SVG in Flex programs. For those of you who aren't familiar, Flex is an adobe toolkit/library that generates SWF programs that run in the normal Flash player. Many (all?) of the normal Flash libraries are available to it. It uses ActionScript. For you doubters, here's a snippet showing exactly how you do it, copied from a Flex program I wrote. It should go inside an MXML file.</p>\n\n<pre><code>&lt;mx:Script&gt;&lt;![CDATA[\n\n[Embed(source=\"../images/down.svg\")]\n[Bindable]\nprotected var drillDownImage:Class;\n\n]]&gt;&lt;/mx:Script&gt;\n\n&lt;mx:HBox width=\"50%\" horizontalAlign=\"right\"&gt;\n &lt;mx:Image id=\"drillDownButton\" source=\"{drillDownImage}\" height=\"20\" width=\"20\" click=\"drillDown();\" /&gt;\n&lt;/mx:HBox&gt;\n</code></pre>\n\n<p>Now all you need to do is wrap that in an appropriate MXML file, maybe import some controls packages for the HBox and Image tags, and you're good to go. The example in the link I provided should be sufficient for you to figure it out.</p>\n" }, { "answer_id": 267178, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "<p>Mm, I know some libraries outputting Flash content, like <a href=\"http://www.swift-tools.net/swift-generator.html\" rel=\"nofollow noreferrer\"></a> or <a href=\"http://www.libming.org/\" rel=\"nofollow noreferrer\" title=\"Ming\">Ming</a>, or even <a href=\"http://haxe.org/\" rel=\"nofollow noreferrer\">Haxe</a>, a language which can be \"translated\" into JavaScript, Flash or PHP code... But I know no Java library.</p>\n\n<p>Searching a bit (I am curious), I found a commercial <a href=\"http://big.faceless.org/products/graph/index.jsp\" rel=\"nofollow noreferrer\" title=\"Java Graph Library\">Java Graph Library</a>, probably closed source, a Flash player in Java, libraries to manipulate ActionScript source code or <a href=\"http://www.badgers-in-foil.co.uk/projects/jactionscript/\" rel=\"nofollow noreferrer\" title=\"ActionScript bytecode\">bytecode</a>... Ah, the latter points to <a href=\"http://www.anotherbigidea.com/javaswf/\" rel=\"nofollow noreferrer\" title=\"JavaSWF2\">JavaSWF2</a> which is supposed to be able to generate SWF. I found also a <a href=\"http://drawswf.sourceforge.net/\" rel=\"nofollow noreferrer\" title=\"DrawSWF\">DrawSWF</a> which uses... JavaSWF2 library as back-end!</p>\n\n<p>PS.: Also found <a href=\"http://www.flagstonesoftware.com/transform/index.html\" rel=\"nofollow noreferrer\" title=\"Transform SWF\">Transform SWF</a>. Looks promising.</p>\n" }, { "answer_id": 268235, "author": "jcoder", "author_id": 417292, "author_profile": "https://Stackoverflow.com/users/417292", "pm_score": 0, "selected": false, "text": "<p>As far as I know flash does not use SVG at all. I'm not at all convinced that the answer mentioning that is correct. (But I can't just add this as a comment as I wanted to as I don't have enough points...)</p>\n" }, { "answer_id": 268670, "author": "jcoder", "author_id": 417292, "author_profile": "https://Stackoverflow.com/users/417292", "pm_score": 1, "selected": false, "text": "<p>This probably isn't what you are looking for but I'll throw it in as a suggestion -</p>\n\n<p>Have you considered making your java output actionscript to draw the vectors using the flash drawing API and compile it to a .SWF file using the free flex as3 compiler? If you don't use the flex library it doesn't include any of it. Your java code would just output the drawing lines surrounded by a template for the actionscript code.</p>\n\n<p>This makes Test.swf that draws a square and compiles down to 610 bytes for me.</p>\n\n<p>If you need to convert on the fly then this would be slow but for preconverted drawings it would be simple.</p>\n\n<pre><code>package{\n import flash.display.Sprite;\n\n public class Test extends Sprite{\n public function Test (){\n\n // Start of lines generated by your java\n graphics.lineStyle(1, 0, 1);\n graphics.lineTo(100, 0);\n graphics.lineTo(100, 100);\n graphics.lineTo(0, 100);\n graphics.lineTo(0, 0);\n // End of lines generated by your java\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 269714, "author": "delux247", "author_id": 5569, "author_profile": "https://Stackoverflow.com/users/5569", "pm_score": 4, "selected": true, "text": "<p>I just got an example to work using the <a href=\"http://opensource.adobe.com/svn/opensource/flex/sdk/trunk/modules/swfutils/src/java/flash/graphics/g2d/SpriteGraphics2D.java\" rel=\"nofollow noreferrer\">SpriteGraphics2D</a> object from <a href=\"http://opensource.adobe.com/wiki/display/flexsdk/Downloads\" rel=\"nofollow noreferrer\">Adobe's Flex 3</a>. FYI... Flex 3 is now open source.</p>\n\n<blockquote>\n <p><em>(from SpriteGraphics2D javadoc)</em> <a href=\"http://opensource.adobe.com/svn/opensource/flex/sdk/trunk/modules/swfutils/src/java/flash/graphics/g2d/SpriteGraphics2D.java\" rel=\"nofollow noreferrer\">SpriteGraphics2D</a> is a SWF specific implementation of Java2D's Graphics2D API. Calls to this class are converted into a TagList that can be used to construct a SWF Sprite.</p>\n</blockquote>\n\n<p>I figured this out by looking at these two classes <a href=\"http://opensource.adobe.com/svn/opensource/flex/sdk/trunk/modules/swfutils/test/java/flash/swf/builder/types/CubicCurveTest.java\" rel=\"nofollow noreferrer\">CubicCurveTest.java</a> and <a href=\"http://opensource.adobe.com/svn/opensource/flex/sdk/trunk/modules/compiler/src/java/flash/svg/SpriteTranscoder.java\" rel=\"nofollow noreferrer\">SpriteTranscoder.java</a>.</p>\n\n<p>The only two jars needed to run this example are swfutils.jar and batik-awt-util.jar which can be <a href=\"http://opensource.adobe.com/wiki/display/flexsdk/Downloads\" rel=\"nofollow noreferrer\">downloaded here</a>.</p>\n\n<p>Here is my example code...</p>\n\n<pre><code> // Create the SpriteGraphics2D object\n SpriteGraphics2D g = new SpriteGraphics2D(100, 100);\n\n // Draw on to the graphics object\n Font font = new Font(\"Serif\", Font.PLAIN, 16);\n g.setFont(font); \n g.drawString(\"Test swf\", 30, 30); \n g.draw(new Line2D.Double(5, 5, 50, 60));\n g.draw(new Line2D.Double(50, 60, 150, 40));\n g.draw(new Line2D.Double(150, 40, 160, 10));\n\n // Create a new empty movie\n Movie m = new Movie();\n m.version = 7;\n m.bgcolor = new SetBackgroundColor(SwfUtils.colorToInt(255, 255, 255));\n m.framerate = 12;\n m.frames = new ArrayList(1);\n m.frames.add(new Frame());\n m.size = new Rect(11000, 8000);\n\n // Get the DefineSprite from the graphics object\n DefineSprite tag = g.defineSprite(\"swf-test\");\n\n // Place the DefineSprite on the first frame\n Frame frame1 = (Frame) m.frames.get(0);\n Matrix mt = new Matrix(0, 0);\n frame1.controlTags.add(new PlaceObject(mt, tag, 1, null));\n\n TagEncoder tagEncoder = new TagEncoder();\n MovieEncoder movieEncoder = new MovieEncoder(tagEncoder);\n movieEncoder.export(m);\n\n //Write to file\n FileOutputStream fos = new FileOutputStream(new File(\"/test.swf\"));\n tagEncoder.writeTo(fos);\n</code></pre>\n" }, { "answer_id": 440180, "author": "Rich Apodaca", "author_id": 54426, "author_profile": "https://Stackoverflow.com/users/54426", "pm_score": 0, "selected": false, "text": "<p>Check out <a href=\"http://www.flagstonesoftware.com/transform/\" rel=\"nofollow noreferrer\">Transform SWF</a>. The API takes some time to get used to, but it comes with some really helpful examples to get you started. I've used it myself and it work very well.</p>\n\n<p>My advice would be to skip SVG altogether as a way to go from Java2D to SWF. The SVG that Batik produces behaves very badly with the solutions I tried to import SVG into Flash.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/267001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34888/" ]
I'm trying to save the output of an vector image drawin in Java2D to an SWF file. There are great libraries for saving java2D output as things like SVG (BATIK) and PDF(itext) but I can't find one for SWF. Any ideas?
I just got an example to work using the [SpriteGraphics2D](http://opensource.adobe.com/svn/opensource/flex/sdk/trunk/modules/swfutils/src/java/flash/graphics/g2d/SpriteGraphics2D.java) object from [Adobe's Flex 3](http://opensource.adobe.com/wiki/display/flexsdk/Downloads). FYI... Flex 3 is now open source. > > *(from SpriteGraphics2D javadoc)* [SpriteGraphics2D](http://opensource.adobe.com/svn/opensource/flex/sdk/trunk/modules/swfutils/src/java/flash/graphics/g2d/SpriteGraphics2D.java) is a SWF specific implementation of Java2D's Graphics2D API. Calls to this class are converted into a TagList that can be used to construct a SWF Sprite. > > > I figured this out by looking at these two classes [CubicCurveTest.java](http://opensource.adobe.com/svn/opensource/flex/sdk/trunk/modules/swfutils/test/java/flash/swf/builder/types/CubicCurveTest.java) and [SpriteTranscoder.java](http://opensource.adobe.com/svn/opensource/flex/sdk/trunk/modules/compiler/src/java/flash/svg/SpriteTranscoder.java). The only two jars needed to run this example are swfutils.jar and batik-awt-util.jar which can be [downloaded here](http://opensource.adobe.com/wiki/display/flexsdk/Downloads). Here is my example code... ``` // Create the SpriteGraphics2D object SpriteGraphics2D g = new SpriteGraphics2D(100, 100); // Draw on to the graphics object Font font = new Font("Serif", Font.PLAIN, 16); g.setFont(font); g.drawString("Test swf", 30, 30); g.draw(new Line2D.Double(5, 5, 50, 60)); g.draw(new Line2D.Double(50, 60, 150, 40)); g.draw(new Line2D.Double(150, 40, 160, 10)); // Create a new empty movie Movie m = new Movie(); m.version = 7; m.bgcolor = new SetBackgroundColor(SwfUtils.colorToInt(255, 255, 255)); m.framerate = 12; m.frames = new ArrayList(1); m.frames.add(new Frame()); m.size = new Rect(11000, 8000); // Get the DefineSprite from the graphics object DefineSprite tag = g.defineSprite("swf-test"); // Place the DefineSprite on the first frame Frame frame1 = (Frame) m.frames.get(0); Matrix mt = new Matrix(0, 0); frame1.controlTags.add(new PlaceObject(mt, tag, 1, null)); TagEncoder tagEncoder = new TagEncoder(); MovieEncoder movieEncoder = new MovieEncoder(tagEncoder); movieEncoder.export(m); //Write to file FileOutputStream fos = new FileOutputStream(new File("/test.swf")); tagEncoder.writeTo(fos); ```
267,006
<p>My new ASP.NET MVC Web Application works on my development workstation, but does not run on my web server...</p> <hr> <h1>Server Error in '/' Application.</h1> <hr> <h2>Configuration Error</h2> <p><strong>Description:</strong> An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. </p> <p><strong>Parser Error Message:</strong> Could not load file or assembly 'System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. </p> <p><strong>Source Error:</strong> </p> <pre><code>Line 44: &lt;add assembly="System.Web.Abstractions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/&gt; Line 45: &lt;add assembly="System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/&gt; Line 46: &lt;add assembly="System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/&gt; Line 47: &lt;add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/&gt; Line 48: &lt;add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/&gt; </code></pre> <p><strong>Source File:</strong> C:\inetpub\www.example.org\web.config <strong>Line:</strong> 46 </p> <p><strong>Assembly Load Trace:</strong> The following information can be helpful to determine why the assembly 'System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' could not be loaded. </p> <pre> WRN: Assembly binding logging is turned OFF. To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1. Note: There is some performance penalty associated with assembly bind failure logging. To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog]. </pre> <hr> <p><strong>Version Information:</strong> Microsoft .NET Framework Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053</p> <hr> <p>Do I need to install the <em>AspNetMVCBeta-setup.msi</em> on the server? Or is there a different installer for servers?</p> <p><img src="https://i.stack.imgur.com/V21XS.gif" alt="enter image description here"></p>
[ { "answer_id": 267020, "author": "Matt Rudder", "author_id": 29715, "author_profile": "https://Stackoverflow.com/users/29715", "pm_score": 5, "selected": false, "text": "<p>Installing MVC directly on your web server is one option, as then the assemblies will be installed in the GAC. You can also bin deploy the assemblies, which might help keep your server clear of pre-release assemblies until a final release is available.</p>\n\n<p>Phil Haack posted a nice article a couple days ago about how to deploy MVC along with your app, so it's not necessary to install directly:</p>\n\n<p><a href=\"http://www.haacked.com/archive/2008/11/03/bin-deploy-aspnetmvc.aspx\" rel=\"noreferrer\">http://www.haacked.com/archive/2008/11/03/bin-deploy-aspnetmvc.aspx</a></p>\n" }, { "answer_id": 267021, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 9, "selected": true, "text": "<p>I just wrote a blog post addressing this. You could install ASP.NET MVC on your server OR you can follow the <a href=\"http://haacked.com/archive/2008/11/03/bin-deploy-aspnetmvc.aspx\" rel=\"noreferrer\">steps here</a>.</p>\n\n<hr>\n\n<p><strong>EDIT:</strong> (by jcolebrand) I went through this link, then had the same issue as <a href=\"https://stackoverflow.com/users/653855/victor-juri\">Victor</a> <a href=\"https://stackoverflow.com/questions/267006/could-not-load-file-or-assembly-system-web-mvc/5481834#5481834\">below</a>, so I suggest you also add these:</p>\n\n<pre><code>* Microsoft.Web.Infrastructure\n* System.Web.Razor\n* System.Web.WebPages.Deployment\n* System.Web.WebPages.Razor\n</code></pre>\n" }, { "answer_id": 4801390, "author": "sgriffinusa", "author_id": 71519, "author_profile": "https://Stackoverflow.com/users/71519", "pm_score": 5, "selected": false, "text": "<p>I ran into this same issue trying to deploy my MVC3 Razor web application on GoDaddy shared hosting. There are some additional .dlls that need to be referenced. Details here: <a href=\"http://paulmason.biz/?p=108\" rel=\"noreferrer\">http://paulmason.biz/?p=108</a></p>\n\n<p>Basically you need to add references to the following in addition to the ones listed in @Haacked's post and set them to deploy locally as described.</p>\n\n<ul>\n<li>Microsoft.Web.Infrastructure</li>\n<li>System.Web.Razor</li>\n<li>System.Web.WebPages.Deployment</li>\n<li>System.Web.WebPages.Razor</li>\n</ul>\n" }, { "answer_id": 5481834, "author": "Victor Juri", "author_id": 653855, "author_profile": "https://Stackoverflow.com/users/653855", "pm_score": 5, "selected": false, "text": "<p>I ran into the same issue as sgriffinusa.\nIn addition to the references Phil's article suggests: <a href=\"http://www.haacked.com/archive/2008/11/03/bin-deploy-aspnetmvc.aspx\" rel=\"noreferrer\">http://www.haacked.com/archive/2008/11/03/bin-deploy-aspnetmvc.aspx</a> . I added these:</p>\n\n<pre><code>* Microsoft.Web.Infrastructure\n* System.Web.Razor\n* System.Web.WebPages.Deployment\n* System.Web.WebPages.Razor\n</code></pre>\n\n<p>Godaddy Deployment worked perfectly. Turn custom errors off and add references to correct the errors. That should lead you in the right direction.</p>\n" }, { "answer_id": 6538170, "author": "Tom Stickel", "author_id": 756246, "author_profile": "https://Stackoverflow.com/users/756246", "pm_score": 2, "selected": false, "text": "<p>If your NOT using a hosting provider, and you have access to the server to install ... Then install the MVC 3 update tools, do that... it will save you hours of problems on a windows 2003 server / IIS6 machine. , I commented on this page here <a href=\"https://stackoverflow.com/questions/5831785/problem-deploying-nuget-server-with-deployable-dependencies/6529145#6529145\">Nuget.Core.dll version number mismatch</a></p>\n" }, { "answer_id": 6573919, "author": "James Lawruk", "author_id": 88204, "author_profile": "https://Stackoverflow.com/users/88204", "pm_score": 2, "selected": false, "text": "<p>In addition to the Haack post, Hanselman also has a similar post. <a href=\"http://www.hanselman.com/blog/BINDeployingASPNETMVC3WithRazorToAWindowsServerWithoutMVCInstalled.aspx\" rel=\"nofollow\">BIN Delploying ASP.NET MVC 3 with Razor to a Windows Server without MVC installed</a> </p>\n\n<p>For me, the \"Copy Local = true\" solution was insufficient because my Website's project references did not include all the dlls that were missing. As Scott mentions in his post, I also needed to get additional dlls from the following folder on my development box: C:\\Program Files (x86)\\Microsoft ASP.NET\\ASP.NET Web Pages\\v1.0\\Assemblies. The error message informed me which dll was missing (System.Web.Infrastructure, System.Web.Razor, etc.) I continued to add each missing dll, one by one, until it worked.</p>\n" }, { "answer_id": 8059272, "author": "warrickh", "author_id": 896727, "author_profile": "https://Stackoverflow.com/users/896727", "pm_score": 4, "selected": false, "text": "<p>In VS2010, right click the project in the Solution Explorer and select 'Add Deployable Dependencies'. Then check the MVC related check boxes in the following dialog.</p>\n\n<p>This creates a '_bin_deployableAssemblies' folder in the project which contains all the .dll files mentioned in other answers. I believe these get copied to the bin folder when creating a deployment package.</p>\n" }, { "answer_id": 11972187, "author": "Axle", "author_id": 1385801, "author_profile": "https://Stackoverflow.com/users/1385801", "pm_score": 3, "selected": false, "text": "<p>Simple fix. In VS2010, right click on your MVC project, select \"Add Deployable Dependencies...\", select the the options you want and click ok</p>\n" }, { "answer_id": 13426060, "author": "Dave Shinkle", "author_id": 1647603, "author_profile": "https://Stackoverflow.com/users/1647603", "pm_score": 3, "selected": false, "text": "<p>We want to add it because we are making a class library that uses it.</p>\n\n<p>For me it is here...</p>\n\n<p><code>C:\\Program Files (x86)\\Microsoft ASP.NET\\ASP.NET MVC 4\\Assemblies</code></p>\n" }, { "answer_id": 14759102, "author": "Matan L", "author_id": 1498837, "author_profile": "https://Stackoverflow.com/users/1498837", "pm_score": 1, "selected": false, "text": "<p>After trying everything and still failing this was my solution:\ni remembered i had and error last updating the MVC version in my Visual studio so i run the project from another Visual studio (different computer) and than uploaded the dll-s and it worked.\nmaybe it will help someone...</p>\n" }, { "answer_id": 16171757, "author": "Jenzo", "author_id": 978835, "author_profile": "https://Stackoverflow.com/users/978835", "pm_score": 0, "selected": false, "text": "<p>I am using Jenkins with .net projects and had troubles with MVC 4 references.</p>\n\n<p>I finallys solved my issue by using a .Net reference search engine functionality based on the registry using : </p>\n\n<p>\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft.NETFramework\\v2.0.50727\\AssemblyFoldersEx\"</p>\n\n<p>You can create subkey et set the default key to \"c:\\myreferenceedir\" for example.</p>\n\n<p>It saved me with MVC versions and also ASP.net Web pages.</p>\n\n<p>Usefull to add references to the \"Add Reference Dialog\"</p>\n\n<p><a href=\"http://dhakshinamoorthy.wordpress.com/2011/12/04/how-to-register-your-net-assembly-in-gac-and-make-it-show-in-add-reference-dialog/\" rel=\"nofollow\">http://dhakshinamoorthy.wordpress.com/2011/12/04/how-to-register-your-net-assembly-in-gac-and-make-it-show-in-add-reference-dialog/</a></p>\n" }, { "answer_id": 26952471, "author": "Dave", "author_id": 652259, "author_profile": "https://Stackoverflow.com/users/652259", "pm_score": 2, "selected": false, "text": "<p>Also check the version of the assembly in the web.config inside your <strong>Views folder</strong> and make sure it matches. I sometimes forget there is a 2nd web.config in that location.</p>\n" }, { "answer_id": 28169588, "author": "Romeo", "author_id": 2373529, "author_profile": "https://Stackoverflow.com/users/2373529", "pm_score": 3, "selected": false, "text": "<p>Had the same issue and added all the assembly that they said but still got the same error.</p>\n\n<p>turns out you need to make the \"<strong>Specific Version</strong>\" = False.</p>\n\n<p><img src=\"https://i.stack.imgur.com/KMp9O.png\" alt=\"Specific version should be false.\"></p>\n" }, { "answer_id": 28819836, "author": "Brian Rice", "author_id": 1027031, "author_profile": "https://Stackoverflow.com/users/1027031", "pm_score": 0, "selected": false, "text": "<p>I added \"Microsoft ASP.NET Razor\" using Manage NuGet Packages.</p>\n\n<p>With Add References, for some reason, I only had System.Web.Helpers 1.0.0 and 2.0.0... but not 3.0.0.</p>\n\n<p>Another option, that worked form me was to delete the references to System.Web.Mvc and System.Web.Http... then re-add them browing to the package locations in the csproj file (you can most easily edit the project with a text editor):</p>\n\n<pre><code>&lt;Reference Include=\"System.Web.Http\"&gt;\n &lt;HintPath&gt;..\\packages\\Microsoft.AspNet.WebApi.Core.5.2.3\\lib\\net45\\System.Web.Http.dll&lt;/HintPath&gt;\n\n&lt;Reference Include=\"System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\"&gt;\n &lt;HintPath&gt;..\\packages\\Microsoft.AspNet.Mvc.5.2.3\\lib\\net45\\System.Web.Mvc.dll&lt;/HintPath&gt;\n</code></pre>\n" }, { "answer_id": 32367093, "author": "actual_kangaroo", "author_id": 2377920, "author_profile": "https://Stackoverflow.com/users/2377920", "pm_score": 0, "selected": false, "text": "<p>As Others have mentioned, add these refernces to visual studios with <code>Copy Local</code> set to <code>true</code>. ( I also had to add <code>System.Web.Webpages</code>)</p>\n\n<pre><code>Microsoft.Web.Infrastructure\nSystem.Web.Razor\nSystem.Web.WebPages.Deployment\nSystem.Web.WebPages.Razor\nSystem.Web.Webpages\n</code></pre>\n" }, { "answer_id": 36714873, "author": "Mikael Puusaari", "author_id": 6094057, "author_profile": "https://Stackoverflow.com/users/6094057", "pm_score": 2, "selected": false, "text": "<p>I had the same problem with a bunch of assembly files after moving the project to another solution.</p>\n\n<p>For me, the <code>web.config</code> file was trying to add this assembly:</p>\n\n<pre><code>&lt;add assembly=\"System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/&gt;\n</code></pre>\n\n<p>Thought the reference in the project was pointing towards version <code>3.0.0.0</code> (click on the reference and scroll to the bottom of the properties). Hence I just changed the reference version in the <code>web.config</code> file. </p>\n\n<p>I don´t know if this was just a bug of some sort. The problem with adding all the other references was that the references appeared in the config file but it wasn't actually referenced at all in the project (inside the solution explorer) and the needed files were not copied with the rest of the project files, probably due to not being <code>\"copy local = true\"</code></p>\n\n<p>Now, I wasn´t able to find these assemblies in the addable assemblies (by right clicking the reference and trying to add them from the assemblies or extensions). Instead I created a new MVC solution which added all the assemblies and references I needed, and finding them under the new projects references in the solution explorer and finding their path in the properties window for the reference.</p>\n\n<p>Then I just copied the libraries I needed into the other project and referenced them.</p>\n" }, { "answer_id": 37585918, "author": "Muhammad Amir", "author_id": 3301185, "author_profile": "https://Stackoverflow.com/users/3301185", "pm_score": 3, "selected": false, "text": "<p><strong>Quick &amp; Simple Solution:</strong> I faced this problem with Microsoft.AspNet.Mvc -Version 5.2.3 and after going through all these threads I found a simplest solution. </p>\n\n<p>Just follow steps:</p>\n\n<ol>\n<li>Open NuGet Package Manager in Visual studio for your project</li>\n<li>Search for Microsoft.AspNet.Mvc</li>\n<li>When found, change action to Uninstall and Uninstall it</li>\n<li>Once done, install it again and try it now</li>\n</ol>\n\n<p>This will automatically fix all issues with references. \nSee image below:</p>\n\n<p><a href=\"https://i.stack.imgur.com/WrWK6.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/WrWK6.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 38050215, "author": "Olaj", "author_id": 40609, "author_profile": "https://Stackoverflow.com/users/40609", "pm_score": 2, "selected": false, "text": "<p>I've did a \"Update-Package –reinstall Microsoft.AspNet.Mvc\" to fix it in Visual Studio 2015.</p>\n" }, { "answer_id": 41758515, "author": "PBo", "author_id": 5262306, "author_profile": "https://Stackoverflow.com/users/5262306", "pm_score": 2, "selected": false, "text": "<p>An important consideration is the web.config file, Some packages can mangle your binding redirects causing havoc (the rogue package was in house package that I did not remove the web.config from the package or making sure the web.config in in the package doesn't have any binding redirects. For example by removing the duplicate and incorrect node resolves this</p>\n\n<pre><code> &lt;runtime&gt;\n &lt;assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\"&gt;\n &lt;dependentAssembly&gt;\n &lt;assemblyIdentity name=\"System.Web.WebPages\" publicKeyToken=\"31BF3856AD364E35\" culture=\"neutral\"/&gt;\n &lt;bindingRedirect oldVersion=\"0.0.0.0-3.0.0.0\" newVersion=\"3.0.0.0\"/&gt;\n &lt;/dependentAssembly&gt;\n &lt;dependentAssembly&gt;\n\n\n &lt;assemblyIdentity name=\"System.Web.Mvc\" publicKeyToken=\"31bf3856ad364e35\"/&gt;\n &lt;bindingRedirect oldVersion=\"0.0.0.0-5.2.3.0\" newVersion=\"5.2.3.0\"/&gt;\n &lt;assemblyIdentity name=\"Microsoft.Owin\" publicKeyToken=\"31bf3856ad364e35\" culture=\"neutral\"/&gt;\n &lt;bindingRedirect oldVersion=\"0.0.0.0-3.0.1.0\" newVersion=\"3.0.1.0\"/&gt;\n &lt;assemblyIdentity name=\"Microsoft.Owin.Security.OAuth\" publicKeyToken=\"31bf3856ad364e35\" culture=\"neutral\"/&gt;\n &lt;assemblyIdentity name=\"Microsoft.Owin.Security\" publicKeyToken=\"31bf3856ad364e35\" culture=\"neutral\"/&gt;\n &lt;assemblyIdentity name=\"Microsoft.Owin.Security.Cookies\" publicKeyToken=\"31bf3856ad364e35\" culture=\"neutral\"/&gt;\n &lt;assemblyIdentity name=\"Newtonsoft.Json\" publicKeyToken=\"30ad4fe6b2a6aeed\" culture=\"neutral\"/&gt;\n &lt;bindingRedirect oldVersion=\"0.0.0.0-9.0.0.0\" newVersion=\"9.0.0.0\"/&gt;\n &lt;assemblyIdentity name=\"WebGrease\" publicKeyToken=\"31bf3856ad364e35\" culture=\"neutral\"/&gt;\n &lt;bindingRedirect oldVersion=\"0.0.0.0-1.6.5135.21930\" newVersion=\"1.6.5135.21930\"/&gt;\n &lt;assemblyIdentity name=\"Antlr3.Runtime\" publicKeyToken=\"eb42632606e9261f\" culture=\"neutral\"/&gt;\n &lt;bindingRedirect oldVersion=\"0.0.0.0-3.5.0.2\" newVersion=\"3.5.0.2\"/&gt;\n\n\n &lt;assemblyIdentity name=\"System.Web.Helpers\" publicKeyToken=\"31bf3856ad364e35\"/&gt;\n &lt;bindingRedirect oldVersion=\"1.0.0.0-3.0.0.0\" newVersion=\"3.0.0.0\"/&gt;\n &lt;/dependentAssembly&gt;\n &lt;dependentAssembly&gt;\n &lt;assemblyIdentity name=\"System.Web.Mvc\" publicKeyToken=\"31bf3856ad364e35\"/&gt;\n &lt;bindingRedirect oldVersion=\"0.0.0.0-5.2.3.0\" newVersion=\"5.2.3.0\"/&gt;\n &lt;/dependentAssembly&gt;\n &lt;dependentAssembly&gt;\n &lt;assemblyIdentity name=\"Microsoft.Owin.Security\" publicKeyToken=\"31bf3856ad364e35\" culture=\"neutral\"/&gt;\n &lt;bindingRedirect oldVersion=\"0.0.0.0-3.0.1.0\" newVersion=\"3.0.1.0\"/&gt;\n &lt;/dependentAssembly&gt;\n &lt;dependentAssembly&gt;\n &lt;assemblyIdentity name=\"Microsoft.Owin\" publicKeyToken=\"31bf3856ad364e35\" culture=\"neutral\"/&gt;\n &lt;bindingRedirect oldVersion=\"0.0.0.0-3.0.1.0\" newVersion=\"3.0.1.0\"/&gt;\n &lt;/dependentAssembly&gt;\n &lt;dependentAssembly&gt;\n &lt;assemblyIdentity name=\"Newtonsoft.Json\" publicKeyToken=\"30ad4fe6b2a6aeed\" culture=\"neutral\"/&gt;\n &lt;bindingRedirect oldVersion=\"0.0.0.0-9.0.0.0\" newVersion=\"9.0.0.0\"/&gt;\n &lt;/dependentAssembly&gt;\n &lt;dependentAssembly&gt;\n &lt;assemblyIdentity name=\"WebGrease\" publicKeyToken=\"31bf3856ad364e35\" culture=\"neutral\"/&gt;\n &lt;bindingRedirect oldVersion=\"0.0.0.0-1.6.5135.21930\" newVersion=\"1.6.5135.21930\"/&gt;\n &lt;/dependentAssembly&gt;\n &lt;dependentAssembly&gt;\n &lt;assemblyIdentity name=\"Microsoft.Owin.Security.Cookies\" publicKeyToken=\"31bf3856ad364e35\" culture=\"neutral\"/&gt;\n &lt;bindingRedirect oldVersion=\"0.0.0.0-3.0.1.0\" newVersion=\"3.0.1.0\"/&gt;\n &lt;/dependentAssembly&gt;\n &lt;dependentAssembly&gt;\n &lt;assemblyIdentity name=\"Microsoft.Owin.Security.OAuth\" publicKeyToken=\"31bf3856ad364e35\" culture=\"neutral\"/&gt;\n &lt;bindingRedirect oldVersion=\"0.0.0.0-3.0.1.0\" newVersion=\"3.0.1.0\"/&gt;\n &lt;/dependentAssembly&gt;\n &lt;dependentAssembly&gt;\n &lt;assemblyIdentity name=\"SimpleInjector\" publicKeyToken=\"984cb50dea722e99\" culture=\"neutral\"/&gt;\n &lt;bindingRedirect oldVersion=\"0.0.0.0-3.3.2.0\" newVersion=\"3.3.2.0\"/&gt;\n &lt;/dependentAssembly&gt;\n &lt;dependentAssembly&gt;\n &lt;assemblyIdentity name=\"Antlr3.Runtime\" publicKeyToken=\"eb42632606e9261f\" culture=\"neutral\"/&gt;\n &lt;bindingRedirect oldVersion=\"0.0.0.0-3.5.0.2\" newVersion=\"3.5.0.2\"/&gt;\n &lt;/dependentAssembly&gt;\n &lt;dependentAssembly&gt;\n &lt;assemblyIdentity name=\"HtmlAgilityPack\" publicKeyToken=\"bd319b19eaf3b43a\" culture=\"neutral\"/&gt;\n &lt;bindingRedirect oldVersion=\"0.0.0.0-1.4.9.5\" newVersion=\"1.4.9.5\"/&gt;\n &lt;/dependentAssembly&gt;\n &lt;/assemblyBinding&gt;\n &lt;/runtime&gt;\n</code></pre>\n\n<p>by removing lines 8 to 24 fixes the build.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/267006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
My new ASP.NET MVC Web Application works on my development workstation, but does not run on my web server... --- Server Error in '/' Application. ================================ --- Configuration Error ------------------- **Description:** An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. **Parser Error Message:** Could not load file or assembly 'System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. **Source Error:** ``` Line 44: <add assembly="System.Web.Abstractions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> Line 45: <add assembly="System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> Line 46: <add assembly="System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> Line 47: <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> Line 48: <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> ``` **Source File:** C:\inetpub\www.example.org\web.config **Line:** 46 **Assembly Load Trace:** The following information can be helpful to determine why the assembly 'System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' could not be loaded. ``` WRN: Assembly binding logging is turned OFF. To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1. Note: There is some performance penalty associated with assembly bind failure logging. To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog]. ``` --- **Version Information:** Microsoft .NET Framework Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053 --- Do I need to install the *AspNetMVCBeta-setup.msi* on the server? Or is there a different installer for servers? ![enter image description here](https://i.stack.imgur.com/V21XS.gif)
I just wrote a blog post addressing this. You could install ASP.NET MVC on your server OR you can follow the [steps here](http://haacked.com/archive/2008/11/03/bin-deploy-aspnetmvc.aspx). --- **EDIT:** (by jcolebrand) I went through this link, then had the same issue as [Victor](https://stackoverflow.com/users/653855/victor-juri) [below](https://stackoverflow.com/questions/267006/could-not-load-file-or-assembly-system-web-mvc/5481834#5481834), so I suggest you also add these: ``` * Microsoft.Web.Infrastructure * System.Web.Razor * System.Web.WebPages.Deployment * System.Web.WebPages.Razor ```
267,011
<p>I'm trying to understand what this method means as I'm reading <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.getpostbackeventreference.aspx" rel="noreferrer">this</a> and have wondered what uses this may have. I don't quite understand the example given.</p> <p>Can anyone give another explanation of it. Examples would help.</p> <p>Thanks</p>
[ { "answer_id": 267246, "author": "stevemegson", "author_id": 25028, "author_profile": "https://Stackoverflow.com/users/25028", "pm_score": 4, "selected": true, "text": "<p>The simplest example is a LinkButton. Drop one in a page and look at the HTML it generates. You'll see something like.</p>\n\n<pre><code>href=\"javascript:__doPostBack('ctl00$LinkButton1','')\"\n</code></pre>\n\n<p>GetPostBackEventReference allows you to get that piece of JavaScript, so that you can trigger that postback from elsewhere. However you run that bit of JavaScript, a postback will happen and the OnClick event will fire on the server just as if you'd clicked the LinkButton. The example on MSDN wires up a similar bit of JavaScript to the links to trigger server-side events on the GridView.</p>\n\n<p>The more practical uses are when you want to handle postbacks in a custom control. Your control implements <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.ipostbackeventhandler.aspx\" rel=\"noreferrer\">IPostBackEventHandler</a> to handle the postbacks on the server, and you use GetPostBackEventReference to get the JavaScript that will trigger those postbacks.</p>\n" }, { "answer_id": 267269, "author": "Ramesh", "author_id": 30594, "author_profile": "https://Stackoverflow.com/users/30594", "pm_score": 2, "selected": false, "text": "<p>As steve mentioned this can be used for </p>\n\n<blockquote>\n <p>GetPostBackEventReference allows you to get that piece of JavaScript, so that you can trigger that postback from elsewhere.</p>\n</blockquote>\n\n<p>To give an example, you can use this function to get reference to PostBack event of button click and add it to onblur of a textbox.</p>\n\n<p>This would simulate the button click whenever the textbox looses the focus.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/267011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5853/" ]
I'm trying to understand what this method means as I'm reading [this](http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.getpostbackeventreference.aspx) and have wondered what uses this may have. I don't quite understand the example given. Can anyone give another explanation of it. Examples would help. Thanks
The simplest example is a LinkButton. Drop one in a page and look at the HTML it generates. You'll see something like. ``` href="javascript:__doPostBack('ctl00$LinkButton1','')" ``` GetPostBackEventReference allows you to get that piece of JavaScript, so that you can trigger that postback from elsewhere. However you run that bit of JavaScript, a postback will happen and the OnClick event will fire on the server just as if you'd clicked the LinkButton. The example on MSDN wires up a similar bit of JavaScript to the links to trigger server-side events on the GridView. The more practical uses are when you want to handle postbacks in a custom control. Your control implements [IPostBackEventHandler](http://msdn.microsoft.com/en-us/library/system.web.ui.ipostbackeventhandler.aspx) to handle the postbacks on the server, and you use GetPostBackEventReference to get the JavaScript that will trigger those postbacks.
267,026
<p>This very simple code gives me tons of errors:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; int main() { std::string test = " "; std::cout &lt;&lt; test; } </code></pre> <p>I tried to compile it on linux by typing <strong>gcc -o simpletest simpletest.cpp</strong> on the console. I can't see why it isn't working. What is happening?</p>
[ { "answer_id": 267031, "author": "rmeador", "author_id": 10861, "author_profile": "https://Stackoverflow.com/users/10861", "pm_score": 0, "selected": false, "text": "<p>You declared your <code>main()</code> as returning an <code>int</code> yet you have no return statement. Add <code>return 0;</code> and see if that helps. If that doesn't solve your problem, try editing your post to include some representative lines from those errors your getting and maybe we can help you better.</p>\n" }, { "answer_id": 267032, "author": "grieve", "author_id": 34329, "author_profile": "https://Stackoverflow.com/users/34329", "pm_score": 4, "selected": true, "text": "<p>Try using 'g++' instead of 'gcc'.</p>\n" }, { "answer_id": 267034, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 3, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>g++ -o simpletest simpletest.cpp\n</code></pre>\n" }, { "answer_id": 267039, "author": "MP24", "author_id": 6206, "author_profile": "https://Stackoverflow.com/users/6206", "pm_score": 3, "selected": false, "text": "<p>Try with <code>g++ -o simpletest simpletest.cpp</code>.\ngcc is the C compiler, while g++ is the C++ compiler which also links in the required C++ libraries.</p>\n\n<p>Additionally, you will have to add a <code>return 0;</code> at the end of your <code>main()</code> function.</p>\n" }, { "answer_id": 267078, "author": "RAGNO", "author_id": 11540, "author_profile": "https://Stackoverflow.com/users/11540", "pm_score": 2, "selected": false, "text": "<p>if your compiler is picky you may want to add that all important <code>return 0;</code> at the end there</p>\n" }, { "answer_id": 267099, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": false, "text": "<p>To add to what others have said: <code>g++</code> is the GNU C++ compiler. <code>gcc</code> is the GNU compiler collection (<strong>not</strong> the GNU C compiler, as many people assume). <code>gcc</code> serves as a frontend for <code>g++</code> when compiling C++ sources. <code>gcc</code> can compile C, C++, Objective-C, Fortran, Ada, assembly, and others.</p>\n\n<p>The reason why it fails trying to compile with <code>gcc</code> is that you need to link in the C++ standard library. By default, <code>g++</code> does this, but <code>gcc</code> does not. To link in the C++ standard library using <code>gcc</code>, use the following:</p>\n\n<pre><code>gcc -o simpletest simpletest.cpp <b>-lstdc++</b></code></pre>\n" }, { "answer_id": 10180787, "author": "Bill IV", "author_id": 280769, "author_profile": "https://Stackoverflow.com/users/280769", "pm_score": 0, "selected": false, "text": "<p>g++ was the right answer for me too, I voted it up, thanks. </p>\n\n<p>But my code, a little ditty that I've been using since Feb 13, 1998 (first comment), to calculate effective gross pay and withholding for our kid's nanny, was far TOO simple even for g++. In terms of the example above, my Stroustrup-second-edition-compliant dinosaur went:</p>\n\n<pre><code>// too simple!\n\n#include &lt;iostream.h&gt;\n#include &lt;stdlib.h&gt;\n\nmain() {\n cout &lt;&lt; \"Hello World!\" &lt;&lt; endl;\n}\n</code></pre>\n\n<p>This will give you a full terminal window of error messages. Everything except the curly braces is an error! AND its missing a return line. Time was, this would compile and run correctly in commercial C++ development environments...</p>\n\n<p>Kicking it new-school, I'm now using:\n // just simple enough</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;stdlib.h&gt;\n\nint main(int argc, char* argv[] ) {\n std::cout &lt;&lt; \"Hello World!\" &lt;&lt; std::endl;\n// TODO - this ought to return success, 0\n}\n</code></pre>\n\n<p>The original questioner had the std::cout and used string from </p>\n\n<pre><code> &lt;string&gt;... \n</code></pre>\n\n<p>\"simple\" is a relative term...</p>\n\n<p>Bill</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/267026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27090/" ]
This very simple code gives me tons of errors: ``` #include <iostream> #include <string> int main() { std::string test = " "; std::cout << test; } ``` I tried to compile it on linux by typing **gcc -o simpletest simpletest.cpp** on the console. I can't see why it isn't working. What is happening?
Try using 'g++' instead of 'gcc'.
267,030
<p>I'm needing to script my build. I'm using MSBUILD because of it's integration with VS.net. I am trying to copy some files from the build environment to the deployment folder. I'm using the copy task of MSBuild. But instead of copying the directory tree as I would expect. it copies all the contents into a single folder. I repeat all the files from the directory tree end up in one folder. I need it to copy the tree of folders and directories into the destination folder. Is there something I'm missing?</p> <p>Here is the relavant parts of my build script:</p> <pre><code>&lt;PropertyGroup&gt; &lt;TargetFrameworkVersion&gt;v2.0&lt;/TargetFrameworkVersion&gt; &lt;Source&gt;outputfolder&lt;/Source&gt; &lt;DestEnv&gt;x&lt;/DestEnv&gt; &lt;DeployPath&gt;\\networkpath\$(DestEnv)&lt;/DeployPath&gt; &lt;/PropertyGroup&gt; &lt;ItemGroup&gt; &lt;TargetDir Include="$(DeployPath)\**\*" Exclude="**\web.config"&gt;&lt;/TargetDir&gt; &lt;SourceDir Include="$(Source)\**\*" /&gt; &lt;/ItemGroup&gt; &lt;Target Name="Clean" &gt; &lt;!-- clean detail ... --&gt; &lt;/Target&gt; &lt;Target Name="migrate" DependsOnTargets="Clean"&gt; &lt;Copy DestinationFolder="$(DeployPath)" SourceFiles="@(SourceDir)" /&gt; &lt;/Target&gt; </code></pre>
[ { "answer_id": 267088, "author": "minty", "author_id": 4491, "author_profile": "https://Stackoverflow.com/users/4491", "pm_score": 2, "selected": false, "text": "<p>I found the example in one of the examples in <a href=\"http://msdn.microsoft.com/en-us/library/3e54c37h.aspx\" rel=\"nofollow noreferrer\">MSDN</a> I don't understand it but will leave an example for my fellow travlers here in stackoverflow. Here is the fixed version of the migrate target from above:</p>\n\n<pre><code>&lt;Target Name=\"migrate\" DependsOnTargets=\"Clean\"&gt;\n &lt;Copy DestinationFiles=\"@(SourceDir-&gt;'$(DeployPath)\\%(RecursiveDir)%(Filename)%(Extension)')\" SourceFiles=\"@(SourceDir)\" /&gt;\n&lt;/Target&gt;\n</code></pre>\n\n<p>If someone actually understands this example please explain. Good Luck!</p>\n" }, { "answer_id": 267110, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 4, "selected": false, "text": "<p>When you specify the DestinationFolder for the Copy task, it takes all items from the SourceFiles collection and copies them to the DestinationFolder. This is expected, as there is no way for the Copy task to figure out what part of each item's path needs to be replaced with the DestinationFolder in order to keep the tree structure. For example, if your SourceDir collection is defined like this:</p>\n\n<pre><code>&lt;ItemGroup&gt;\n &lt;SourceDir Include=\"$(Source)\\**\\*\" /&gt;\n &lt;SourceDir Include=\"E:\\ExternalDependencies\\**\\*\" /&gt;\n &lt;SourceDir Include=\"\\\\sharedlibraries\\gdiplus\\*.h\" /&gt;\n&lt;/ItemGroup&gt;\n</code></pre>\n\n<p>What would you expect the destination folder tree look like?</p>\n\n<p>To preserve the tree, you need to do identity transformation and generate one destination item for each item in the SourceFiles collection. Here's an example:</p>\n\n<pre><code>&lt;Copy SourceFiles=\"@(Compile)\" DestinationFiles=\"@(Compile-&gt;'$(DropPath)%(Identity)')\" /&gt;\n</code></pre>\n\n<p>The Copy task will take the each item in the SourceFiles collection, and will transform its path by replacing the part before the ** in the source item specification with $(DropPath).</p>\n\n<p>One could argue that the DestinationFolder property should have been written as a shortcut to the following transformation:</p>\n\n<pre><code>&lt;Copy SourceFiles=\"@(Compile)\" DestinationFiles=\"@(Compile-&gt;'$(DestinationFolder)%(Identity)')\" /&gt;\n</code></pre>\n\n<p>Alas, that would prevent the deep copy to flat folder scenario that you are trying to avoid, but other people might using in their build process.</p>\n" }, { "answer_id": 274974, "author": "Adam", "author_id": 1341, "author_profile": "https://Stackoverflow.com/users/1341", "pm_score": 3, "selected": false, "text": "<p>Very simple example that copies a directory contents and structure recursively:</p>\n\n<pre><code>&lt;Copy SourceFiles=\"@(Compile)\" DestinationFolder=\"c:\\foocopy\\%(Compile.RecursiveDir)\"&gt;&lt;/Copy&gt;\n</code></pre>\n\n<p>@(Compile) is an ItemGroup of all files that you want to copy. Could be something like:</p>\n\n<pre><code> &lt;ItemGroup&gt;\n &lt;Compile Include=\".\\**\\*.dll\" /&gt; \n &lt;/ItemGroup&gt;\n</code></pre>\n\n<p>The Copy task will copy all the files into c:\\foocopy just like xcopy.</p>\n" }, { "answer_id": 434742, "author": "Jarrod Dixon", "author_id": 3, "author_profile": "https://Stackoverflow.com/users/3", "pm_score": 4, "selected": false, "text": "<p>Just a gem we found as we were debugging MSBuild issues around copying:</p>\n\n<p><a href=\"http://blog.scrappydog.com/2008/06/subtle-msbuild-bug-feature.html\" rel=\"noreferrer\">http://blog.scrappydog.com/2008/06/subtle-msbuild-bug-feature.html</a></p>\n\n<p>ItemGroups are parsed before Targets, so any Targets that create new files (e.g. compiles!) won't be picked up when an ItemGroup is referenced further along the script.</p>\n\n<p>Eric Bowen also describes a work-around for this \"feature\", the <strong>CreateItem</strong> task:</p>\n\n<pre><code>&lt;Target Name=\"Copy\" &gt;\n &lt;CreateItem Include=\"..\\Source\\**\\bin\\**\\*.exe\"\n Exclude=\"..\\Source\\**\\bin\\**\\*.vshost.exe\"&gt;\n &lt;Output TaskParameter=\"Include\" ItemName=\"CompileOutput\" /&gt;\n &lt;/CreateItem&gt;\n &lt;Copy SourceFiles=\"@(CompileOutput)\" \n DestinationFolder=\"$(OutputDirectory)\"&gt;&lt;/Copy&gt;\n&lt;/Target&gt;\n</code></pre>\n\n<p>Many kudos to him!</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/267030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4491/" ]
I'm needing to script my build. I'm using MSBUILD because of it's integration with VS.net. I am trying to copy some files from the build environment to the deployment folder. I'm using the copy task of MSBuild. But instead of copying the directory tree as I would expect. it copies all the contents into a single folder. I repeat all the files from the directory tree end up in one folder. I need it to copy the tree of folders and directories into the destination folder. Is there something I'm missing? Here is the relavant parts of my build script: ``` <PropertyGroup> <TargetFrameworkVersion>v2.0</TargetFrameworkVersion> <Source>outputfolder</Source> <DestEnv>x</DestEnv> <DeployPath>\\networkpath\$(DestEnv)</DeployPath> </PropertyGroup> <ItemGroup> <TargetDir Include="$(DeployPath)\**\*" Exclude="**\web.config"></TargetDir> <SourceDir Include="$(Source)\**\*" /> </ItemGroup> <Target Name="Clean" > <!-- clean detail ... --> </Target> <Target Name="migrate" DependsOnTargets="Clean"> <Copy DestinationFolder="$(DeployPath)" SourceFiles="@(SourceDir)" /> </Target> ```
When you specify the DestinationFolder for the Copy task, it takes all items from the SourceFiles collection and copies them to the DestinationFolder. This is expected, as there is no way for the Copy task to figure out what part of each item's path needs to be replaced with the DestinationFolder in order to keep the tree structure. For example, if your SourceDir collection is defined like this: ``` <ItemGroup> <SourceDir Include="$(Source)\**\*" /> <SourceDir Include="E:\ExternalDependencies\**\*" /> <SourceDir Include="\\sharedlibraries\gdiplus\*.h" /> </ItemGroup> ``` What would you expect the destination folder tree look like? To preserve the tree, you need to do identity transformation and generate one destination item for each item in the SourceFiles collection. Here's an example: ``` <Copy SourceFiles="@(Compile)" DestinationFiles="@(Compile->'$(DropPath)%(Identity)')" /> ``` The Copy task will take the each item in the SourceFiles collection, and will transform its path by replacing the part before the \*\* in the source item specification with $(DropPath). One could argue that the DestinationFolder property should have been written as a shortcut to the following transformation: ``` <Copy SourceFiles="@(Compile)" DestinationFiles="@(Compile->'$(DestinationFolder)%(Identity)')" /> ``` Alas, that would prevent the deep copy to flat folder scenario that you are trying to avoid, but other people might using in their build process.
267,033
<p>Say I have a list of all <code>Projects</code>, and that I group them by <code>Category</code> like this:</p> <pre><code>var projectsByCat = from p in Projects group p by p.Category into g orderby g.Count() descending select new { Category = g.Key, Projects = g }; </code></pre> <p>Now I want to display this as a list in a web page, where first I create the left side div, secondly the right side div. I am ordering by number of <code>Projects</code> in each <code>Category</code> to show the <code>Categories</code> with the most <code>Projects</code> on top - thus I would like to split <code>projectsByCat</code> in two - if I put all the &quot;odd numbered&quot; <code>Categories</code> on the left and the &quot;even numbered&quot; categories on the right, I think I will get a reasonably sane view.</p> <p>So I thought I could do this to get the odd and even members of <code>projectsByCat</code>:</p> <pre><code>var oddCategories = projectsByCat.Where((cat, index) =&gt; index % 2 != 0); var evenCategories = projectsByCat.Where((cat, index) =&gt; index % 2 == 0); </code></pre> <p>And it compiles - however, when I run it, I get an exception such as this:</p> <blockquote> <p>Unsupported overload used for query operator 'Where'.</p> </blockquote> <p>And I thought I was safe since it compiled in the first place.. ;)</p> <p>Is there an elegant way to do this? And also, is there an elegant explanation for why my creative use of <code>Where()</code> won't work?</p>
[ { "answer_id": 267053, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 7, "selected": true, "text": "<p>If you're using LINQ to SQL or LINQ to Entities you should first fully materialize the results into memory:</p>\n\n<pre><code>var oddCategories = projectsByCat.ToList().Where((c,i) =&gt; i % 2 != 0);\nvar evenCategories = projectsByCat.ToList().Where((c,i) =&gt; i % 2 == 0);\n</code></pre>\n\n<p>It isn't possible to iterate through results on the database with an indexer without the use of a cursor, which either ORM framework does <strong>not</strong> do.</p>\n" }, { "answer_id": 267235, "author": "Jacob Carpenter", "author_id": 26627, "author_profile": "https://Stackoverflow.com/users/26627", "pm_score": 5, "selected": false, "text": "<p>Note that calling <code>.ToList()</code> twice for the same query is going query the database twice.</p>\n\n<p>It would be much better to cache the result in an intermediate list, <em>then</em> apply your predicate filtering:</p>\n\n<pre><code>var projectsByCat =\n (from p in Projects\n group p by p.Category into g\n orderby g.Count() descending\n select new { Category = g.Key, Projects = g }).ToList();\n\nvar oddCategories = projectsByCat.Where((cat, index) =&gt; index % 2 != 0);\nvar evenCategories = projectsByCat.Where((cat, index) =&gt; index % 2 == 0);\n</code></pre>\n" }, { "answer_id": 6343500, "author": "bjhamltn", "author_id": 427534, "author_profile": "https://Stackoverflow.com/users/427534", "pm_score": 3, "selected": false, "text": "<p>The oddCategories and the evenCategories are backward.</p>\n\n<p>Indexes start a 0 not 1</p>\n\n<p>0 % 2 = 0</p>\n\n<p>0 index is odd.</p>\n\n<pre><code>var oddCategories = projectsByCat.Where((cat, index) =&gt; index % 2 == 0);\n\nvar evenCategories = projectsByCat.Where((cat, index) =&gt; index % 2 != 0);\n</code></pre>\n" }, { "answer_id": 37384168, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 2, "selected": false, "text": "<p>The proper way to do this using LINQ, and avoiding multiple enumerations over the input, is to do a grouping or similar on whether each item is even or odd.</p>\n<p>A simple way using the overload for <code>Select</code> that <a href=\"https://msdn.microsoft.com/en-us/library/bb534869(v=vs.100).aspx\" rel=\"nofollow noreferrer\">mixes in an index</a> coupled with <a href=\"https://msdn.microsoft.com/en-us/library/bb549211(v=vs.100).aspx\" rel=\"nofollow noreferrer\"><code>ToLookup</code></a> gives you what you want:</p>\n<pre><code>var oddsAndEvens = input\n .ToList() // if necessary to get from IQueryable to IEnumerable\n .Select((item, index) =&gt; new { isEven = index % 2 == 0, item })\n .ToLookup(\n i =&gt; i.isEven,\n i =&gt; i.item);\n</code></pre>\n<p>This will produce a <a href=\"https://msdn.microsoft.com/en-us/library/bb460184(v=vs.100).aspx\" rel=\"nofollow noreferrer\"><code>Lookup&lt;TKey, TElement&gt;</code></a> data structure that has the <a href=\"https://msdn.microsoft.com/en-us/library/bb292716(v=vs.100).aspx\" rel=\"nofollow noreferrer\">following benefit</a>:</p>\n<blockquote>\n<p>If the key is not found in the collection, an empty sequence is returned.</p>\n</blockquote>\n<p>This means that after the above LINQ query you can do:</p>\n<pre><code>var evens = oddsAndEvens[true];\nvar odds = oddsAndEvens[false];\n</code></pre>\n" }, { "answer_id": 42022394, "author": "Athul Nalupurakkal", "author_id": 4136430, "author_profile": "https://Stackoverflow.com/users/4136430", "pm_score": 1, "selected": false, "text": "<p>You can separate odd and even in your view using linq.</p>\n\n<pre><code>//even \n@foreach (var item in Model.Where((item, index) =&gt; index % 2 == 0))\n{\n //do the code\n}\n\n//odd\n@foreach (var item in Model.Where((item, index) =&gt; index % 2 != 0))\n{\n //do the code\n}\n</code></pre>\n" }, { "answer_id": 45640412, "author": "Sam Saarian", "author_id": 1617686, "author_profile": "https://Stackoverflow.com/users/1617686", "pm_score": 0, "selected": false, "text": "<pre><code>var text = \"this is a test &lt;string&gt; to extract odd &lt;index&gt; values after split\";\nvar parts = text.Split(new char[] { '&lt;', '&gt;' });\nIEnumerable words = parts.Where(x =&gt; parts.ToList().IndexOf(x) % 2 == 1)\n</code></pre>\n\n<p><em>words</em> would contain \"string\" and \"index\"</p>\n" }, { "answer_id": 49890217, "author": "Hrishikesh Kulkarni", "author_id": 9620863, "author_profile": "https://Stackoverflow.com/users/9620863", "pm_score": 0, "selected": false, "text": "<p>You Can find Even odd number without foreach loop</p>\n\n<pre><code>static void Main(string[] args)\n{\n List&lt;int&gt; lstnum = new List&lt;int&gt; { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };\n\n List&lt;int&gt; lstresult = lstnum.FindAll(x =&gt; (x % 2) == 0);\n\n lstresult.ForEach(x =&gt; Console.WriteLine(x));\n}\n</code></pre>\n" }, { "answer_id": 74255511, "author": "jptrujillol", "author_id": 20373528, "author_profile": "https://Stackoverflow.com/users/20373528", "pm_score": 0, "selected": false, "text": "<p>Using Linq GroupBy Method:</p>\n<pre><code> List&lt;string&gt; lista = new List&lt;string&gt; { &quot;uno&quot;, &quot;dos&quot;, &quot;tres&quot;, &quot;cuatro&quot; };\n\n var grupoXindices = lista.GroupBy(i =&gt; (lista.IndexOf(i) % 2) == 0);\n foreach (var grupo in grupoXindices) \n {\n Console.WriteLine(grupo.Key); \n foreach (var i in grupo) Console.WriteLine(i);\n }\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/267033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2122/" ]
Say I have a list of all `Projects`, and that I group them by `Category` like this: ``` var projectsByCat = from p in Projects group p by p.Category into g orderby g.Count() descending select new { Category = g.Key, Projects = g }; ``` Now I want to display this as a list in a web page, where first I create the left side div, secondly the right side div. I am ordering by number of `Projects` in each `Category` to show the `Categories` with the most `Projects` on top - thus I would like to split `projectsByCat` in two - if I put all the "odd numbered" `Categories` on the left and the "even numbered" categories on the right, I think I will get a reasonably sane view. So I thought I could do this to get the odd and even members of `projectsByCat`: ``` var oddCategories = projectsByCat.Where((cat, index) => index % 2 != 0); var evenCategories = projectsByCat.Where((cat, index) => index % 2 == 0); ``` And it compiles - however, when I run it, I get an exception such as this: > > Unsupported overload used for query operator 'Where'. > > > And I thought I was safe since it compiled in the first place.. ;) Is there an elegant way to do this? And also, is there an elegant explanation for why my creative use of `Where()` won't work?
If you're using LINQ to SQL or LINQ to Entities you should first fully materialize the results into memory: ``` var oddCategories = projectsByCat.ToList().Where((c,i) => i % 2 != 0); var evenCategories = projectsByCat.ToList().Where((c,i) => i % 2 == 0); ``` It isn't possible to iterate through results on the database with an indexer without the use of a cursor, which either ORM framework does **not** do.
267,057
<p>I hope someone can help me with this, I'm mostly a C# developer so my C and C++ skills are bad. I have a native C dll that is a plugin of a larger application. I cross compile this dll for windows on linux using gcc.</p> <p>In the native dll when I create a D3DSurface I want to call a function in a Mixed Mode C++ dll and pass in the pointer to the surface along with a Hwnd/handle. That Mixed Mode C++ should then call my C# managed code.</p> <p>As an example, in C I want to do the following;</p> <pre><code>Hwnd handle; LPDIRECT3DSURFACE d3dtarg; SurfaceCreated(handle, d3dtarg); </code></pre> <p>In C# I want this called from the mixed mode assembly</p> <pre><code>public static class D3DInterop { public static void SurfaceCreated(IntPtr handle, IntPtr surface) { //do work } } </code></pre> <p>Since I suck at C++, I just want to know if someone can give me an example of what I need to code for the mixed mode dll. I'd also like to not have to compile the mixed mode dll with directx headers, so is there a way I can cast the 'C' LPDIRECT3DSURFACE into a generic pointer? In C# I just use the IntPtr anyway. </p>
[ { "answer_id": 267348, "author": "Joel Lucsy", "author_id": 645, "author_profile": "https://Stackoverflow.com/users/645", "pm_score": 2, "selected": false, "text": "<p>Have you looked into <a href=\"http://en.wikipedia.org/wiki/Microsoft_XNA\" rel=\"nofollow noreferrer\">Microsoft XNA</a>? It supposedly has managed wrappers for DirectX.</p>\n" }, { "answer_id": 268822, "author": "Sunlight", "author_id": 33650, "author_profile": "https://Stackoverflow.com/users/33650", "pm_score": 0, "selected": false, "text": "<p>You can use <code>void *</code> in the mixed-mode DLL. There is an implicit cast from a pointer to anything (including a pointer to <code>IDirect3DSurface</code>) to <code>void *</code>. You can then cast that pointer to <code>IntPtr</code>.</p>\n" }, { "answer_id": 271446, "author": "Assaf Lavie", "author_id": 11208, "author_profile": "https://Stackoverflow.com/users/11208", "pm_score": 2, "selected": false, "text": "<p>Create a managed C++ (C++/CLI) DLL project which will be callable from C and will also be able to reference other .Net assemblies (namely your C# thing). Then all your C++/CLI bridge would have to do is translate the data types from HWND to IntPtr, etc. </p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/267057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I hope someone can help me with this, I'm mostly a C# developer so my C and C++ skills are bad. I have a native C dll that is a plugin of a larger application. I cross compile this dll for windows on linux using gcc. In the native dll when I create a D3DSurface I want to call a function in a Mixed Mode C++ dll and pass in the pointer to the surface along with a Hwnd/handle. That Mixed Mode C++ should then call my C# managed code. As an example, in C I want to do the following; ``` Hwnd handle; LPDIRECT3DSURFACE d3dtarg; SurfaceCreated(handle, d3dtarg); ``` In C# I want this called from the mixed mode assembly ``` public static class D3DInterop { public static void SurfaceCreated(IntPtr handle, IntPtr surface) { //do work } } ``` Since I suck at C++, I just want to know if someone can give me an example of what I need to code for the mixed mode dll. I'd also like to not have to compile the mixed mode dll with directx headers, so is there a way I can cast the 'C' LPDIRECT3DSURFACE into a generic pointer? In C# I just use the IntPtr anyway.
Have you looked into [Microsoft XNA](http://en.wikipedia.org/wiki/Microsoft_XNA)? It supposedly has managed wrappers for DirectX.