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
45,600
<p>The <a href="http://dev.jquery.com/view/trunk/ui/demos/functional/#ui.dialog" rel="nofollow noreferrer">demos</a> for the jquery ui dialog all use the "flora" theme. I wanted a customized theme, so I used the themeroller to generate a css file. When I used it, everything seemed to be working fine, but later I found that I can't control any input element contained in the dialog (i.e, can't type into a text field, can't check checkboxes). Further investigation revealed that this happens if I set the dialog attribute "modal" to true. This doesn't happen when I use the flora theme. </p> <p>Here is the js file:</p> <pre><code>topMenu = { init: function(){ $("#my_button").bind("click", function(){ $("#SERVICE03_DLG").dialog("open"); $("#something").focus(); }); $("#SERVICE03_DLG").dialog({ autoOpen: false, modal: true, resizable: false, title: "my title", overlay: { opacity: 0.5, background: "black" }, buttons: { "OK": function() { alert("hi!"); }, "cancel": function() { $(this).dialog("close"); } }, close: function(){ $("#something").val(""); } }); } } $(document).ready(topMenu.init); </code></pre> <p>Here is the html that uses the flora theme:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS"&gt; &lt;title&gt;sample&lt;/title&gt; &lt;script src="jquery-1.2.6.min.js" language="JavaScript"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="flora/flora.all.css" type="text/css"&gt; &lt;script src="jquery-ui-personalized-1.5.2.min.js" language="JavaScript"&gt;&lt;/script&gt; &lt;script src="TopMenu.js" language="JavaScript"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;input type="button" value="click me!" id="my_button"&gt; &lt;div id="SERVICE03_DLG" class="flora"&gt;please enter something&lt;br&gt;&lt;br&gt; &lt;label for="something"&gt;somthing:&lt;/label&gt;&amp;nbsp;&lt;input name="something" id="something" type="text" maxlength="20" size="24"&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Here is the html that uses the downloaded themeroller theme:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS"&gt; &lt;title&gt;sample&lt;/title&gt; &lt;script src="jquery-1.2.6.min.js" language="JavaScript"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="jquery-ui-themeroller.css" type="text/css"&gt; &lt;script src="jquery-ui-personalized-1.5.2.min.js" language="JavaScript"&gt;&lt;/script&gt; &lt;script src="TopMenu.js" language="JavaScript"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;input type="button" value="click me!" id="my_button"&gt; &lt;div id="SERVICE03_DLG" class="ui-dialog"&gt;please enter something&lt;br&gt;&lt;br&gt; &lt;label for="something"&gt;somthing:&lt;/label&gt;&amp;nbsp;&lt;input name="something" id="something" type="text" maxlength="20" size="24"&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>As you can see, only the referenced css file and class names are different. Anybody have a clue as to what could be wrong?</p> <p>@David: I tried it, and it doesn't seem to work (neither on FF or IE). I tried inline css:</p> <pre class="lang-none prettyprint-override"><code>style="z-index:5000" </code></pre> <p>and I've also tried it referencing an external css file:</p> <pre class="lang-none prettyprint-override"><code>#SERVICE03_DLG{z-index:5000;} </code></pre> <p>But neither of these work. Am I missing something in what you suggested?</p> <p><strong>Edit:</strong><br> Solve by brostbeef!<br> Since I was originally using flora, I had mistakenly assumed that I have to specify a class attribute. Turns out, this is only true when you actually use the flora theme (as in the samples). If you use the customized theme, specifying a class attribute causes that strange behaviour.</p>
[ { "answer_id": 45752, "author": "David McLaughlin", "author_id": 3404, "author_profile": "https://Stackoverflow.com/users/3404", "pm_score": 1, "selected": false, "text": "<p>After playing with this in Firebug, if you add a z-index attribute greater than 1004 to your default div, id of \...
2008/09/05
[ "https://Stackoverflow.com/questions/45600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3751/" ]
The [demos](http://dev.jquery.com/view/trunk/ui/demos/functional/#ui.dialog) for the jquery ui dialog all use the "flora" theme. I wanted a customized theme, so I used the themeroller to generate a css file. When I used it, everything seemed to be working fine, but later I found that I can't control any input element contained in the dialog (i.e, can't type into a text field, can't check checkboxes). Further investigation revealed that this happens if I set the dialog attribute "modal" to true. This doesn't happen when I use the flora theme. Here is the js file: ``` topMenu = { init: function(){ $("#my_button").bind("click", function(){ $("#SERVICE03_DLG").dialog("open"); $("#something").focus(); }); $("#SERVICE03_DLG").dialog({ autoOpen: false, modal: true, resizable: false, title: "my title", overlay: { opacity: 0.5, background: "black" }, buttons: { "OK": function() { alert("hi!"); }, "cancel": function() { $(this).dialog("close"); } }, close: function(){ $("#something").val(""); } }); } } $(document).ready(topMenu.init); ``` Here is the html that uses the flora theme: ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS"> <title>sample</title> <script src="jquery-1.2.6.min.js" language="JavaScript"></script> <link rel="stylesheet" href="flora/flora.all.css" type="text/css"> <script src="jquery-ui-personalized-1.5.2.min.js" language="JavaScript"></script> <script src="TopMenu.js" language="JavaScript"></script> </head> <body> <input type="button" value="click me!" id="my_button"> <div id="SERVICE03_DLG" class="flora">please enter something<br><br> <label for="something">somthing:</label>&nbsp;<input name="something" id="something" type="text" maxlength="20" size="24"> </div> </body> </html> ``` Here is the html that uses the downloaded themeroller theme: ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS"> <title>sample</title> <script src="jquery-1.2.6.min.js" language="JavaScript"></script> <link rel="stylesheet" href="jquery-ui-themeroller.css" type="text/css"> <script src="jquery-ui-personalized-1.5.2.min.js" language="JavaScript"></script> <script src="TopMenu.js" language="JavaScript"></script> </head> <body> <input type="button" value="click me!" id="my_button"> <div id="SERVICE03_DLG" class="ui-dialog">please enter something<br><br> <label for="something">somthing:</label>&nbsp;<input name="something" id="something" type="text" maxlength="20" size="24"> </div> </body> </html> ``` As you can see, only the referenced css file and class names are different. Anybody have a clue as to what could be wrong? @David: I tried it, and it doesn't seem to work (neither on FF or IE). I tried inline css: ```none style="z-index:5000" ``` and I've also tried it referencing an external css file: ```none #SERVICE03_DLG{z-index:5000;} ``` But neither of these work. Am I missing something in what you suggested? **Edit:** Solve by brostbeef! Since I was originally using flora, I had mistakenly assumed that I have to specify a class attribute. Turns out, this is only true when you actually use the flora theme (as in the samples). If you use the customized theme, specifying a class attribute causes that strange behaviour.
I think it is because you have the classes different. `<div id="SERVICE03_DLG" class="flora">` (flora) `<div id="SERVICE03_DLG" class="ui-dialog">` (custom) Even with the flora theme, you would still use the ui-dialog class to define it as a dialog. I've done modals before and I've never even defined a class in the tag. jQueryUI should take care of that for you. Try getting rid of the class attribute or using the "ui-dialog" class.
45,604
<p>C# doesn't require you to specify a generic type parameter if the compiler can infer it, for instance:</p> <pre><code>List&lt;int&gt; myInts = new List&lt;int&gt; {0,1,1, 2,3,5,8,13,21,34,55,89,144,233,377, 610,987,1597,2584,4181,6765}; //this statement is clunky List&lt;string&gt; myStrings = myInts. Select&lt;int,string&gt;( i =&gt; i.ToString() ). ToList&lt;string&gt;(); //the type is inferred from the lambda expression //the compiler knows that it's taking an int and //returning a string List&lt;string&gt; myStrings = myInts. Select( i =&gt; i.ToString() ). ToList(); </code></pre> <p>This is needed for anonymous types where you don't know what the type parameter would be (in intellisense it shows up as <code>'a</code>) because it's added by the compiler.</p> <p>Class-level type parameters don't let you do this:</p> <pre><code>//sample generic class public class GenericDemo&lt;T&gt; { public GenericDemo ( T value ) { GenericTypedProperty = value; } public T GenericTypedProperty {get; set;} } //why can't I do: int anIntValue = 4181; var item = new GenericDemo( anIntValue ); //type inference fails //however I can create a wrapper like this: public static GenericDemo&lt;T&gt; Create&lt;T&gt; ( T value ) { return new GenericDemo&lt;T&gt; ( value ); } //then this works - type inference on the method compiles var item = Create( anIntValue ); </code></pre> <p>Why doesn't C# support this class level generic type inference?</p>
[ { "answer_id": 45612, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>Why doesn't C# support this class level generic type inference?</p>\n</blockquote>\n\n<p>Because th...
2008/09/05
[ "https://Stackoverflow.com/questions/45604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
C# doesn't require you to specify a generic type parameter if the compiler can infer it, for instance: ``` List<int> myInts = new List<int> {0,1,1, 2,3,5,8,13,21,34,55,89,144,233,377, 610,987,1597,2584,4181,6765}; //this statement is clunky List<string> myStrings = myInts. Select<int,string>( i => i.ToString() ). ToList<string>(); //the type is inferred from the lambda expression //the compiler knows that it's taking an int and //returning a string List<string> myStrings = myInts. Select( i => i.ToString() ). ToList(); ``` This is needed for anonymous types where you don't know what the type parameter would be (in intellisense it shows up as `'a`) because it's added by the compiler. Class-level type parameters don't let you do this: ``` //sample generic class public class GenericDemo<T> { public GenericDemo ( T value ) { GenericTypedProperty = value; } public T GenericTypedProperty {get; set;} } //why can't I do: int anIntValue = 4181; var item = new GenericDemo( anIntValue ); //type inference fails //however I can create a wrapper like this: public static GenericDemo<T> Create<T> ( T value ) { return new GenericDemo<T> ( value ); } //then this works - type inference on the method compiles var item = Create( anIntValue ); ``` Why doesn't C# support this class level generic type inference?
Actually, your question isn't bad. I've been toying with a generic programming language for last few years and although I've never come around to actually develop it (and probably never will), I've thought a lot about generic type inference and one of my top priorities has always been to allow the construction of classes without having to specify the generic type. C# simply lacks the set of rules to make this possible. I think the developers never saw the neccesity to include this. Actually, the following code would be very near to your proposition and solve the problem. All C# needs is an added syntax support. ``` class Foo<T> { public Foo(T x) { … } } // Notice: non-generic class overload. Possible in C#! class Foo { public static Foo<T> ctor<T>(T x) { return new Foo<T>(x); } } var x = Foo.ctor(42); ``` Since this code actually works, we've shown that the problem is not one of semantics but simply one of lacking support. I guess I have to take back my previous posting. ;-)
45,611
<p>I have a database with a few dozen tables interlinked with foreign keys. Under normal circumstances, I want the default <code>ON DELETE RESTRICT</code> behavior for those constraints. But when trying to share a snapshot of the database with a consultant, I needed to remove some sensitive data. I wish that my memory of a <code>DELETE FROM Table CASCADE</code> command hadn't been pure hallucination.</p> <p>What I ended out doing was dumping the database, writing a script to process the dump by adding <code>ON DELETE CASCADE</code> clauses too all the foreign key constraints, restoring from that, performing my deletes, dumping again, removing the <code>ON DELETE CASCADE</code>, and finally restoring again. That was easier than writing the deletion query I'd have needed to do this in SQL -- removing whole slices of the database isn't a normal operation, so the schema isn't exactly adapted to it.</p> <p>Does anyone have a better solution for the next time something like this comes up?</p>
[ { "answer_id": 45893, "author": "Tony Lenzi", "author_id": 4513, "author_profile": "https://Stackoverflow.com/users/4513", "pm_score": 0, "selected": false, "text": "<p>You may want to look into using <a href=\"http://www.postgresql.org/docs/8.2/static/ddl-schemas.html\" rel=\"nofollow n...
2008/09/05
[ "https://Stackoverflow.com/questions/45611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a database with a few dozen tables interlinked with foreign keys. Under normal circumstances, I want the default `ON DELETE RESTRICT` behavior for those constraints. But when trying to share a snapshot of the database with a consultant, I needed to remove some sensitive data. I wish that my memory of a `DELETE FROM Table CASCADE` command hadn't been pure hallucination. What I ended out doing was dumping the database, writing a script to process the dump by adding `ON DELETE CASCADE` clauses too all the foreign key constraints, restoring from that, performing my deletes, dumping again, removing the `ON DELETE CASCADE`, and finally restoring again. That was easier than writing the deletion query I'd have needed to do this in SQL -- removing whole slices of the database isn't a normal operation, so the schema isn't exactly adapted to it. Does anyone have a better solution for the next time something like this comes up?
You do not need to dump and restore. You should be able to just drop the constraint, rebuild it with cascade, do your deletes, drop it again, and the rebuild it with restrict. ``` CREATE TABLE "header" ( header_id serial NOT NULL, CONSTRAINT header_pkey PRIMARY KEY (header_id) ); CREATE TABLE detail ( header_id integer, stuff text, CONSTRAINT detail_header_id_fkey FOREIGN KEY (header_id) REFERENCES "header" (header_id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION ); insert into header values(1); insert into detail values(1,'stuff'); delete from header where header_id=1; alter table detail drop constraint detail_header_id_fkey; alter table detail add constraint detail_header_id_fkey FOREIGN KEY (header_id) REFERENCES "header" (header_id) on delete cascade; delete from header where header_id=1; alter table detail add constraint detail_header_id_fkey FOREIGN KEY (header_id) REFERENCES "header" (header_id) on delete restrict; ```
45,613
<p>What could be the problem with reversing the array of DOM objects as in the following code:</p> <pre><code>var imagesArr = new Array(); imagesArr = document.getElementById("myDivHolderId").getElementsByTagName("img"); imagesArr.reverse(); </code></pre> <p>In Firefox 3, when I call the <code>reverse()</code> method the script stops executing and shows the following error in the console of the Web Developer Toolbar:</p> <pre class="lang-none prettyprint-override"><code>imagesArr.reverse is not a function </code></pre> <p>The <code>imagesArr</code> variable can be iterated through with a for loop and elements like <code>imagesArr[i]</code> can be accessed, so why is it not seen as an array when calling the <code>reverse()</code> method?</p>
[ { "answer_id": 45622, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": 1, "selected": false, "text": "<p>Your first line is irrelevant, since it doesn't coerce the assignment to the variable, javascript works the other ...
2008/09/05
[ "https://Stackoverflow.com/questions/45613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4723/" ]
What could be the problem with reversing the array of DOM objects as in the following code: ``` var imagesArr = new Array(); imagesArr = document.getElementById("myDivHolderId").getElementsByTagName("img"); imagesArr.reverse(); ``` In Firefox 3, when I call the `reverse()` method the script stops executing and shows the following error in the console of the Web Developer Toolbar: ```none imagesArr.reverse is not a function ``` The `imagesArr` variable can be iterated through with a for loop and elements like `imagesArr[i]` can be accessed, so why is it not seen as an array when calling the `reverse()` method?
Because getElementsByTag name actually returns a NodeList structure. It has similar array like indexing properties for syntactic convenience, but it is *not* an array. For example, the set of entries is actually constantly being dynamically updated - if you add a new img tag under myDivHolderId, it will automatically appear in imagesArr. See <http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-536297177> for more.
45,623
<p>In Java, what would the best way be to have a constantly listening port open, and still send upon receipt of a packet. I am not particularly savvy with network programming at the moment, so the tutorials I have found on the net aren't particularly helpful.</p> <p>Would it make sense to have the listening socket as a serversocket and run it in a separate thread to the socket I'm using to send data to the server?</p> <p>In a loosely related question. Does anyone know if programming simply for java, in netbeans then exporting it for use on a blackberry (using a plugin) the sockets would still work ?</p>
[ { "answer_id": 45630, "author": "basszero", "author_id": 287, "author_profile": "https://Stackoverflow.com/users/287", "pm_score": 5, "selected": true, "text": "<p>If you can afford the threading, try this (keep in mind I've left out some details like exception handling and playing nice ...
2008/09/05
[ "https://Stackoverflow.com/questions/45623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4739/" ]
In Java, what would the best way be to have a constantly listening port open, and still send upon receipt of a packet. I am not particularly savvy with network programming at the moment, so the tutorials I have found on the net aren't particularly helpful. Would it make sense to have the listening socket as a serversocket and run it in a separate thread to the socket I'm using to send data to the server? In a loosely related question. Does anyone know if programming simply for java, in netbeans then exporting it for use on a blackberry (using a plugin) the sockets would still work ?
If you can afford the threading, try this (keep in mind I've left out some details like exception handling and playing nice with threads). You may want to look into `SocketChannels` and/or NIO async sockets / selectors. This should get you started. ``` boolean finished = false; int port = 10000; ServerSocket server = new ServerSocket(port); while (!finished) { // This will block until a connection is made Socket s = server.accept(); // Spawn off some thread (or use a thread pool) to handle this socket // Server will continue to listen } ```
45,624
<p>I use TortoiseSVN to access file based local repo. In all my commits an author is my Windows login name. Is it possible to use different name?</p> <p>I know how to change author after commit but how to change before? Installing apache/svnserver is not an option. </p>
[ { "answer_id": 45668, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>As far as I know, TortoiseSVN does not offer any way to do this.</p>\n\n<p>Presumably it's not seen as a big issue, since fi...
2008/09/05
[ "https://Stackoverflow.com/questions/45624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/501/" ]
I use TortoiseSVN to access file based local repo. In all my commits an author is my Windows login name. Is it possible to use different name? I know how to change author after commit but how to change before? Installing apache/svnserver is not an option.
Yes, it's possible. *TortoiseSVN* and the [*svn*](http://subversion.tigris.org/) command line client share the same settings location in your profile folder. So you may simply checkout one version using *svn.exe*: ``` $ svn co --username different_user_name file:///C:/path/to/your/repo ``` ... and Subversion will happily replace the associated username for that repository. New commits from TortoiseSVN will then always use that username, no matter with what program you make the new checkouts. The procedure should work with TortoiseSVN 1.5.5. If it doesn't, try emptying svn's authentication cache (`%APPDATA%\Subversion\auth\svn.username`) first.
45,626
<p>I have a basic CRUD form that uses PageMethods to update the user details, however the Validators don't fire off, I think I need to manually initialize the validators and check whether the validation has passed in my javascript save method. Any ideas on how to do this?</p>
[ { "answer_id": 45892, "author": "Sara Chipps", "author_id": 4140, "author_profile": "https://Stackoverflow.com/users/4140", "pm_score": 0, "selected": false, "text": "<p>what are you using for development? VS 2008 supposedly has better JS debugging, haven't tried it yet. </p>\n\n<p>For A...
2008/09/05
[ "https://Stackoverflow.com/questions/45626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2808/" ]
I have a basic CRUD form that uses PageMethods to update the user details, however the Validators don't fire off, I think I need to manually initialize the validators and check whether the validation has passed in my javascript save method. Any ideas on how to do this?
Ok so I finally solved this: You need to call `Page_ClientValidate()` in your Save javascript method and If it returns true continue with the save, the `Page_ClientValidate()` initiates the client side validators, See code below: ``` function Save() { var clientValidationPassed =Page_ClientValidate(); if(clientValidationPassed) { //Save Data PageMethods.SaveUser(UserName,Role,SaveCustomerRequestComplete, RequestError); $find('editPopupExtender').hide(); } else { //Do Nothing as CLient Validation messages are now displayed } return false; } ```
45,634
<p>How do you rewrite this in Linq?</p> <pre><code>SELECT Id, Name FROM TableA WHERE TableA.Id IN (SELECT xx from TableB INNER JOIN Table C....) </code></pre> <p>So in plain english, I want to select Id and Name from TableA where TableA's Id is in a result set from a second query.</p>
[ { "answer_id": 45648, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 4, "selected": true, "text": "<pre><code>from a in TableA \nwhere (from b in TableB \n join c in TableC on b.id equals c.id\n where .. select...
2008/09/05
[ "https://Stackoverflow.com/questions/45634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3047/" ]
How do you rewrite this in Linq? ``` SELECT Id, Name FROM TableA WHERE TableA.Id IN (SELECT xx from TableB INNER JOIN Table C....) ``` So in plain english, I want to select Id and Name from TableA where TableA's Id is in a result set from a second query.
``` from a in TableA where (from b in TableB join c in TableC on b.id equals c.id where .. select b.id) .Contains(a.Id) select new { a.Id, a.Name } ```
45,642
<p>I was wondering if there is an open source library or algorithm that can expand a non-numeric range. For example, if you have <code>1A</code> to <code>9A</code> you should get </p> <pre><code>1A, 2A, 3A, 4A, 5A, 6A, 7A, 8A, 9A. </code></pre> <p>I've tried Googling for this and the best I could come up with were Regex that would expand numerics with dashes (1-3 becoming 1,2,3).</p>
[ { "answer_id": 45701, "author": "Gariig", "author_id": 1210, "author_profile": "https://Stackoverflow.com/users/1210", "pm_score": 0, "selected": false, "text": "<p>I was trying to leave it somewhat open because the number of possibilities is staggering. I believe this one of those ques...
2008/09/05
[ "https://Stackoverflow.com/questions/45642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1210/" ]
I was wondering if there is an open source library or algorithm that can expand a non-numeric range. For example, if you have `1A` to `9A` you should get ``` 1A, 2A, 3A, 4A, 5A, 6A, 7A, 8A, 9A. ``` I've tried Googling for this and the best I could come up with were Regex that would expand numerics with dashes (1-3 becoming 1,2,3).
As noted by others, it would be useful to be more specific. I don't think you can expect there to be a library that will generate ranges according to any arbitrary order on string you can come up with. If you can simply define what the successor of any given string is, then the solutions is quite easy. That is, if you have a successor function `S` on strings (e.g. with `S('3A') = '4A'`), then something like the following can be used: ``` s = initial_string while s != final_string do output s s = S(s) output s ``` Something I have used in the past to generate all strings of a given length `l` and with given range `b` to `e` of characters, is the following piece of (pseudo-)code. It can be easily adapted to a wide range of variations. ``` // initialise s with b at every position for i in [0..l) do s[i] = b done = false while not done do output s j = 0 // if s[j] is e, reset it to b and "add carry" while j < l and s[j] == e do s[j] = b j = j + 1 if j == l then done = true if not done then s[j] = s[j] + 1 ``` For example, to start at a specific string you need only the change the initialisation. To set the end you only need to change the behaviour for the inner while to separately handle position `l` (limiting to the character in the end string on that position and if reached decrementing `l`).
45,653
<p>We use QuickBooks for financial management, and feed it from a variety of sources. I now need to hook it up to BizTalk, and I'd hate to reinvent the wheel. I've done searches, and as far as I can tell there's no QuickBooks adapter for BizTalk. Does anyone know of anything that'll do the job, preferably something that doesn't suck? </p> <hr> <p>Doesn't the QB SDK require that Quickbooks be running on the client machine? Is there any way around it?</p>
[ { "answer_id": 45735, "author": "seanyboy", "author_id": 1726, "author_profile": "https://Stackoverflow.com/users/1726", "pm_score": 2, "selected": true, "text": "<p>Quickbooks talks .NET quite easily. You'll need the QuickBooks SDK 7.0 and a copy of Visual Studio.NET, but after that it'...
2008/09/05
[ "https://Stackoverflow.com/questions/45653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2757/" ]
We use QuickBooks for financial management, and feed it from a variety of sources. I now need to hook it up to BizTalk, and I'd hate to reinvent the wheel. I've done searches, and as far as I can tell there's no QuickBooks adapter for BizTalk. Does anyone know of anything that'll do the job, preferably something that doesn't suck? --- Doesn't the QB SDK require that Quickbooks be running on the client machine? Is there any way around it?
Quickbooks talks .NET quite easily. You'll need the QuickBooks SDK 7.0 and a copy of Visual Studio.NET, but after that it's very easy to do anything with Quickbooks. ``` Imports QBFC7Lib Sub AttachToDB() If isAttachedtoQB Then Exit Sub Lasterror = "Unknown QuickBooks Error" Try QbSession = New QBSessionManager QbSession.OpenConnection("", "Your Company Name") QbSession.BeginSession("", ENOpenMode.omDontCare) MsgReq = QbSession.CreateMsgSetRequest("UK", 6, 0) MsgReq.Attributes.OnError = ENRqOnError.roeStop Lasterror = "" isAttachedtoQB = True Catch e As Exception If Not QbSession Is Nothing Then QbSession.CloseConnection() QbSession = Nothing End If isAttachedtoQB = False Lasterror = "QuickBooks Connection Error. - " + e.Message + "." End Try End Sub ``` See <http://developer.intuit.com/> for more information.
45,658
<p>I wrote an Active X plugin for IE7 which implements IObjectWithSite besides some other necessary interfaces (note no IOleClient). This interface is queried and called by IE7. During the SetSite() call I retrieve a pointer to IE7's site interface which I can use to retrieve the IHTMLDocument2 interface using the following approach:</p> <pre><code>IUnknown *site = pUnkSite; /* retrieved from IE7 during SetSite() call */ IServiceProvider *sp = NULL; IHTMLWindow2 *win = NULL; IHTMLDocument2 *doc = NULL; if(site) { site-&gt;QueryInterface(IID_IServiceProvider, (void **)&amp;sp); if(sp) { sp-&gt;QueryService(IID_IHTMLWindow2, IID_IHTMLWindow2, (void **)&amp;win); if(win) { win-&gt;get_document(&amp;doc); } } } if(doc) { /* found */ } </code></pre> <p>I tried a similiar approach on PIE as well using the following code, however, even the IPIEHTMLWindow2 interface cannot be acquired, so I'm stuck:</p> <pre><code>IUnknown *site = pUnkSite; /* retrieved from PIE during SetSite() call */ IPIEHTMLWindow2 *win = NULL; IPIEHTMLDocument1 *tmp = NULL; IPIEHTMLDocument2 *doc = NULL; if(site) { site-&gt;QueryInterface(__uuidof(*win), (void **)&amp;win); if(win) { /* never the case */ win-&gt;get_document(&amp;tmp); if(tmp) { tmp-&gt;QueryInterface(__uuidof(*doc), (void **)&amp;doc); } } } if(doc) { /* found */ } </code></pre> <p>Using the IServiceProvider interface doesn't work either, so I already tested this.</p> <p>Any ideas?</p>
[ { "answer_id": 63430, "author": "gnobal", "author_id": 7748, "author_profile": "https://Stackoverflow.com/users/7748", "pm_score": 3, "selected": true, "text": "<p>I found the following code in the Google Gears code, <a href=\"http://code.google.com/p/gears/source/browse/trunk/gears/base...
2008/09/05
[ "https://Stackoverflow.com/questions/45658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4735/" ]
I wrote an Active X plugin for IE7 which implements IObjectWithSite besides some other necessary interfaces (note no IOleClient). This interface is queried and called by IE7. During the SetSite() call I retrieve a pointer to IE7's site interface which I can use to retrieve the IHTMLDocument2 interface using the following approach: ``` IUnknown *site = pUnkSite; /* retrieved from IE7 during SetSite() call */ IServiceProvider *sp = NULL; IHTMLWindow2 *win = NULL; IHTMLDocument2 *doc = NULL; if(site) { site->QueryInterface(IID_IServiceProvider, (void **)&sp); if(sp) { sp->QueryService(IID_IHTMLWindow2, IID_IHTMLWindow2, (void **)&win); if(win) { win->get_document(&doc); } } } if(doc) { /* found */ } ``` I tried a similiar approach on PIE as well using the following code, however, even the IPIEHTMLWindow2 interface cannot be acquired, so I'm stuck: ``` IUnknown *site = pUnkSite; /* retrieved from PIE during SetSite() call */ IPIEHTMLWindow2 *win = NULL; IPIEHTMLDocument1 *tmp = NULL; IPIEHTMLDocument2 *doc = NULL; if(site) { site->QueryInterface(__uuidof(*win), (void **)&win); if(win) { /* never the case */ win->get_document(&tmp); if(tmp) { tmp->QueryInterface(__uuidof(*doc), (void **)&doc); } } } if(doc) { /* found */ } ``` Using the IServiceProvider interface doesn't work either, so I already tested this. Any ideas?
I found the following code in the Google Gears code, [here](http://code.google.com/p/gears/source/browse/trunk/gears/base/ie/activex_utils.cc?r=2157). I copied the functions I think you need to here. The one you need is at the bottom (GetHtmlWindow2), but the other two are needed as well. Hopefully I didn't miss anything, but if I did the stuff you need is probably at the link. ``` #ifdef WINCE // We can't get IWebBrowser2 for WinCE. #else HRESULT ActiveXUtils::GetWebBrowser2(IUnknown *site, IWebBrowser2 **browser2) { CComQIPtr<IServiceProvider> service_provider = site; if (!service_provider) { return E_FAIL; } return service_provider->QueryService(SID_SWebBrowserApp, IID_IWebBrowser2, reinterpret_cast<void**>(browser2)); } #endif HRESULT ActiveXUtils::GetHtmlDocument2(IUnknown *site, IHTMLDocument2 **document2) { HRESULT hr; #ifdef WINCE // Follow path Window2 -> Window -> Document -> Document2 CComPtr<IPIEHTMLWindow2> window2; hr = GetHtmlWindow2(site, &window2); if (FAILED(hr) || !window2) { return false; } CComQIPtr<IPIEHTMLWindow> window = window2; CComPtr<IHTMLDocument> document; hr = window->get_document(&document); if (FAILED(hr) || !document) { return E_FAIL; } return document->QueryInterface(__uuidof(*document2), reinterpret_cast<void**>(document2)); #else CComPtr<IWebBrowser2> web_browser2; hr = GetWebBrowser2(site, &web_browser2); if (FAILED(hr) || !web_browser2) { return E_FAIL; } CComPtr<IDispatch> doc_dispatch; hr = web_browser2->get_Document(&doc_dispatch); if (FAILED(hr) || !doc_dispatch) { return E_FAIL; } return doc_dispatch->QueryInterface(document2); #endif } HRESULT ActiveXUtils::GetHtmlWindow2(IUnknown *site, #ifdef WINCE IPIEHTMLWindow2 **window2) { // site is javascript IDispatch pointer. return site->QueryInterface(__uuidof(*window2), reinterpret_cast<void**>(window2)); #else IHTMLWindow2 **window2) { CComPtr<IHTMLDocument2> html_document2; // To hook an event on a page's window object, follow the path // IWebBrowser2->document->parentWindow->IHTMLWindow2 HRESULT hr = GetHtmlDocument2(site, &html_document2); if (FAILED(hr) || !html_document2) { return E_FAIL; } return html_document2->get_parentWindow(window2); #endif } ```
45,732
<p>I have an object graph serialized to xaml. A rough sample of what it looks like is:</p> <pre><code>&lt;MyObject xmlns.... &gt; &lt;MyObject.TheCollection&gt; &lt;PolymorphicObjectOne .../&gt; &lt;HiImPolymorphic ... /&gt; &lt;/MyObject.TheCollection&gt; &lt;/MyObject&gt; </code></pre> <p>I want to use Linq to XML in order to extract the serialized objects within the TheCollection.</p> <p><strong>Note</strong>: <code>MyObject</code> may be named differently at runtime; I'm interested in any object that implements the same interface, which has a public collection called <code>TheCollection</code> that contains types of <code>IPolymorphicLol</code>.</p> <p>The only things I know at runtime are the depth at which I will find the collection and that the collection element is named ``*.TheCollection`. Everything else will change.</p> <p>The xml will be retrieved from a database using Linq; if I could combine both queries so instead of getting the entire serialized graph and then extracting the collection objects I would just get back the collection that would be sweet.</p>
[ { "answer_id": 45745, "author": "hakan", "author_id": 3993, "author_profile": "https://Stackoverflow.com/users/3993", "pm_score": 1, "selected": false, "text": "<p>I am not exactly sure about it but I believe GacRemove should do the same thing as gacutil /u. So, it should be the path of...
2008/09/05
[ "https://Stackoverflow.com/questions/45732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have an object graph serialized to xaml. A rough sample of what it looks like is: ``` <MyObject xmlns.... > <MyObject.TheCollection> <PolymorphicObjectOne .../> <HiImPolymorphic ... /> </MyObject.TheCollection> </MyObject> ``` I want to use Linq to XML in order to extract the serialized objects within the TheCollection. **Note**: `MyObject` may be named differently at runtime; I'm interested in any object that implements the same interface, which has a public collection called `TheCollection` that contains types of `IPolymorphicLol`. The only things I know at runtime are the depth at which I will find the collection and that the collection element is named ``\*.TheCollection`. Everything else will change. The xml will be retrieved from a database using Linq; if I could combine both queries so instead of getting the entire serialized graph and then extracting the collection objects I would just get back the collection that would be sweet.
I am using the `GacInstall` to publish my assemblies, however once installed into the gac, I sometimes delete my ‘temporary’ copy of the assemblies. And then, if I ever wanted to uninstall the assemblies from the gac I do not have the files at the original path. This is causing a problem since I cannot seem to get the `GacRemove` method to uninstall the assemblies unless I keep the original files. Conclusion: Yes, you need to specify the path to the original DLL. (And try to not move/delete it later). If you delete it, try to copy the file from the GAC to your original path and you should be able to uninstall it using `GacRemove`.
45,769
<p>I'm curious about everyones practices when it comes to using or distributing libraries for an application that you write.</p> <p>First of all, when developing your application do you link the debug or release version of the libraries? (For when you run your application in debug mode)</p> <p>Then when you run your app in release mode just before deploying, which build of the libraries do you use?</p> <p>How do you perform the switch between your debug and release version of the libraries? Do you do it manually, do you use macros, or whatever else is it that you do?</p>
[ { "answer_id": 46120, "author": "Henk", "author_id": 4613, "author_profile": "https://Stackoverflow.com/users/4613", "pm_score": 2, "selected": false, "text": "<p>I would first determine what requirements are needed from the library:</p>\n\n<ol>\n<li>Debug/Release</li>\n<li>Unicode suppo...
2008/09/05
[ "https://Stackoverflow.com/questions/45769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4225/" ]
I'm curious about everyones practices when it comes to using or distributing libraries for an application that you write. First of all, when developing your application do you link the debug or release version of the libraries? (For when you run your application in debug mode) Then when you run your app in release mode just before deploying, which build of the libraries do you use? How do you perform the switch between your debug and release version of the libraries? Do you do it manually, do you use macros, or whatever else is it that you do?
I would first determine what requirements are needed from the library: 1. Debug/Release 2. Unicode support 3. And so on.. With that determined you can then create configurations for each combination required by yourself or other library users. When compiling and linking it is very important that you keep that libraries and executable consistent with respect to configurations used i.e. don't mix release & debug when linking. I know on the Windows/VS platform this can cause subtle memory issues if debug & release libs are mixed within an executable. As Brian has mentioned to Visual Studio it's best to use the Configuration Manager to setup how you want each configuration you require to be built. For example our projects require the following configurations to be available depending on the executable being built. 1. Debug+Unicode 2. Debug+ASCII 3. Release+Unicode 4. Release+ASCII The users of this particular project use the Configuration Manager to match their executable requirements with the project's available configurations. Regarding the use of macros, they are used extensively in implementing compile time decisions for requirements like if the debug or release version of a function is to be linked. If you're using VS you can view the pre-processor definitions attribute to see how the various macros are defined e.g. \_DEBUG \_RELEASE, this is how the configuration controls whats compiled. What platform are you using to compile/link your projects? EDIT: Expanding on your updated comment.. If the **Configuration Manager** option is not available to you then I recommend using the following properties from the project: * **Linker**->**Additional Library Directories** or **Linker**->**Input** Use the macro `$(ConfigurationName)` to link with the appropriate library configuration e.g. Debug/Release. ``` $(ProjectDir)\..\third-party-prj\$(ConfigurationName)\third-party.lib ``` * **Build Events** or **Custom Build Step** configuration property Execute a copy of the required library file(s) from the dependent project prior (or after) to the build occurring. ``` xcopy $(ProjectDir)\..\third-party-prj\$(ConfigurationName)\third-party.dll $(IntDir) ``` The macro `$(ProjectDir)` will be substituted for the current project's location and causes the operation to occur relative to the current project. The macro `$(ConfigurationName)` will be substituted for the currently selected configuration (default is `Debug` or `Release`) which allows the correct items to be copied depending on what configuration is being built currently. If you use a regular naming convention for your project configurations it will help, as you can use the `$(ConfigurationName)` macro, otherwise you can simply use a fixed string.
45,779
<p>How would you dynamically subscribe to a C# event so that given a Object instance and a String name containing the name of the event, you subscribe to that event and do something (write to the console for example) when that event has been fired?</p> <p>It would seem using Reflection this isn't possible and I would like to avoid having to use Reflection.Emit if possible, as this currently (to me) seems like the only way of doing it.</p> <p><strong>/EDIT:</strong> I do not know the signature of the delegate needed for the event, this is the core of the problem</p> <p><strong>/EDIT 2:</strong> Although delegate contravariance seems like a good plan, I can not make the assumption necessary to use this solution</p>
[ { "answer_id": 45795, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 0, "selected": false, "text": "<p>What you want can be achieved using dependency injection. For example <a href=\"http://msdn.microsoft.com/en-us/library/aa4804...
2008/09/05
[ "https://Stackoverflow.com/questions/45779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1111/" ]
How would you dynamically subscribe to a C# event so that given a Object instance and a String name containing the name of the event, you subscribe to that event and do something (write to the console for example) when that event has been fired? It would seem using Reflection this isn't possible and I would like to avoid having to use Reflection.Emit if possible, as this currently (to me) seems like the only way of doing it. **/EDIT:** I do not know the signature of the delegate needed for the event, this is the core of the problem **/EDIT 2:** Although delegate contravariance seems like a good plan, I can not make the assumption necessary to use this solution
You can compile expression trees to use void methods without any arguments as event handlers for events of any type. To accommodate other event handler types, you have to map the event handler's parameters to the events somehow. ``` using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; class ExampleEventArgs : EventArgs { public int IntArg {get; set;} } class EventRaiser { public event EventHandler SomethingHappened; public event EventHandler<ExampleEventArgs> SomethingHappenedWithArg; public void RaiseEvents() { if (SomethingHappened!=null) SomethingHappened(this, EventArgs.Empty); if (SomethingHappenedWithArg!=null) { SomethingHappenedWithArg(this, new ExampleEventArgs{IntArg = 5}); } } } class Handler { public void HandleEvent() { Console.WriteLine("Handler.HandleEvent() called.");} public void HandleEventWithArg(int arg) { Console.WriteLine("Arg: {0}",arg); } } static class EventProxy { //void delegates with no parameters static public Delegate Create(EventInfo evt, Action d) { var handlerType = evt.EventHandlerType; var eventParams = handlerType.GetMethod("Invoke").GetParameters(); //lambda: (object x0, EventArgs x1) => d() var parameters = eventParams.Select(p=>Expression.Parameter(p.ParameterType,"x")); var body = Expression.Call(Expression.Constant(d),d.GetType().GetMethod("Invoke")); var lambda = Expression.Lambda(body,parameters.ToArray()); return Delegate.CreateDelegate(handlerType, lambda.Compile(), "Invoke", false); } //void delegate with one parameter static public Delegate Create<T>(EventInfo evt, Action<T> d) { var handlerType = evt.EventHandlerType; var eventParams = handlerType.GetMethod("Invoke").GetParameters(); //lambda: (object x0, ExampleEventArgs x1) => d(x1.IntArg) var parameters = eventParams.Select(p=>Expression.Parameter(p.ParameterType,"x")).ToArray(); var arg = getArgExpression(parameters[1], typeof(T)); var body = Expression.Call(Expression.Constant(d),d.GetType().GetMethod("Invoke"), arg); var lambda = Expression.Lambda(body,parameters); return Delegate.CreateDelegate(handlerType, lambda.Compile(), "Invoke", false); } //returns an expression that represents an argument to be passed to the delegate static Expression getArgExpression(ParameterExpression eventArgs, Type handlerArgType) { if (eventArgs.Type==typeof(ExampleEventArgs) && handlerArgType==typeof(int)) { //"x1.IntArg" var memberInfo = eventArgs.Type.GetMember("IntArg")[0]; return Expression.MakeMemberAccess(eventArgs,memberInfo); } throw new NotSupportedException(eventArgs+"->"+handlerArgType); } } static class Test { public static void Main() { var raiser = new EventRaiser(); var handler = new Handler(); //void delegate with no parameters string eventName = "SomethingHappened"; var eventinfo = raiser.GetType().GetEvent(eventName); eventinfo.AddEventHandler(raiser,EventProxy.Create(eventinfo,handler.HandleEvent)); //void delegate with one parameter string eventName2 = "SomethingHappenedWithArg"; var eventInfo2 = raiser.GetType().GetEvent(eventName2); eventInfo2.AddEventHandler(raiser,EventProxy.Create<int>(eventInfo2,handler.HandleEventWithArg)); //or even just: eventinfo.AddEventHandler(raiser,EventProxy.Create(eventinfo,()=>Console.WriteLine("!"))); eventInfo2.AddEventHandler(raiser,EventProxy.Create<int>(eventInfo2,i=>Console.WriteLine(i+"!"))); raiser.RaiseEvents(); } } ```
45,783
<p>My team is currently trying to automate the deployment of our .Net and PHP web applications. We want to streamline deployments, and to avoid the hassle and many of the headaches caused by doing it manually.</p> <p>We require a solution that will enable us to:</p> <pre><code>- Compile the application - Version the application with the SVN version number - Backup the existing site - Deploy to a web farm </code></pre> <p>All our apps are source controlled using SVN and our .Net apps use CruiseControl. We have been trying to use MSBuild and NAnt deployment scripts with limited success. We have also used Capistrano in the past, but wish to avoid using Ruby if possible.</p> <p>Are there any other deployment tools out there that would help us?</p>
[ { "answer_id": 45799, "author": "Jordi Bunster", "author_id": 4272, "author_profile": "https://Stackoverflow.com/users/4272", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.nongnu.org/fab/\" rel=\"nofollow noreferrer\">Fabric</a>. Seems small, simple, procedural. Writ...
2008/09/05
[ "https://Stackoverflow.com/questions/45783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4734/" ]
My team is currently trying to automate the deployment of our .Net and PHP web applications. We want to streamline deployments, and to avoid the hassle and many of the headaches caused by doing it manually. We require a solution that will enable us to: ``` - Compile the application - Version the application with the SVN version number - Backup the existing site - Deploy to a web farm ``` All our apps are source controlled using SVN and our .Net apps use CruiseControl. We have been trying to use MSBuild and NAnt deployment scripts with limited success. We have also used Capistrano in the past, but wish to avoid using Ruby if possible. Are there any other deployment tools out there that would help us?
Thank you all for your kind suggestions. We checked them all out, but after careful consideration we decided to roll our own with a combination of CruiseControl, NAnt, MSBuild and MSDeploy. This article has some great information: [Integrating MSBuild with CruiseControl.NET](http://dougrohm.com/blog/post/2006/01/29/Integrating-MSBuild-with-CruiseControlNET.aspx) Here's roughly how our solution works: * Developers build the 'debug' version of the app and run unit tests, then check in to SVN. * CruiseControl sees the updates and calls our build script... + Runs any new migrations on the build database + Replaces the config files with the build server config + Builds the 'debug' configuration of the app + Runs all unit and integration tests + Builds the 'deploy' configuration of the app - Versions the DLLs with the current major/minor version and SVN revision, e.g. 1.2.0.423 - Moves this new build to a 'release' folder on our build server - Removes unneeded files + Updates IIS on the build server if required Then when we have verified everything is ready to go up to live/staging we run another script to: * Run migrations on live/staging server * MSDeploy: archive current live/staging site * MSDeploy: sync site from build to live/staging It wasn't pretty getting to this stage, but it's mostly working like a charm now :D I'm going to try and keep this answer updated as we make changes to our process, as there seem to be several similar questions on SA now.
45,796
<p>Our ASP.NET 3.5 website running on IIS 6 has two teams that are adding content: </p> <ul> <li>Development team adding code. </li> <li>Business team adding simple web pages. </li> </ul> <p>For sanity and organization, we would like for the business team to add their web pages to a sub-folder in the project: </p> <blockquote> <p>Root: for pages of development team </p> <p>Content: for pages of business team </p> </blockquote> <p><strong>But</strong> </p> <p>We would like for users to be able to navigate to the business team content without having to append "Content" in their URLs, as described below:</p> <blockquote> <p><strong>Root</strong>: Default.aspx (<em>Available at: www.oursite.com/default.aspx</em>)</p> <p><strong>Content</strong>: Popcorn.aspx (<em>Available at: www.oursite.com/popcorn.aspx</em>)</p> </blockquote> <p>Is there a way we can accomplish for making a config entry in an ISAPI rewrite tool for every one of these pages?</p>
[ { "answer_id": 45808, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 2, "selected": false, "text": "<p>Since the extensions will be ASPX, ASP.NET will pick up the request... you can write an HttpModule that checks for p...
2008/09/05
[ "https://Stackoverflow.com/questions/45796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/308/" ]
Our ASP.NET 3.5 website running on IIS 6 has two teams that are adding content: * Development team adding code. * Business team adding simple web pages. For sanity and organization, we would like for the business team to add their web pages to a sub-folder in the project: > > Root: for pages of development team > > > Content: for pages of business team > > > **But** We would like for users to be able to navigate to the business team content without having to append "Content" in their URLs, as described below: > > **Root**: Default.aspx (*Available at: www.oursite.com/default.aspx*) > > > **Content**: Popcorn.aspx (*Available at: www.oursite.com/popcorn.aspx*) > > > Is there a way we can accomplish for making a config entry in an ISAPI rewrite tool for every one of these pages?
I don't have any way to test this right now, but I think you can use the -f flag on RewriteCond to check if a file exists, in either directory. ``` RewriteCond %{REQUEST_FILENAME} -!f RewriteCond Content/%{REQUEST_FILENAME} -f RewriteRule (.*) Content/(.*) ``` Something like that might do what you're after, too.
45,803
<ol> <li>Video podcast</li> <li>???</li> <li>Audio only mp3 player</li> </ol> <p>I'm looking for somewhere which will extract audio from video, but instead of a single file, for an on going video podcast.</p> <p>I would most like a website which would suck in the RSS and spit out an RSS (I'm thinking of something like Feedburner), though would settle for something on my own machine.</p> <p>If it must be on my machine, it should be quick, transparent, and automatic when I download each episode. </p> <p>What would you use?</p> <p><b>Edit:</b> I'm on an Ubuntu 8.04 machine; so running ffmpeg is no problem; however, I'm looking for automation and feed awareness.</p> <p>Here's my use case: I want to listen to <a href="http://video.google.com/videosearch?q=google+techtalks&amp;so=1&amp;output=rss" rel="nofollow noreferrer">lectures</a> at Google Video, or <a href="http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/" rel="nofollow noreferrer">Structure and Interpretation of Computer Programs</a>. These videos come out fairly often, so anything that's needed to be done manually will also be done fairly often. </p> <p>Here's one approach I'd thought of:</p> <ul> <li>download the RSS</li> <li>parse the RSS for enclosures, </li> <li>download the enclosures, keeping a track what has already been downloaded previously</li> <li>transcode the files, but not the ones done already</li> <li>reconstruct an RSS with the audio files, remembering to change the metadata.</li> <li>schedule to be run periodically</li> <li>point podcatcher at new RSS feed.</li> </ul> <p>I also liked the approach of gPodder of using a <a href="http://wiki.gpodder.org/wiki/Time_stretching#Using_the_post-download_script_hook" rel="nofollow noreferrer">post-download script</a>.</p> <p>I wish the <a href="http://www.openp2p.com/pub/a/p2p/2003/01/07/lazyweb.html" rel="nofollow noreferrer">Lazy Web</a> still worked.</p>
[ { "answer_id": 45810, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 0, "selected": false, "text": "<p>How to extract audio from video to MP3:</p>\n\n<p><a href=\"http://www.dvdvideosoft.com/guides/dvd/extract-audio-from-video-t...
2008/09/05
[ "https://Stackoverflow.com/questions/45803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4737/" ]
1. Video podcast 2. ??? 3. Audio only mp3 player I'm looking for somewhere which will extract audio from video, but instead of a single file, for an on going video podcast. I would most like a website which would suck in the RSS and spit out an RSS (I'm thinking of something like Feedburner), though would settle for something on my own machine. If it must be on my machine, it should be quick, transparent, and automatic when I download each episode. What would you use? **Edit:** I'm on an Ubuntu 8.04 machine; so running ffmpeg is no problem; however, I'm looking for automation and feed awareness. Here's my use case: I want to listen to [lectures](http://video.google.com/videosearch?q=google+techtalks&so=1&output=rss) at Google Video, or [Structure and Interpretation of Computer Programs](http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/). These videos come out fairly often, so anything that's needed to be done manually will also be done fairly often. Here's one approach I'd thought of: * download the RSS * parse the RSS for enclosures, * download the enclosures, keeping a track what has already been downloaded previously * transcode the files, but not the ones done already * reconstruct an RSS with the audio files, remembering to change the metadata. * schedule to be run periodically * point podcatcher at new RSS feed. I also liked the approach of gPodder of using a [post-download script](http://wiki.gpodder.org/wiki/Time_stretching#Using_the_post-download_script_hook). I wish the [Lazy Web](http://www.openp2p.com/pub/a/p2p/2003/01/07/lazyweb.html) still worked.
You could automate this using the open source command line tool ffmpeg. Parse the RSS to get the video files, fetch them over the net if needed, then spit each one out to a command line like this: ``` ffmpeg -i episode1.mov -ab 128000 episode1.mp3 ``` The -ab switch sets the output bit rate to 128 kbits/s on the audio file, adjust as needed. Once you have the audio files you can reconstruct the RSS feed to link to the audio files if so desired.
45,813
<p>Is there a way with WPF to get an array of elements under the mouse on a MouseMove event?</p>
[ { "answer_id": 45817, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 2, "selected": false, "text": "<p>Can you use the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.media.visualtreehelper.hittest.aspx\" rel=\"...
2008/09/05
[ "https://Stackoverflow.com/questions/45813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3291/" ]
Is there a way with WPF to get an array of elements under the mouse on a MouseMove event?
From "[WPF Unleashed](https://web.archive.org/web/20081205070201/http://adamnathan.net/wpf/)", page 383: > > Visual hit testing can inform you > about *all* `Visual`s that intersect a > location, [...] you must use [...] the > `[VisualTreeHelper.]HitTest` method that accepts a > `HitTestResultCallback` delegate. Before > this version of `HitTest` returns, the > delegate is invoked once for each > relevant `Visual`, starting from the > topmost and ending at the bottommost. > > > The signature of such a callback is ``` HitTestResultBehavior Callback(HitTestResult result) ``` and it has to return `HitTestResultBehaviour.Continue` to receive further hits, as shown below (from the linked page on MSDN): ``` // Return the result of the hit test to the callback. public HitTestResultBehavior MyHitTestResult(HitTestResult result) { // Add the hit test result to the list that will be processed after the enumeration. hitResultsList.Add(result.VisualHit); // Set the behavior to return visuals at all z-order levels. return HitTestResultBehavior.Continue; } ``` For further information, please consult the [MSDN documentation for `VisualTreeHelper.HitTest`](https://msdn.microsoft.com/en-us/library/ms608753(v=vs.110).aspx).
45,824
<p>I notice that StackOverflow has a views count for each question and that these view numbers are fairly low and accurate. </p> <p>I have a similar thing on one of my sites. It basically logs a "hit" whenever the page is loaded in the backend code. Unfortunately it also does this for search engine hits giving bloated and inaccurate numbers.</p> <p>I guess one way to not count a robot would be to do the view counting with an AJAX call once the page has loaded, but I'm sure there's other, better ways to ignore search engines in your hit counters whilst still letting them in to crawl your site. Do you know any?</p>
[ { "answer_id": 45825, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 0, "selected": false, "text": "<p>The reason Stack Overflow has accurate view counts is that it only count each view/user once.</p>\n\n<p>Third-party hit count...
2008/09/05
[ "https://Stackoverflow.com/questions/45824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3404/" ]
I notice that StackOverflow has a views count for each question and that these view numbers are fairly low and accurate. I have a similar thing on one of my sites. It basically logs a "hit" whenever the page is loaded in the backend code. Unfortunately it also does this for search engine hits giving bloated and inaccurate numbers. I guess one way to not count a robot would be to do the view counting with an AJAX call once the page has loaded, but I'm sure there's other, better ways to ignore search engines in your hit counters whilst still letting them in to crawl your site. Do you know any?
An AJAX call will do it, but usually search engines will not load images, javascript or CSS files, so it may be easier to include one of those files in the page, and pass the URL of the page you want to log a request against as a parameter in the file request. For example, in the page... <http://www.example.com/example.html> You might include in the head section ``` <link href="empty.css?log=example.html" rel="stylesheet" type="text/css" /> ``` And have your server side log the request, then return an empty css file. The same approach would apply to JavaScript or and image file, though in all cases you'll want to look carefully at what caching might take place. Another option would be to eliminate the search engines based on their [user agent](http://en.wikipedia.org/wiki/User_agent). There's a big list of possible user agents at <http://user-agents.org/> to get you started. Of course, you could go the other way, and only count requests from things you know are web browsers (covering IE, Firefox, Safari, Opera and this newfangled Chrome thing would get you 99% of the way there). Even easier would be to use a log analytics tool like [awstats](http://awstats.sourceforge.net/) or a service like [Google analytics](http://www.google.com/analytics/), both of which have already solved this problem.
45,827
<p>How do you automatically set the focus to a textbox when a web page loads?</p> <p>Is there an HTML tag to do it or does it have to be done via Javascript?</p>
[ { "answer_id": 45833, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 4, "selected": false, "text": "<p>You need to use javascript:</p>\n\n<pre><code>&lt;BODY onLoad=\"document.getElementById('myButton').focus();\"&gt;\n</code></...
2008/09/05
[ "https://Stackoverflow.com/questions/45827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
How do you automatically set the focus to a textbox when a web page loads? Is there an HTML tag to do it or does it have to be done via Javascript?
If you're using jquery: ``` $(function() { $("#Box1").focus(); }); ``` or prototype: ``` Event.observe(window, 'load', function() { $("Box1").focus(); }); ``` or plain javascript: ``` window.onload = function() { document.getElementById("Box1").focus(); }; ``` though keep in mind that this will replace other on load handlers, so look up addLoadEvent() in google for a safe way to append onload handlers rather than replacing.
45,861
<p>I am using <a href="http://code.google.com/p/js2-mode/" rel="noreferrer">js2-mode</a> to edit Javascript in Emacs, but I can't seem to get it to stop using tabs instead of spaces for indentation. My other modes work fine, just having issues w/ js2.</p>
[ { "answer_id": 46174, "author": "Peter S. Housel", "author_id": 949, "author_profile": "https://Stackoverflow.com/users/949", "pm_score": 6, "selected": true, "text": "<p>Do you have</p>\n\n<pre>\n(setq-default indent-tabs-mode nil)\n</pre>\n\n<p>in your .emacs? It works fine for me in e...
2008/09/05
[ "https://Stackoverflow.com/questions/45861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4748/" ]
I am using [js2-mode](http://code.google.com/p/js2-mode/) to edit Javascript in Emacs, but I can't seem to get it to stop using tabs instead of spaces for indentation. My other modes work fine, just having issues w/ js2.
Do you have ``` (setq-default indent-tabs-mode nil) ``` in your .emacs? It works fine for me in emacs 23.0.60.1 when I do that. js2-mode uses the standard emacs function indent-to, which respects indent-tabs-mode, to do its indenting.
45,888
<p>I have jQuery but I'm not sure if it has any built-in sorting helpers. I could make a 2d array of each item's <code>text</code>, <code>value</code>, and <code>selected</code> properties, but I don't think that javascript's built in <code>Array.sort()</code> would work correctly.</p>
[ { "answer_id": 45890, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 3, "selected": false, "text": "<p>Well, in IE6 it seems to sort on the nested array's [0] item:</p>\n\n<pre><code>function sortSelect(selectToSort) {\n va...
2008/09/05
[ "https://Stackoverflow.com/questions/45888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1414/" ]
I have jQuery but I'm not sure if it has any built-in sorting helpers. I could make a 2d array of each item's `text`, `value`, and `selected` properties, but I don't think that javascript's built in `Array.sort()` would work correctly.
Extract options into a temporary array, sort, then rebuild the list: ``` var my_options = $("#my_select option"); var selected = $("#my_select").val(); my_options.sort(function(a,b) { if (a.text > b.text) return 1; if (a.text < b.text) return -1; return 0 }) $("#my_select").empty().append( my_options ); $("#my_select").val(selected); ``` [Mozilla's sort documentation](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort "Mozilla's sort documentation") (specifically the compareFunction) and [Wikipedia's Sorting Algorithm page](http://en.wikipedia.org/wiki/Sorting_algorithm) are relevant. If you want to make the sort case insensitive, replace `text` with `text.toLowerCase()` The sort function shown above illustrates how to sort. Sorting non-english languages accurately can be complex (see the [unicode collation algorithm](http://www.unicode.org/reports/tr10/)). Using [localeCompare](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare) in the sort function is a good solution, eg: ``` my_options.sort(function(a,b) { return a.text.localeCompare(b.text); }); ```
45,898
<p>In an application that I'm writing I have some code like this:</p> <pre><code>NSWorkspace* ws = [NSWorkspace sharedWorkspace]; NSString* myurl = @"http://www.somewebsite.com/method?a=%d"; NSURL* url = [NSURL URLWithString:myurl]; [ws openURL:url]; </code></pre> <p>The main difference being that <em>myurl</em> comes from somewhere outside my control. Note the %d in the URL which isn't entirely correct and means that URLWithString fails, returning <em>nil</em>.</p> <p>What is the "correct" way of handling this? Do I need to parse the string and properly encode the arguments? Or is there some clever method in Cocoa that does all the hard work for me?</p>
[ { "answer_id": 45905, "author": "Matt Sheppard", "author_id": 797, "author_profile": "https://Stackoverflow.com/users/797", "pm_score": 2, "selected": false, "text": "<p>I think the behaviour here is correct, because %d is not a valid component of a URL (% is the escape, but expects two ...
2008/09/05
[ "https://Stackoverflow.com/questions/45898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2998/" ]
In an application that I'm writing I have some code like this: ``` NSWorkspace* ws = [NSWorkspace sharedWorkspace]; NSString* myurl = @"http://www.somewebsite.com/method?a=%d"; NSURL* url = [NSURL URLWithString:myurl]; [ws openURL:url]; ``` The main difference being that *myurl* comes from somewhere outside my control. Note the %d in the URL which isn't entirely correct and means that URLWithString fails, returning *nil*. What is the "correct" way of handling this? Do I need to parse the string and properly encode the arguments? Or is there some clever method in Cocoa that does all the hard work for me?
I'm not sure if this is exactly what you're looking for, but there is a method in NSString that will sanitize a URL: [stringByAddingPercentEscapesUsingEncoding:](https://developer.apple.com/documentation/foundation/nsstring/1415058-stringbyaddingpercentescapesusin)
45,904
<p><strong>Situation:</strong></p> <p>I have a simple <em>XML</em> document that contains image information. I need to transform it into <em>HTML</em>. However, I can't see where the open tag is and when I use the <em>XSL</em> code below, it shows the following error message: </p> <blockquote> <p>"Cannot write an attribute node when no element start tag is open."</p> </blockquote> <p><strong>XML content:</strong></p> <pre><code>&lt;root&gt; &lt;HeaderText&gt; &lt;HeaderText&gt;Dan Testing&lt;/HeaderText&gt; &lt;/HeaderText&gt; &lt;Image&gt; &lt;img width="100" height="100" alt="FPO lady" src="/uploadedImages/temp_photo_small.jpg"/&gt; &lt;/Image&gt; &lt;BodyText&gt; &lt;p&gt;This is a test of the body text&lt;br /&gt;&lt;/p&gt; &lt;/BodyText&gt; &lt;ShowLinkArrow&gt;false&lt;/ShowLinkArrow&gt; &lt;/root&gt; </code></pre> <p><strong>XSL code:</strong></p> <pre><code>&lt;xsl:stylesheet version="1.0" extension-element-prefixes="msxsl" exclude-result-prefixes="msxsl js dl" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:js="urn:custom-javascript" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:dl="urn:datalist"&gt; &lt;xsl:output method="xml" version="1.0" omit-xml-declaration="yes" indent="yes" encoding="utf-8"/&gt; &lt;xsl:template match="/" xml:space="preserve"&gt; &lt;img&gt; &lt;xsl:attribute name="width"&gt; 100 &lt;/xsl:attribute&gt; &lt;xsl:attribute name="height"&gt; 100 &lt;/xsl:attribute&gt; &lt;xsl:attribute name="class"&gt; CalloutRightPhoto &lt;/xsl:attribute&gt; &lt;xsl:attribute name="src"&gt; &lt;xsl:copy-of select="/root/Image/node()"/&gt; &lt;/xsl:attribute&gt; &lt;/img&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre>
[ { "answer_id": 45909, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 2, "selected": false, "text": "<p>Never mind -- I'm an idiot. I just needed <b>\n&lt;xsl:value-of select=\"/root/Image/node()\"/&gt;</b></p>\n" }, { ...
2008/09/05
[ "https://Stackoverflow.com/questions/45904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2757/" ]
**Situation:** I have a simple *XML* document that contains image information. I need to transform it into *HTML*. However, I can't see where the open tag is and when I use the *XSL* code below, it shows the following error message: > > "Cannot write an attribute node when no element start tag is open." > > > **XML content:** ``` <root> <HeaderText> <HeaderText>Dan Testing</HeaderText> </HeaderText> <Image> <img width="100" height="100" alt="FPO lady" src="/uploadedImages/temp_photo_small.jpg"/> </Image> <BodyText> <p>This is a test of the body text<br /></p> </BodyText> <ShowLinkArrow>false</ShowLinkArrow> </root> ``` **XSL code:** ``` <xsl:stylesheet version="1.0" extension-element-prefixes="msxsl" exclude-result-prefixes="msxsl js dl" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:js="urn:custom-javascript" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:dl="urn:datalist"> <xsl:output method="xml" version="1.0" omit-xml-declaration="yes" indent="yes" encoding="utf-8"/> <xsl:template match="/" xml:space="preserve"> <img> <xsl:attribute name="width"> 100 </xsl:attribute> <xsl:attribute name="height"> 100 </xsl:attribute> <xsl:attribute name="class"> CalloutRightPhoto </xsl:attribute> <xsl:attribute name="src"> <xsl:copy-of select="/root/Image/node()"/> </xsl:attribute> </img> </xsl:template> </xsl:stylesheet> ```
Just to clarify the problem here - the error is in the following bit of code: ``` <xsl:attribute name="src"> <xsl:copy-of select="/root/Image/node()"/> </xsl:attribute> ``` The instruction xsl:copy-of takes a node or node-set and makes a copy of it - outputting a node or node-set. However an attribute cannot contain a node, only a textual value, so xsl:value-of would be a possible solution (as this returns the textual value of a node or nodeset). A MUCH shorter solution (and perhaps more elegant) would be the following: ``` <img width="100" height="100" src="{/root/Image/node()}" class="CalloutRightPhoto"/> ``` The use of the {} in the attribute is called an Attribute Value Template, and can contain any XPATH expression. Note, the same XPath can be used here as you have used in the xsl\_copy-of as it knows to take the textual value when used in a Attribute Value Template.
45,908
<p>After answering on <a href="https://stackoverflow.com/questions/45650/common-files-in-visual-studio-solution#45664">this question</a> I thought it would be nice to collect some tips &amp; tricks for working with MSVS solutions and projects. </p> <p>Here is my list: </p> <ul> <li><p>How to avoid saving new projects automatically to reduce garbage in file system.</p> <p>Uncheck <strong>Tools->Options->Projects and Solutions->Save new projects when created</strong></p></li> <li><p>How to add common file to multiple projects without copying it to project’s directory.</p> <p>Right click on a project, select <strong>Add->Existing Item->Add as link</strong> (press on small arrow on Add button)</p></li> <li><p>How to add project to solution without including it in the build process</p> <p>Right click on solution, select <strong>Add->New solution folder</strong>.<br> Right click on created folder, <strong>select Add->Add existing project</strong></p></li> <li><p>How to edit project file from Visual Studio?</p> <p>Right click on project and select <strong>Unload Project</strong>, right click on unloaded project and select <strong>Edit</strong>. Or install <a href="http://code.msdn.microsoft.com/PowerCommands" rel="nofollow noreferrer">Power Commands</a> and select <strong>Edit Project File</strong></p></li> <li><p>How to group files in the project tree (like auto-generated files for WinForms controls)</p> <p>Open project file for editing. </p></li> </ul> <pre> Change</pre> <pre><code>&lt;Compile Include="MainFile.cs" /&gt; &lt;Compile Include="SecondaryFile.cs" /&gt; To &lt;Compile Include="SecondaryFile.cs "&gt; &lt;DependentUpon&gt; MainFile.cs &lt;/DependentUpon&gt; &lt;/Compile&gt; </code></pre> <p>Do you have anything else to add?</p>
[ { "answer_id": 45995, "author": "Craig", "author_id": 2894, "author_profile": "https://Stackoverflow.com/users/2894", "pm_score": 2, "selected": false, "text": "<p>I like changing the default location that new projects are saved to. </p>\n\n<p>Tools->Options (Select Projects and Solutio...
2008/09/05
[ "https://Stackoverflow.com/questions/45908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1196/" ]
After answering on [this question](https://stackoverflow.com/questions/45650/common-files-in-visual-studio-solution#45664) I thought it would be nice to collect some tips & tricks for working with MSVS solutions and projects. Here is my list: * How to avoid saving new projects automatically to reduce garbage in file system. Uncheck **Tools->Options->Projects and Solutions->Save new projects when created** * How to add common file to multiple projects without copying it to project’s directory. Right click on a project, select **Add->Existing Item->Add as link** (press on small arrow on Add button) * How to add project to solution without including it in the build process Right click on solution, select **Add->New solution folder**. Right click on created folder, **select Add->Add existing project** * How to edit project file from Visual Studio? Right click on project and select **Unload Project**, right click on unloaded project and select **Edit**. Or install [Power Commands](http://code.msdn.microsoft.com/PowerCommands) and select **Edit Project File** * How to group files in the project tree (like auto-generated files for WinForms controls) Open project file for editing. ``` Change ``` ``` <Compile Include="MainFile.cs" /> <Compile Include="SecondaryFile.cs" /> To <Compile Include="SecondaryFile.cs "> <DependentUpon> MainFile.cs </DependentUpon> </Compile> ``` Do you have anything else to add?
First rule of working with Visual Studio: * **Install [ReSharper](http://www.jetbrains.com/resharper/)**
45,924
<p>My users are having an intermittent error when using a Windows Forms application built in VB.NET 3.5. Apparently when they click on the form and the form re-paints, a red 'X' will be painted over the MenuStrip control and the app will crash with the following error. </p> <p>Has anyone seen this before? Can someone point me in the right direction? </p> <pre><code> System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index at System.Collections.ArrayList.get_Item(Int32 index) at System.Windows.Forms.ToolStripItemCollection.get_Item(Int32 index) at System.Windows.Forms.ToolStrip.OnPaint(PaintEventArgs e) at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs) at System.Windows.Forms.Control.WmPaint(Message&amp; m) at System.Windows.Forms.Control.WndProc(Message&amp; m) at System.Windows.Forms.ScrollableControl.WndProc(Message&amp; m) at System.Windows.Forms.ToolStrip.WndProc(Message&amp; m) at System.Windows.Forms.MenuStrip.WndProc(Message&amp; m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp; m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp; m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) </code></pre>
[ { "answer_id": 45995, "author": "Craig", "author_id": 2894, "author_profile": "https://Stackoverflow.com/users/2894", "pm_score": 2, "selected": false, "text": "<p>I like changing the default location that new projects are saved to. </p>\n\n<p>Tools->Options (Select Projects and Solutio...
2008/09/05
[ "https://Stackoverflow.com/questions/45924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4770/" ]
My users are having an intermittent error when using a Windows Forms application built in VB.NET 3.5. Apparently when they click on the form and the form re-paints, a red 'X' will be painted over the MenuStrip control and the app will crash with the following error. Has anyone seen this before? Can someone point me in the right direction? ``` System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index at System.Collections.ArrayList.get_Item(Int32 index) at System.Windows.Forms.ToolStripItemCollection.get_Item(Int32 index) at System.Windows.Forms.ToolStrip.OnPaint(PaintEventArgs e) at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs) at System.Windows.Forms.Control.WmPaint(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ScrollableControl.WndProc(Message& m) at System.Windows.Forms.ToolStrip.WndProc(Message& m) at System.Windows.Forms.MenuStrip.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) ```
First rule of working with Visual Studio: * **Install [ReSharper](http://www.jetbrains.com/resharper/)**
45,941
<p>I've used subversion for a while, and used the svnmerge.py script for a while in my old job to manage merges between branches. I believe Subversion 1.5 is now out, and was supposed to have some branch / merge management system integrated with it.</p> <p>So, can someone give me a quick overview of how to track merges in a branch with Subversion 1.5? Are there any pitfalls with using this support? Do I need to ensure all the team upgrades to 1.5 before using this support?</p>
[ { "answer_id": 45978, "author": "Chris Zwiryk", "author_id": 734, "author_profile": "https://Stackoverflow.com/users/734", "pm_score": 3, "selected": true, "text": "<h3>Usage</h3>\n\n<p>Merge tracking is managed by the client and stored in a property (<a href=\"http://subversion.tigris.o...
2008/09/05
[ "https://Stackoverflow.com/questions/45941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
I've used subversion for a while, and used the svnmerge.py script for a while in my old job to manage merges between branches. I believe Subversion 1.5 is now out, and was supposed to have some branch / merge management system integrated with it. So, can someone give me a quick overview of how to track merges in a branch with Subversion 1.5? Are there any pitfalls with using this support? Do I need to ensure all the team upgrades to 1.5 before using this support?
### Usage Merge tracking is managed by the client and stored in a property ([svn:mergeinfo](http://subversion.tigris.org/merge-tracking/design.html)). To use merge tracking you just merge as usual but without the revision range: ``` svn merge trunkURL ``` The client will take care of reading the properties to see what revision(s) need to be merged in and then update the properties with the newly-merged revision(s). [Here](http://blog.red-bean.com/sussman/?p=92) is a pretty basic overview of the process. ### Pitfalls, etc. I personally haven't run into any problems with merge tracking, but my usage of the feature has been pretty light. ### Upgrading There are two upgrades you'll need to do to get merge tracking: 1. Server: Your server **must** be running 1.5 to get merge tracking support. 2. Client: You can use a 1.x client against a 1.5 server, **but you won't get merge tracking.** Just upgrade everyone.
45,953
<p>I need to execute a directory copy upon a user action, but the directories are quite large, so I would like to be able to perform such an action without the user being aware of the time it takes for the copy to complete.</p> <p>Any suggestions would be much appreciated.</p>
[ { "answer_id": 45962, "author": "Matt Sheppard", "author_id": 797, "author_profile": "https://Stackoverflow.com/users/797", "pm_score": 2, "selected": false, "text": "<p>Can you arrange to fork off a separate process, and then run your copy in the background? It's been a while since I di...
2008/09/05
[ "https://Stackoverflow.com/questions/45953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1071/" ]
I need to execute a directory copy upon a user action, but the directories are quite large, so I would like to be able to perform such an action without the user being aware of the time it takes for the copy to complete. Any suggestions would be much appreciated.
Assuming this is running on a Linux machine, I've always handled it like this: ``` exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile)); ``` This launches the command `$cmd`, redirects the command output to `$outputfile`, and writes the process id to `$pidfile`. That lets you easily monitor what the process is doing and if it's still running. ``` function isRunning($pid){ try{ $result = shell_exec(sprintf("ps %d", $pid)); if( count(preg_split("/\n/", $result)) > 2){ return true; } }catch(Exception $e){} return false; } ```
45,964
<p>How do I multiply 10 to an <code>Integer</code> object and get back the <code>Integer</code> object?</p> <p>I am looking for the neatest way of doing this.</p> <p>I would probably do it this way: Get int from <code>Integer</code> object, multiply it with the other int and create another Integer object with this int value.</p> <p>Code will be something like ... </p> <pre><code>integerObj = new Integer(integerObj.intValue() * 10); </code></pre> <p>But, I saw a code where the author is doing it this way: Get the <code>String</code> from the <code>Integer</code> object, concatenate "0" at the end and then get <code>Integer</code> object back by using <code>Integer.parseInt</code></p> <p>The code is something like this:</p> <pre><code>String s = integerObj + "0"; integerObj = Integer.parseInt(s); </code></pre> <p>Is there any merit in doing it either way?</p> <p>And what would be the most efficient/neatest way in general and in this case?</p>
[ { "answer_id": 45973, "author": "Matt Sheppard", "author_id": 797, "author_profile": "https://Stackoverflow.com/users/797", "pm_score": 3, "selected": false, "text": "<p>The string approach is amusing, but almost certainly a bad way to do it.</p>\n\n<p>Getting the int value of an Integer...
2008/09/05
[ "https://Stackoverflow.com/questions/45964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4406/" ]
How do I multiply 10 to an `Integer` object and get back the `Integer` object? I am looking for the neatest way of doing this. I would probably do it this way: Get int from `Integer` object, multiply it with the other int and create another Integer object with this int value. Code will be something like ... ``` integerObj = new Integer(integerObj.intValue() * 10); ``` But, I saw a code where the author is doing it this way: Get the `String` from the `Integer` object, concatenate "0" at the end and then get `Integer` object back by using `Integer.parseInt` The code is something like this: ``` String s = integerObj + "0"; integerObj = Integer.parseInt(s); ``` Is there any merit in doing it either way? And what would be the most efficient/neatest way in general and in this case?
With Java 5's [autoboxing](http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html), you can simply do: ``` Integer a = new Integer(2); // or even just Integer a = 2; a *= 10; System.out.println(a); ```
45,988
<p>In a C# .NET 3.5 app (a mix of WinForms and WPF) I want to let the user select a folder to import a load of data from. At the moment, it's using <code>System.Windows.Forms.FolderBrowserDialog</code> but that's a bit lame. Mainly because you can't type the path into it (so you need to map a network drive, instead of typing a UNC path).</p> <p>I'd like something more like the <code>System.Windows.Forms.OpenFileDialog</code>, but for folders instead of files. </p> <p>What can I use instead? A WinForms or WPF solution is fine, but I'd prefer not to PInvoke into the Windows API if I can avoid it.</p>
[ { "answer_id": 45994, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 1, "selected": false, "text": "<p>Unfortunately there are no dialogs other than FolderBrowserDialog for folder selection. You need to create this dialog yoursel...
2008/09/05
[ "https://Stackoverflow.com/questions/45988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1367/" ]
In a C# .NET 3.5 app (a mix of WinForms and WPF) I want to let the user select a folder to import a load of data from. At the moment, it's using `System.Windows.Forms.FolderBrowserDialog` but that's a bit lame. Mainly because you can't type the path into it (so you need to map a network drive, instead of typing a UNC path). I'd like something more like the `System.Windows.Forms.OpenFileDialog`, but for folders instead of files. What can I use instead? A WinForms or WPF solution is fine, but I'd prefer not to PInvoke into the Windows API if I can avoid it.
Don't create it yourself! It's been done. You can use [FolderBrowserDialogEx](http://dotnetzip.codeplex.com/SourceControl/changeset/view/29832#432677) - a re-usable derivative of the built-in FolderBrowserDialog. This one allows you to type in a path, even a UNC path. You can also browse for computers or printers with it. Works just like the built-in FBD, but ... better. Full Source code. Free. MS-Public license. ![FolderBrowserDialogEx](https://i.stack.imgur.com/V1caf.png) Code to use it: ``` var dlg1 = new Ionic.Utils.FolderBrowserDialogEx(); dlg1.Description = "Select a folder to extract to:"; dlg1.ShowNewFolderButton = true; dlg1.ShowEditBox = true; //dlg1.NewStyle = false; dlg1.SelectedPath = txtExtractDirectory.Text; dlg1.ShowFullPathInEditBox = true; dlg1.RootFolder = System.Environment.SpecialFolder.MyComputer; // Show the FolderBrowserDialog. DialogResult result = dlg1.ShowDialog(); if (result == DialogResult.OK) { txtExtractDirectory.Text = dlg1.SelectedPath; } ```
45,991
<p>I'm building a website that requires very basic markup capabilities. I can't use any 3rd party plugins, so I just need a simple way to convert markup to HTML. I might have a total of 3 tags that I'll allow.</p> <p>What is the best way to convert <code>==Heading==</code> to <code>&lt;h2&gt;Heading&lt;/h2&gt;</code>, or <code>--bold--</code> to <code>&lt;b&gt;bold&lt;/b&gt;</code>? Can this be done simply with Regex, or does somebody have a simple function?</p> <p>I'm writing this in C#, but examples from other languages would probably work.</p>
[ { "answer_id": 45998, "author": "Matt Sheppard", "author_id": 797, "author_profile": "https://Stackoverflow.com/users/797", "pm_score": 3, "selected": true, "text": "<p>It's not really a simple problem, because if you're going to display things back to the user, you'll need to also sanit...
2008/09/05
[ "https://Stackoverflow.com/questions/45991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681/" ]
I'm building a website that requires very basic markup capabilities. I can't use any 3rd party plugins, so I just need a simple way to convert markup to HTML. I might have a total of 3 tags that I'll allow. What is the best way to convert `==Heading==` to `<h2>Heading</h2>`, or `--bold--` to `<b>bold</b>`? Can this be done simply with Regex, or does somebody have a simple function? I'm writing this in C#, but examples from other languages would probably work.
It's not really a simple problem, because if you're going to display things back to the user, you'll need to also sanitise the input to ensure you don't create any [cross site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting) vulnerabilities. That said, you could probably do something pretty simple as you describe most easily with a regular expression replacement. For example ``` replace the pattern ==([^=]*)== with <h2>\1</h2> ```
46,003
<p>How can I change default <a href="http://msdn.microsoft.com/en-us/library/3a7hkh29.aspx" rel="nofollow noreferrer">Generate Method Stub</a> behavior in Visaul Studio to generate method with body</p> <pre><code>throw new NotImplementedException(); </code></pre> <p>instead of </p> <pre><code>throw new Exception("The method or operation is not implemented."); </code></pre>
[ { "answer_id": 46016, "author": "Sam Wessel", "author_id": 4734, "author_profile": "https://Stackoverflow.com/users/4734", "pm_score": 4, "selected": true, "text": "<p>Taken from: <a href=\"http://blogs.msdn.com/ansonh/archive/2005/12/08/501763.aspx\" rel=\"noreferrer\">http://blogs.msdn...
2008/09/05
[ "https://Stackoverflow.com/questions/46003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2361/" ]
How can I change default [Generate Method Stub](http://msdn.microsoft.com/en-us/library/3a7hkh29.aspx) behavior in Visaul Studio to generate method with body ``` throw new NotImplementedException(); ``` instead of ``` throw new Exception("The method or operation is not implemented."); ```
Taken from: <http://blogs.msdn.com/ansonh/archive/2005/12/08/501763.aspx> > > Visual Studio 2005 supports targeting the 1.0 version of the compact framework. In order to keep the size of the compact framework small, it does not include all of the same types that exist in the desktop framework. One of the types that is not included is NotImplementedException. > > > You can change the generated code by editing the code snippet file: **C:\Program Files\Microsoft Visual Studio 8\VC#\Snippets\1033\Refactoring\MethodStub.snippet** and changing the Declarations section to the following: ``` <Declarations> <Literal Editable="true"> <ID>signature</ID> <Default>signature</Default> </Literal> <Literal> <ID>Exception</ID> <Function>SimpleTypeName(global::System.NotImplementedException)</Function> </Literal> </Declarations> ```
46,004
<p>We are trying to implement a REST API for an application we have now. We want to expose read/write capabilities for various resources using the REST API. How do we implement the "form" part of this? I get how to expose "read" of our data by creating RESTful URLs that essentially function as method calls and return the data:</p> <pre><code>GET /restapi/myobject?param=object-id-maybe </code></pre> <p>...and an XML document representing some data structure is returned. Fine.</p> <p>But, normally, in a web application, an "edit" would involve two requests: one to load the current version of the resources and populate the form with that data, and one to post the modified data back. </p> <p>But I don't get how you would do the same thing with HTTP methods that REST is sort of mapped to. It's a PUT, right? Can someone explain this?</p> <p>(Additional consideration: The UI would be primarily done with AJAX)</p> <p>-- Update: That definitely helps. But, I am still a bit confused about the server side? Obviously, I am not simply dealing with files here. On the server, the code that answers the requests should be filtering the request method to determine what to do with it? Is that the "switch" between reads and writes?</p>
[ { "answer_id": 46014, "author": "Matt Sheppard", "author_id": 797, "author_profile": "https://Stackoverflow.com/users/797", "pm_score": 0, "selected": false, "text": "<p>The load should just be a normal GET request, and the saving of new data should be a POST to the URL which currently h...
2008/09/05
[ "https://Stackoverflow.com/questions/46004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/577/" ]
We are trying to implement a REST API for an application we have now. We want to expose read/write capabilities for various resources using the REST API. How do we implement the "form" part of this? I get how to expose "read" of our data by creating RESTful URLs that essentially function as method calls and return the data: ``` GET /restapi/myobject?param=object-id-maybe ``` ...and an XML document representing some data structure is returned. Fine. But, normally, in a web application, an "edit" would involve two requests: one to load the current version of the resources and populate the form with that data, and one to post the modified data back. But I don't get how you would do the same thing with HTTP methods that REST is sort of mapped to. It's a PUT, right? Can someone explain this? (Additional consideration: The UI would be primarily done with AJAX) -- Update: That definitely helps. But, I am still a bit confused about the server side? Obviously, I am not simply dealing with files here. On the server, the code that answers the requests should be filtering the request method to determine what to do with it? Is that the "switch" between reads and writes?
If you're submitting the data via plain HTML, you're restricted to doing a POST based form. The URI that the POST request is sent to **should not** be the URI for the resource being modified. You should either POST to a collection resource that ADDs a newly created resource each time (with the URI for the new resource in the *Location* header and a **202** status code) or POST to an updater resource that updates a resource with a supplied URI in the request's content (or custom header). If you're using an XmlHttpRequest object, you can set the method to PUT and submit the data to the resource's URI. This can also work with empty forms if the server supplies a valid URI for the yet-nonexistent resource. The first PUT would create the resource (returning **202**). Subsequent PUTs will either do nothing if it's the same data or modify the existing resource (in either case a **200** is returned unless an error occurs).
46,029
<p>If I have a collection of database tables (in an Access file, for example) and need to validate each table in this collection against a rule set that has both common rules across all tables as well as individual rules specific to one or a subset of tables, can someone recommend a good design pattern to look into?</p> <p>Specifically, I would like to avoid code similar to:</p> <pre><code>void Main() { ValidateTable1(); ValidateTable2(); ValidateTable3(); } private void ValidateTable1() { //Table1 validation code goes here } private void ValidateTable2() { //Table2 validation code goes here } private void ValidateTable3() { //Table3 validation code goes here } </code></pre> <p>Also, I've decided to use log4net to log all of the errors and warnings, so that each method can be declared <code>void</code> and doesn't need to return anything. Is this a good idea or would it be better to create some sort of <code>ValidationException</code> that catches all exceptions and stores them in a <code>List&lt;ValidationException&gt;</code> before printing them all out at the end?</p> <p>I did find <a href="http://www.hickorysystems.com/sw_validation.html" rel="noreferrer">this</a>, which looks like it may work, but I'm hoping to actually find some code samples to work off of. Any suggestions? Has anyone done something similar in the past?</p> <p>For some background, the program will be written in either C# or VB.NET and the tables will more than likely be stored in either Access or SQL Server CE.</p>
[ { "answer_id": 46035, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 3, "selected": false, "text": "<p>I'd return some type of ValidationSummary for each one... or an IList depending on how you want to structure it.</p>...
2008/09/05
[ "https://Stackoverflow.com/questions/46029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1108/" ]
If I have a collection of database tables (in an Access file, for example) and need to validate each table in this collection against a rule set that has both common rules across all tables as well as individual rules specific to one or a subset of tables, can someone recommend a good design pattern to look into? Specifically, I would like to avoid code similar to: ``` void Main() { ValidateTable1(); ValidateTable2(); ValidateTable3(); } private void ValidateTable1() { //Table1 validation code goes here } private void ValidateTable2() { //Table2 validation code goes here } private void ValidateTable3() { //Table3 validation code goes here } ``` Also, I've decided to use log4net to log all of the errors and warnings, so that each method can be declared `void` and doesn't need to return anything. Is this a good idea or would it be better to create some sort of `ValidationException` that catches all exceptions and stores them in a `List<ValidationException>` before printing them all out at the end? I did find [this](http://www.hickorysystems.com/sw_validation.html), which looks like it may work, but I'm hoping to actually find some code samples to work off of. Any suggestions? Has anyone done something similar in the past? For some background, the program will be written in either C# or VB.NET and the tables will more than likely be stored in either Access or SQL Server CE.
Just an update on this: I decided to go with the [Decorator pattern](http://en.wikipedia.org/wiki/Decorator_pattern). That is, I have one 'generic' table class that implements an `IValidateableTable` interface (which contains `validate()` method). Then, I created several validation decorators (that also `implement IValidateableTable`) which I can wrap around each table that I'm trying to validate. So, the code ends up looking like this: ``` IValidateableTable table1 = new GenericTable(myDataSet); table1 = new NonNullNonEmptyColumnValidator(table1, "ColumnA"); table1 = new ColumnValueValidator(table1, "ColumnB", "ExpectedValue"); ``` Then, all I need to do is call `table1.Validate()` which unwinds through the decorators calling all of the needed validations. So far, it seems to work really well, though I am still open to suggestions.
46,030
<p>So, I did search google and SO prior to asking this question. Basically I have a DLL that has a form compiled into it. The form will be used to display information to the screen. Eventually it will be asynchronous and expose a lot of customization in the dll. For now I just want it to display properly. The problem that I am having is that I use the dll by loading it in a Powershell session. So when I try to display the form and get it to come to the top and have focus, It has no problem with displaying over all the other apps, but I can't for the life of me get it to display over the Powershell window. Here is the code that I am currently using to try and get it to display. I am sure that the majority of it won't be required once I figure it out, this just represents all the things that I found via google.</p> <pre><code>CLass Blah { [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")] public static extern bool SystemParametersInfo(uint uiAction, uint uiParam, uint pvParam, uint fWinIni); [DllImport("user32.dll", EntryPoint = "SetForegroundWindow")] public static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("User32.dll", EntryPoint = "ShowWindowAsync")] private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow); private const int WS_SHOWNORMAL = 1; public void ShowMessage(string msg) { MessageForm msgFrm = new MessageForm(); msgFrm.lblMessage.Text = "FOO"; msgFrm.ShowDialog(); msgFrm.BringToFront(); msgFrm.TopMost = true; msgFrm.Activate(); SystemParametersInfo((uint)0x2001, 0, 0, 0x0002 | 0x0001); ShowWindowAsync(msgFrm.Handle, WS_SHOWNORMAL); SetForegroundWindow(msgFrm.Handle); SystemParametersInfo((uint)0x2001, 200000, 200000, 0x0002 | 0x0001); } } </code></pre> <p>As I say I'm sure that most of that is either not needed or even flat out wrong, I just wanted to show the things that I had tried. Also, as I mentioned, I plan to have this be asynchronously displayed at some point which I suspect will wind up requiring a separate thread. Would splitting the form out into it's own thread make it easier to cause it to get focus over the Powershell session? </p> <hr> <p>@Joel, thanks for the info. Here is what I tried based on your suggestion:</p> <pre><code>msgFrm.ShowDialog(); msgFrm.BringToFront(); msgFrm.Focus(); Application.DoEvents(); </code></pre> <p>The form still comes up <em>under</em> the Powershell session. I'll proceed with working out the threading. I've spawned threads before but never where the parent thread needed to talk to the child thread, so we'll see how it goes.</p> <p>Thnks for all the ideas so far folks.</p> <hr> <p>Ok, threading it took care of the problem. @Quarrelsome, I did try both of those. Neither (nor both together) worked. I am curious as to what is evil about using threading? I am not using Application.Run and I have yet to have a problem. I am using a mediator class that both the parent thread and the child thread have access to. In that object I am using a ReaderWriterLock to lock one property that represents the message that I want displayed on the form that the child thread creates. The parent locks the property then writes what should be displayed. The child thread locks the property and reads what it should change the label on the form to. The child has to do this on a polling interval (I default it to 500ms) which I'm not real happy about, but I could not find an event driven way to let the child thread know that the proerty had changed, so I'm stuck with polling.</p>
[ { "answer_id": 46092, "author": "Dean Hill", "author_id": 3106, "author_profile": "https://Stackoverflow.com/users/3106", "pm_score": 5, "selected": true, "text": "<p>I also had trouble activating and bringing a window to the foreground. Here is the code that eventually worked for me. I'...
2008/09/05
[ "https://Stackoverflow.com/questions/46030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1358/" ]
So, I did search google and SO prior to asking this question. Basically I have a DLL that has a form compiled into it. The form will be used to display information to the screen. Eventually it will be asynchronous and expose a lot of customization in the dll. For now I just want it to display properly. The problem that I am having is that I use the dll by loading it in a Powershell session. So when I try to display the form and get it to come to the top and have focus, It has no problem with displaying over all the other apps, but I can't for the life of me get it to display over the Powershell window. Here is the code that I am currently using to try and get it to display. I am sure that the majority of it won't be required once I figure it out, this just represents all the things that I found via google. ``` CLass Blah { [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")] public static extern bool SystemParametersInfo(uint uiAction, uint uiParam, uint pvParam, uint fWinIni); [DllImport("user32.dll", EntryPoint = "SetForegroundWindow")] public static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("User32.dll", EntryPoint = "ShowWindowAsync")] private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow); private const int WS_SHOWNORMAL = 1; public void ShowMessage(string msg) { MessageForm msgFrm = new MessageForm(); msgFrm.lblMessage.Text = "FOO"; msgFrm.ShowDialog(); msgFrm.BringToFront(); msgFrm.TopMost = true; msgFrm.Activate(); SystemParametersInfo((uint)0x2001, 0, 0, 0x0002 | 0x0001); ShowWindowAsync(msgFrm.Handle, WS_SHOWNORMAL); SetForegroundWindow(msgFrm.Handle); SystemParametersInfo((uint)0x2001, 200000, 200000, 0x0002 | 0x0001); } } ``` As I say I'm sure that most of that is either not needed or even flat out wrong, I just wanted to show the things that I had tried. Also, as I mentioned, I plan to have this be asynchronously displayed at some point which I suspect will wind up requiring a separate thread. Would splitting the form out into it's own thread make it easier to cause it to get focus over the Powershell session? --- @Joel, thanks for the info. Here is what I tried based on your suggestion: ``` msgFrm.ShowDialog(); msgFrm.BringToFront(); msgFrm.Focus(); Application.DoEvents(); ``` The form still comes up *under* the Powershell session. I'll proceed with working out the threading. I've spawned threads before but never where the parent thread needed to talk to the child thread, so we'll see how it goes. Thnks for all the ideas so far folks. --- Ok, threading it took care of the problem. @Quarrelsome, I did try both of those. Neither (nor both together) worked. I am curious as to what is evil about using threading? I am not using Application.Run and I have yet to have a problem. I am using a mediator class that both the parent thread and the child thread have access to. In that object I am using a ReaderWriterLock to lock one property that represents the message that I want displayed on the form that the child thread creates. The parent locks the property then writes what should be displayed. The child thread locks the property and reads what it should change the label on the form to. The child has to do this on a polling interval (I default it to 500ms) which I'm not real happy about, but I could not find an event driven way to let the child thread know that the proerty had changed, so I'm stuck with polling.
I also had trouble activating and bringing a window to the foreground. Here is the code that eventually worked for me. I'm not sure if it will solve your problem. Basically, call ShowWindow() then SetForegroundWindow(). ``` using System.Diagnostics; using System.Runtime.InteropServices; // Sets the window to be foreground [DllImport("User32")] private static extern int SetForegroundWindow(IntPtr hwnd); // Activate or minimize a window [DllImportAttribute("User32.DLL")] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); private const int SW_SHOW = 5; private const int SW_MINIMIZE = 6; private const int SW_RESTORE = 9; private void ActivateApplication(string briefAppName) { Process[] procList = Process.GetProcessesByName(briefAppName); if (procList.Length > 0) { ShowWindow(procList[0].MainWindowHandle, SW_RESTORE); SetForegroundWindow(procList[0].MainWindowHandle); } } ```
46,034
<p>My work has a financial application, written in <code>VB.NET</code> with <code>SQL</code>, that several users can be working on at the same time.</p> <p>At some point, one user might decide to Post the batch of entries that they (and possibly other people) are currently working on.</p> <p>Obviously, I no longer want any other users to <strong>add</strong>, <strong>edit</strong>, or <strong>delete</strong> entries in that batch <strong>after</strong> the <strong>Post process</strong> has been initiated.</p> <p>I have already seen that I can lock <strong>all</strong> data by opening the SQL transaction the moment the Post process starts, but the process can be fairly lengthy and I would prefer not to have the Transaction open for the several minutes it might take to complete the function.</p> <p>Is there a way to lock just the records that I know need to be operated on from VB.NET code?</p>
[ { "answer_id": 46054, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 0, "selected": false, "text": "<p>add </p>\n\n<pre><code>with (rowlock)\n</code></pre>\n\n<p>to your SQL query</p>\n\n<p><a href=\"http://www.sql-server-perfo...
2008/09/05
[ "https://Stackoverflow.com/questions/46034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
My work has a financial application, written in `VB.NET` with `SQL`, that several users can be working on at the same time. At some point, one user might decide to Post the batch of entries that they (and possibly other people) are currently working on. Obviously, I no longer want any other users to **add**, **edit**, or **delete** entries in that batch **after** the **Post process** has been initiated. I have already seen that I can lock **all** data by opening the SQL transaction the moment the Post process starts, but the process can be fairly lengthy and I would prefer not to have the Transaction open for the several minutes it might take to complete the function. Is there a way to lock just the records that I know need to be operated on from VB.NET code?
If you are using Oracle you would **Select for update** on the rows you are locking. here is an example ``` SELECT address1 , city, country FROM location FOR UPDATE; ```
46,079
<p>Details:</p> <ul> <li>Only disable after user clicks the submit button, but before the posting back to the server</li> <li>ASP.NET Webforms (.NET 1.1)</li> <li>Prefer jQuery (if any library at all)</li> <li>Must be enabled if form reloads (i.e. credit card failed)</li> </ul> <p>This isn't a necessity that I do this, but if there is a simple way to do it without having to change too much, I'll do it. (i.e. if there isn't a simple solution, I probably won't do it, so don't worry about digging too deep)</p>
[ { "answer_id": 46082, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 1, "selected": false, "text": "<p>in JQuery:</p>\n\n<pre><code>$('#SubmitButtonID').click(function() { this.disabled = true; });\n</code></pre>\n" }, { ...
2008/09/05
[ "https://Stackoverflow.com/questions/46079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1446/" ]
Details: * Only disable after user clicks the submit button, but before the posting back to the server * ASP.NET Webforms (.NET 1.1) * Prefer jQuery (if any library at all) * Must be enabled if form reloads (i.e. credit card failed) This isn't a necessity that I do this, but if there is a simple way to do it without having to change too much, I'll do it. (i.e. if there isn't a simple solution, I probably won't do it, so don't worry about digging too deep)
For all submit buttons, via JQuery, it'd be: ``` $('input[type=submit]').click(function() { this.disabled = true; }); ``` Or it might be more useful to do so on form submission: ``` $('form').submit(function() { $('input[type=submit]', this).attr("disabled","disabled"); }); ``` But I think we could give a better answer to your question if we knew a bit more about the context. If this is an ajax request, then you'll need to make sure you enable submit buttons again on either success or failure. If this is a standard HTTP form submission (aside from disabling the button with javascript) and you're doing this to safe guard from multiple submissions of the same form, then you ought to have some sort of control in the code that deals with the submitted data, because disabling a button with javascript might not prevent multiple submissions.
46,080
<p>I'm using TortoiseSVN against the SourceForge SVN repository. I'd like to move a file from one folder to another in order to maintain its revision history. Is this possible? If so, how do you do it?</p> <p>(My current strategy has been to copy the file into the new folder and check it in and then delete the file from the current folder.)</p>
[ { "answer_id": 46083, "author": "Commodore Jaeger", "author_id": 4659, "author_profile": "https://Stackoverflow.com/users/4659", "pm_score": 8, "selected": true, "text": "<p>Subversion has native support for moving files.</p>\n\n<pre><code>svn move SOURCE DESTINATION\n</code></pre>\n\n<p...
2008/09/05
[ "https://Stackoverflow.com/questions/46080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
I'm using TortoiseSVN against the SourceForge SVN repository. I'd like to move a file from one folder to another in order to maintain its revision history. Is this possible? If so, how do you do it? (My current strategy has been to copy the file into the new folder and check it in and then delete the file from the current folder.)
Subversion has native support for moving files. ``` svn move SOURCE DESTINATION ``` See the online help (svn help move) for more information.
46,096
<p>I'm trying to find the correct names for these 2 "types" of coding expressions in LINQ so that I can refer to them correctly. I want to say that the first is called "Fluent Style"?</p> <pre><code>var selectVar = arrayVar.Select( (a,i) =&gt; new { Line = a }); var selectVar = from s in arrayVar select new { Line = s }; </code></pre>
[ { "answer_id": 46104, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 3, "selected": true, "text": "<ul>\n<li>First - calling an extension method. \nThis style of coding is called \"<a href=\"http://www.martinfowler.com/bliki/Flue...
2008/09/05
[ "https://Stackoverflow.com/questions/46096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
I'm trying to find the correct names for these 2 "types" of coding expressions in LINQ so that I can refer to them correctly. I want to say that the first is called "Fluent Style"? ``` var selectVar = arrayVar.Select( (a,i) => new { Line = a }); var selectVar = from s in arrayVar select new { Line = s }; ```
* First - calling an extension method. This style of coding is called "[fluent interface](http://www.martinfowler.com/bliki/FluentInterface.html)" as you mentioned. * Second method is called [language integrated query](http://en.wikipedia.org/wiki/Language_Integrated_Query)
46,124
<p>I've seen people doing things like this in their HTML:</p> <pre><code>&lt;!--[if IE]&gt; &lt;link rel="stylesheet" href="ie.css" type="text/css" /&gt; &lt;![endif]--&gt; </code></pre> <p>Does this work across all modern browsers and is there a list of browser types that will work with that kind of if statement?</p> <p><strong>Edit</strong></p> <p>Thanks <a href="https://stackoverflow.com/questions/46124/is-there-a-list-of-browser-conditionals-for-use-including-stylesheets#46126">Ross</a>. Interesting to find out about <strong>gt, lt, gte, &amp; lte</strong>.</p>
[ { "answer_id": 46126, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 5, "selected": true, "text": "<p>This works across all browsers because anything except IE sees <code>&lt;!--IGNORED COMMENT--&gt;</code>. Only IE reads the co...
2008/09/05
[ "https://Stackoverflow.com/questions/46124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
I've seen people doing things like this in their HTML: ``` <!--[if IE]> <link rel="stylesheet" href="ie.css" type="text/css" /> <![endif]--> ``` Does this work across all modern browsers and is there a list of browser types that will work with that kind of if statement? **Edit** Thanks [Ross](https://stackoverflow.com/questions/46124/is-there-a-list-of-browser-conditionals-for-use-including-stylesheets#46126). Interesting to find out about **gt, lt, gte, & lte**.
This works across all browsers because anything except IE sees `<!--IGNORED COMMENT-->`. Only IE reads the comment if it contains a conditional clause. Have a look at [this article](http://www.quirksmode.org/css/condcom.html) You can also specify which version of IE. For example: ``` <!--[if IE 8]> <link rel="stylesheet type="text/css" href="ie8.css" /> <![endif]--> ```
46,125
<p>I want to do this: </p> <blockquote> <p>//*fu</p> </blockquote> <p>which returns all nodes whose name ends in <strong>fu</strong>, such as <code>&lt;tarfu /&gt;</code> and <code>&lt;snafu /&gt;</code>, but not <code>&lt;fubar /&gt;</code></p>
[ { "answer_id": 46141, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 6, "selected": true, "text": "<p>Do something like:</p>\n\n<pre><code>//*[ends-with(name(), 'fu')]\n</code></pre>\n\n<p>For a good XPath reference, ...
2008/09/05
[ "https://Stackoverflow.com/questions/46125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want to do this: > > //\*fu > > > which returns all nodes whose name ends in **fu**, such as `<tarfu />` and `<snafu />`, but not `<fubar />`
Do something like: ``` //*[ends-with(name(), 'fu')] ``` For a good XPath reference, check out [W3Schools](http://www.w3schools.com/xml/xsl_functions.asp).
46,130
<p>I have a list of <code>Foo</code>. Foo has properties <code>Bar</code> and <code>Lum</code>. Some <code>Foo</code>s have identical values for <code>Bar</code>. How can I use lambda/linq to group my <code>Foo</code>s by <code>Bar</code> so I can iterate over each grouping's <code>Lum</code>s?</p>
[ { "answer_id": 46142, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<pre><code>var q = from x in list\n group x by x.Bar into g\n select g;\n\nforeach (var group in q)\n{\n Console...
2008/09/05
[ "https://Stackoverflow.com/questions/46130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946/" ]
I have a list of `Foo`. Foo has properties `Bar` and `Lum`. Some `Foo`s have identical values for `Bar`. How can I use lambda/linq to group my `Foo`s by `Bar` so I can iterate over each grouping's `Lum`s?
[Deeno](https://stackoverflow.com/questions/46130/how-do-i-group-in-memory-lists#46317), Enjoy: ``` var foos = new List<Foo> { new Foo{Bar = 1,Lum = 1}, new Foo{Bar = 1,Lum = 2}, new Foo{Bar = 2,Lum = 3}, }; // Using language integrated queries: var q = from foo in foos group foo by foo.Bar into groupedFoos let lums = from fooGroup in groupedFoos select fooGroup.Lum select new { Bar = groupedFoos.Key, Lums = lums }; // Using lambdas var q = foos.GroupBy(x => x.Bar). Select(y => new {Bar = y.Key, Lums = y.Select(z => z.Lum)}); foreach (var group in q) { Console.WriteLine("Lums for Bar#" + group.Bar); foreach (var lum in group.Lums) { Console.WriteLine(lum); } } ``` To learn more about LINQ read [101 LINQ Samples](http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx)
46,136
<p>I have a large codebase that targetted Flash 7, with a <em>lot</em> of AS2 classes. I'm hoping that I'll be able to use Flex for any new projects, but a lot of new stuff in our roadmap is additions to the old code.</p> <p>The syntax for AS2 and AS3 is generally the same, so I'm starting to wonder how hard it would be to port the current codebase to Flex/AS3. I know all the UI-related stuff would be iffy (currently the UI is generated at runtime with a lot of createEmptyMovieClip() and attachMovie() stuff), but the UI and controller/model stuff is mostly separated.</p> <p>Has anyone tried porting a large codebase of AS2 code to AS3? How difficult is it? What kinds of pitfalls did you run into? Any recommendations for approaches to doing this kind of project?</p>
[ { "answer_id": 46184, "author": "lilserf", "author_id": 4545, "author_profile": "https://Stackoverflow.com/users/4545", "pm_score": 4, "selected": true, "text": "<p>Some notable problems I saw when attempting to convert a large number of AS2 classes to AS3:</p>\n\n<h3>Package naming</h3>...
2008/09/05
[ "https://Stackoverflow.com/questions/46136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1409/" ]
I have a large codebase that targetted Flash 7, with a *lot* of AS2 classes. I'm hoping that I'll be able to use Flex for any new projects, but a lot of new stuff in our roadmap is additions to the old code. The syntax for AS2 and AS3 is generally the same, so I'm starting to wonder how hard it would be to port the current codebase to Flex/AS3. I know all the UI-related stuff would be iffy (currently the UI is generated at runtime with a lot of createEmptyMovieClip() and attachMovie() stuff), but the UI and controller/model stuff is mostly separated. Has anyone tried porting a large codebase of AS2 code to AS3? How difficult is it? What kinds of pitfalls did you run into? Any recommendations for approaches to doing this kind of project?
Some notable problems I saw when attempting to convert a large number of AS2 classes to AS3: ### Package naming ``` class your.package.YourClass { } ``` becomes ``` package your.package { class YourClass { } } ``` ### Imports are required You must explicitly import any outside classes used -- referring to them by their fully qualified name is no longer enough. ### Interface methods can't be labelled 'public' This makes total sense, but AS2 will let you do it so if you have any they'll need to be removed. ### Explicit 'override' keyword Any functions that override a parent class function must be declared with the *override* keyword, much like C#. Along the same lines, if you have interfaces that extend other interfaces and redeclare functions, those overrides must be removed (again, as with *public,* this notation didn't make sense anyway but AS2 let you do it). ### All the Flash builtin stuff changed You alluded to this above, but it's now *flash.display.MovieClip* instead of just *MovieClip,* for example. There are a lot of specifics in this category, and I didn't get far enough to find them all, but there's going to be a lot of annoyance here. ### Conclusion I didn't get to work on this conversion to the point of success, but I was able in a matter of hours to write a quick C# tool that handled every aspect of this except the *override* keyword. Automating the imports can be tricky -- in my case the packages we use all start with a few root-level packages so they're easy to detect.
46,146
<p>Looking for a string to pass to String#matches(String) that will match IPv4, and another to match IPv6.</p>
[ { "answer_id": 46168, "author": "Kevin Wong", "author_id": 4792, "author_profile": "https://Stackoverflow.com/users/4792", "pm_score": 4, "selected": false, "text": "<pre><code>public static final String IPV4_REGEX = \"\\\\A(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)(\\\\.(25[0-5]|2[0-4]\\\\...
2008/09/05
[ "https://Stackoverflow.com/questions/46146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4792/" ]
Looking for a string to pass to String#matches(String) that will match IPv4, and another to match IPv6.
``` public static final String IPV4_REGEX = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z"; public static final String IPV6_HEX4DECCOMPRESSED_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::((?:[0-9A-Fa-f]{1,4}:)*)(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z"; public static final String IPV6_6HEX4DEC_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}:){6,6})(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z"; public static final String IPV6_HEXCOMPRESSED_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)\\z"; public static final String IPV6_REGEX = "\\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\z"; ``` Got these from some blog. Someone good w/ regexes should be able to come up with a single regex for all IPv6 address types. Actually, I guess you could have a single regex that matches both IPv4 and IPv6.
46,155
<p>I'd like to check if the user input is an email address in JavaScript, before sending it to a server or attempting to send an email to it, to prevent the most basic mistyping. How could I achieve this?</p>
[ { "answer_id": 46170, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 7, "selected": false, "text": "<p>JavaScript can match a regular expression:</p>\n<pre><code>emailAddress.match( / some_regex /);\n</code></pre>\n<p>H...
2008/09/05
[ "https://Stackoverflow.com/questions/46155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72/" ]
I'd like to check if the user input is an email address in JavaScript, before sending it to a server or attempting to send an email to it, to prevent the most basic mistyping. How could I achieve this?
Using [regular expressions](http://en.wikipedia.org/wiki/Regular_expression) is probably the best way. You can see a bunch of tests [here](http://jsfiddle.net/ghvj4gy9/embedded/result,js/) (taken from [chromium](https://cs.chromium.org/chromium/src/third_party/blink/web_tests/fast/forms/resources/ValidityState-typeMismatch-email.js?q=ValidityState-typeMismatch-email.js&sq=package:chromium&dr)) ```js const validateEmail = (email) => { return String(email) .toLowerCase() .match( /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ ); }; ``` Here's the example of a regular expression that accepts unicode: ```js const re = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i; ``` But keep in mind that one should not rely only upon JavaScript validation. JavaScript can easily be disabled. This should be validated on the server side as well. Here's an example of the above in action: ```js const validateEmail = (email) => { return email.match( /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ ); }; const validate = () => { const $result = $('#result'); const email = $('#email').val(); $result.text(''); if (validateEmail(email)) { $result.text(email + ' is valid :)'); $result.css('color', 'green'); } else { $result.text(email + ' is not valid :('); $result.css('color', 'red'); } return false; } $('#email').on('input', validate); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label for="email">Enter an email address: </label> <input id="email" /> <h2 id="result"></h2> ```
46,189
<p>I have a collection of objects to which I'd like to just add a new property. How do I do that with LINQ?</p>
[ { "answer_id": 46206, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 3, "selected": true, "text": "<pre><code>var a = from i in ObjectCollection select new {i.prop1, i.prop2, i.prop3, ..., newprop = newProperty}\n</code></...
2008/09/05
[ "https://Stackoverflow.com/questions/46189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ]
I have a collection of objects to which I'd like to just add a new property. How do I do that with LINQ?
``` var a = from i in ObjectCollection select new {i.prop1, i.prop2, i.prop3, ..., newprop = newProperty} ```
46,219
<p>If I have a </p> <pre><code>&lt;input id="uploadFile" type="file" /&gt; </code></pre> <p>tag, and a submit button, how do I determine, in IE6 (and above) if a file has been selected by the user.</p> <p>In FF, I just do:</p> <pre><code>var selected = document.getElementById("uploadBox").files.length &gt; 0; </code></pre> <p>But that doesn't work in IE.</p>
[ { "answer_id": 46242, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 8, "selected": true, "text": "<p>This works in IE (and FF, I believe):</p>\n\n<pre><code>if(document.getElementById(\"uploadBox\").value != \"\") {\n ...
2008/09/05
[ "https://Stackoverflow.com/questions/46219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/698/" ]
If I have a ``` <input id="uploadFile" type="file" /> ``` tag, and a submit button, how do I determine, in IE6 (and above) if a file has been selected by the user. In FF, I just do: ``` var selected = document.getElementById("uploadBox").files.length > 0; ``` But that doesn't work in IE.
This works in IE (and FF, I believe): ``` if(document.getElementById("uploadBox").value != "") { // you have a file } ```
46,220
<p>I'm writing my first iPhone app, so I haven't gotten around to figuring out much in the way of debugging. Essentially my app displays an image and when touched plays a short sound. When compiling and building the project in XCode, everything builds successfully, but when the app is run in the iPhone simulator, it crashes.</p> <p>I get the following error:</p> <pre><code>Application Specific Information: iPhone Simulator 1.0 (70), iPhone OS 2.0 (5A331) *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[&lt;UIView 0x34efd0&gt; setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key kramerImage.' </code></pre> <p>kramerImage here is the image I'm using for the background.</p> <p>I'm not sure what NSUnknownKeyException means or why the class is not key value coding-compliant for the key.</p>
[ { "answer_id": 46357, "author": "amrox", "author_id": 4468, "author_profile": "https://Stackoverflow.com/users/4468", "pm_score": 6, "selected": true, "text": "<p>(This isn't really iPhone specific - the same thing will happen in regular Cocoa).</p>\n\n<p>NSUnknownKeyException is a commo...
2008/09/05
[ "https://Stackoverflow.com/questions/46220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2293/" ]
I'm writing my first iPhone app, so I haven't gotten around to figuring out much in the way of debugging. Essentially my app displays an image and when touched plays a short sound. When compiling and building the project in XCode, everything builds successfully, but when the app is run in the iPhone simulator, it crashes. I get the following error: ``` Application Specific Information: iPhone Simulator 1.0 (70), iPhone OS 2.0 (5A331) *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIView 0x34efd0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key kramerImage.' ``` kramerImage here is the image I'm using for the background. I'm not sure what NSUnknownKeyException means or why the class is not key value coding-compliant for the key.
(This isn't really iPhone specific - the same thing will happen in regular Cocoa). NSUnknownKeyException is a common error when using [Key-Value Coding](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueCoding/Articles/KeyValueCoding.html) to access a key that the object doesn't have. The properties of most Cocoa objects can be accessing directly: ``` [@"hello world" length] // Objective-C 1.0 @"hello world".length // Objective-C 2.0 ``` Or via Key-Value Coding: ``` [@"hello world" valueForKey:@"length"] ``` I would get an NSUnknownKeyException if I used the following line: ``` [@"hello world" valueForKey:@"purpleMonkeyDishwasher"] ``` because NSString does not have a property (key) called 'purpleMonkeyDishwasher'. Something in your code is trying to set a value for the key 'kramerImage' on an UIView, which (apparently) doesn't support that key. If you're using Interface Builder, it might be something in your nib. Find where 'kramerImage' is being used, and try to track it down from there.
46,282
<p>I am using a class library which represents some of its configuration in .xml. The configuration is read in using the <code>XmlSerializer</code>. Fortunately, the classes which represent the .xml use the <code>XmlAnyElement</code> attribute at which allows me to extend the configuration data for my own purposes without modifying the original class library.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;Config&gt; &lt;data&gt;This is some data&lt;/data&gt; &lt;MyConfig&gt; &lt;data&gt;This is my data&lt;/data&gt; &lt;/MyConfig&gt; &lt;/Config&gt; </code></pre> <p>This works well for deserialization. I am able to allow the class library to deserialize the .xml as normal and the I can use my own <code>XmlSerializer</code> instances with a <code>XmlNodeReader</code> against the internal <code>XmlNode</code>.</p> <pre><code>public class Config { [XmlElement] public string data; [XmlAnyElement] public XmlNode element; } public class MyConfig { [XmlElement] public string data; } class Program { static void Main(string[] args) { using (Stream fs = new FileStream(@"c:\temp\xmltest.xml", FileMode.Open)) { XmlSerializer xser1 = new XmlSerializer(typeof(Config)); Config config = (Config)xser1.Deserialize(fs); if (config.element != null) { XmlSerializer xser2 = new XmlSerializer(typeof(MyConfig)); MyConfig myConfig = (MyConfig)xser2.Deserialize(new XmlNodeReader(config.element)); } } } </code></pre> <p>I need to create a utility which will allow the user to generate a new configuration file that includes both the class library configuration as well my own configuration, so new objects will be created which were not read from the .xml file. The question is how can I serialize the data back into .xml? </p> <p>I realize that I have to initially call <code>XmlSerializer.Serialize</code> on my data before calling the same method on the class library configuration. However, this requires that my data is represented by an <code>XmlNode</code> after calling <code>Serialize</code>. What is the best way to serialize an object into an <code>XmlNode</code> using the <code>XmlSerializer</code>?</p> <p>Thanks,</p> <p>-kevin</p> <p>btw-- It looks like an <code>XmlNodeWriter</code> class written by Chris Lovett was available at one time from Microsoft, but the links are now broken. Does anyone know of an alternative location to get this class?</p>
[ { "answer_id": 46378, "author": "Ed Schwehm", "author_id": 1206, "author_profile": "https://Stackoverflow.com/users/1206", "pm_score": 5, "selected": true, "text": "<p>So you need to have your class contain custom configuration information, then serialize that class to XML, then make tha...
2008/09/05
[ "https://Stackoverflow.com/questions/46282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4599/" ]
I am using a class library which represents some of its configuration in .xml. The configuration is read in using the `XmlSerializer`. Fortunately, the classes which represent the .xml use the `XmlAnyElement` attribute at which allows me to extend the configuration data for my own purposes without modifying the original class library. ``` <?xml version="1.0" encoding="utf-8"?> <Config> <data>This is some data</data> <MyConfig> <data>This is my data</data> </MyConfig> </Config> ``` This works well for deserialization. I am able to allow the class library to deserialize the .xml as normal and the I can use my own `XmlSerializer` instances with a `XmlNodeReader` against the internal `XmlNode`. ``` public class Config { [XmlElement] public string data; [XmlAnyElement] public XmlNode element; } public class MyConfig { [XmlElement] public string data; } class Program { static void Main(string[] args) { using (Stream fs = new FileStream(@"c:\temp\xmltest.xml", FileMode.Open)) { XmlSerializer xser1 = new XmlSerializer(typeof(Config)); Config config = (Config)xser1.Deserialize(fs); if (config.element != null) { XmlSerializer xser2 = new XmlSerializer(typeof(MyConfig)); MyConfig myConfig = (MyConfig)xser2.Deserialize(new XmlNodeReader(config.element)); } } } ``` I need to create a utility which will allow the user to generate a new configuration file that includes both the class library configuration as well my own configuration, so new objects will be created which were not read from the .xml file. The question is how can I serialize the data back into .xml? I realize that I have to initially call `XmlSerializer.Serialize` on my data before calling the same method on the class library configuration. However, this requires that my data is represented by an `XmlNode` after calling `Serialize`. What is the best way to serialize an object into an `XmlNode` using the `XmlSerializer`? Thanks, -kevin btw-- It looks like an `XmlNodeWriter` class written by Chris Lovett was available at one time from Microsoft, but the links are now broken. Does anyone know of an alternative location to get this class?
So you need to have your class contain custom configuration information, then serialize that class to XML, then make that serialized XML into an XML node: is that right? Could you just take the string created by the XMLSerializer and wrap that in it's own XML tags? ``` XmlSerializer xs = new XmlSerializer(typeof(MyConfig)); StringWriter xout = new StringWriter(); xs.Serialize(xout, myConfig); XmlDocument x = new XmlDocument(); x.LoadXml("<myConfig>" + xout.ToString() + "</myConfig>"); ``` Now x is an XmlDocument containing one element, "<myconfig>", which has your serialized custom configuration in it. Is that at all what you're looking for?
46,324
<p>I'm going to guess that the answer is "no" based on the below error message (and <a href="http://archives.postgresql.org/pgsql-sql/2004-08/msg00076.php" rel="noreferrer">this Google result</a>), but is there anyway to perform a cross-database query using PostgreSQL?</p> <pre><code>databaseA=# select * from databaseB.public.someTableName; ERROR: cross-database references are not implemented: "databaseB.public.someTableName" </code></pre> <p>I'm working with some data that is partitioned across two databases although data is really shared between the two (userid columns in one database come from the <code>users</code> table in the other database). I have no idea why these are two separate databases instead of schema, but c'est la vie...</p>
[ { "answer_id": 46336, "author": "stimms", "author_id": 361, "author_profile": "https://Stackoverflow.com/users/361", "pm_score": 5, "selected": false, "text": "<p>I have run into this before an came to the same conclusion about cross database queries as you. What I ended up doing was us...
2008/09/05
[ "https://Stackoverflow.com/questions/46324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249/" ]
I'm going to guess that the answer is "no" based on the below error message (and [this Google result](http://archives.postgresql.org/pgsql-sql/2004-08/msg00076.php)), but is there anyway to perform a cross-database query using PostgreSQL? ``` databaseA=# select * from databaseB.public.someTableName; ERROR: cross-database references are not implemented: "databaseB.public.someTableName" ``` I'm working with some data that is partitioned across two databases although data is really shared between the two (userid columns in one database come from the `users` table in the other database). I have no idea why these are two separate databases instead of schema, but c'est la vie...
*Note: As the original asker implied, if you are setting up two databases on the same machine you probably want to make two [schemas](https://www.postgresql.org/docs/current/static/ddl-schemas.html) instead - in that case you don't need anything special to query across them.* `postgres_fdw` -------------- Use [`postgres_fdw`](https://www.postgresql.org/docs/current/postgres-fdw.html) (foreign data wrapper) to connect to tables in any Postgres database - local or remote. Note that there are [foreign data wrappers for other popular data sources](http://wiki.postgresql.org/wiki/Foreign_data_wrappers). At this time, only `postgres_fdw` and `file_fdw` are part of the official Postgres distribution. ### For Postgres versions before 9.3 Versions this old are no longer supported, but if you need to do this in a pre-2013 Postgres installation, there is a function called [`dblink`](https://www.postgresql.org/docs/current/dblink.html). I've never used it, but it is maintained and distributed with the rest of PostgreSQL. If you're using the version of PostgreSQL that came with your Linux distro, you might need to install a package called postgresql-contrib.
46,338
<p>I am writing a webapp using CodeIgniter that requires authentication. I created a model which handles all my authentication. However, I can't find a way to access this authentication model from inside another model. Is there a way to access a model from inside another mode, or a better way to handle authentication inside CodeIgniter?</p>
[ { "answer_id": 46356, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 5, "selected": true, "text": "<p>In general, you don't want to create objects inside an object. That's a bad habit, instead, write a clear API and inject a mod...
2008/09/05
[ "https://Stackoverflow.com/questions/46338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889/" ]
I am writing a webapp using CodeIgniter that requires authentication. I created a model which handles all my authentication. However, I can't find a way to access this authentication model from inside another model. Is there a way to access a model from inside another mode, or a better way to handle authentication inside CodeIgniter?
In general, you don't want to create objects inside an object. That's a bad habit, instead, write a clear API and inject a model into your model. ``` <?php // in your controller $model1 = new Model1(); $model2 = new Model2(); $model2->setWhatever($model1); ?> ```
46,346
<p>Any ideas on how to implement tab completion for a .NET (C#) Console Application? And I mean within an application that is run and then loops for user input (like if you run ftp.exe without any arguments), like this: </p> <pre><code> string line = string.Empty; while (line != "exit") { //do something here Console.ReadLine(); } </code></pre> <p>I know I probably couldn't actually use readline, but I would like to be able to do tab completion at that same point where you retrieve input from the user.</p>
[ { "answer_id": 46352, "author": "Andrew Burns", "author_id": 3683, "author_profile": "https://Stackoverflow.com/users/3683", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.console.readkey.aspx\" rel=\"nofollow noreferrer\">Console.R...
2008/09/05
[ "https://Stackoverflow.com/questions/46346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194/" ]
Any ideas on how to implement tab completion for a .NET (C#) Console Application? And I mean within an application that is run and then loops for user input (like if you run ftp.exe without any arguments), like this: ``` string line = string.Empty; while (line != "exit") { //do something here Console.ReadLine(); } ``` I know I probably couldn't actually use readline, but I would like to be able to do tab completion at that same point where you retrieve input from the user.
Take a look at this code from the Mono project <http://tirania.org/blog/archive/2008/Aug-26.html> I played with it some the other day. It does a lot of command line editingy, but I don't think it does line completion.
46,347
<p>Is there a clean way to redirect all attempts to going to an HTTP:// version of a site to its HTTPS:// equivalent?</p>
[ { "answer_id": 46418, "author": "slipsec", "author_id": 1635, "author_profile": "https://Stackoverflow.com/users/1635", "pm_score": -1, "selected": false, "text": "<p>I think by 'cleanly' you mean like with a 300 redirect. Config for a lot of servers &amp; languages <a href=\"http://www...
2008/09/05
[ "https://Stackoverflow.com/questions/46347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2312/" ]
Is there a clean way to redirect all attempts to going to an HTTP:// version of a site to its HTTPS:// equivalent?
I think the cleanest way is as described [here on IIS-aid.com](http://www.iis-aid.com/articles/how_to_guides/redirect_http_to_https_iis_7). It's web.config only and so if you change server you don't have to remember all the steps you went through with the 403.4 custom error page or other special permissions, it just works. ``` <configuration> <system.webServer> <rewrite> <rules> <rule name="HTTP to HTTPS redirect" stopProcessing="true"> <match url="(.*)" /> <conditions> <add input="{HTTPS}" pattern="off" ignoreCase="true" /> </conditions> <action type="Redirect" redirectType="Permanent" url="https://{HTTP_HOST}/{R:1}" /> </rule> </rules> </rewrite> </system.webServer> </configuration> ```
46,350
<p>After lots of attempts and search I have never found a satisfactory way to do it with CSS2.</p> <p>A simple way to accomplish it is to wrap it into a handy <code>&lt;table&gt;</code> as shown in the sample below. Do you know how to do it avoiding table layouts and also avoiding quirky tricks?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>table { margin: 0 auto; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;test&lt;br/&gt;test&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;</code></pre> </div> </div> </p> <hr /> <p>What I want to know is how to do it without a fixed width and also being a block.</p>
[ { "answer_id": 46364, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 2, "selected": false, "text": "<p>This is going to be the lamest answer, but it works:</p>\n\n<p><a href=\"http://www.w3schools.com/TAGS/tag_center.as...
2008/09/05
[ "https://Stackoverflow.com/questions/46350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4264/" ]
After lots of attempts and search I have never found a satisfactory way to do it with CSS2. A simple way to accomplish it is to wrap it into a handy `<table>` as shown in the sample below. Do you know how to do it avoiding table layouts and also avoiding quirky tricks? ```css table { margin: 0 auto; } ``` ```html <table> <tr> <td>test<br/>test</td> </tr> </table> ``` --- What I want to know is how to do it without a fixed width and also being a block.
@Jason, yep, `<center>` works. Good times. I'll propose the following, though: ```css body { text-align: center; } .my-centered-content { margin: 0 auto; /* Centering */ display: inline; } ``` ```html <div class="my-centered-content"> <p>test</p> <p>test</p> </div> ``` **EDIT** @Santi, a block-level element will fill the width of the parent container, so it will effectively be `width:100%` and the text will flow on the left, leaving you with useless markup and an uncentered element. You might want to try `display: inline-block;`. Firefox might complain, but [it's right](http://www.w3.org/TR/CSS21/visuren.html#display-prop). Also, try adding a `border: solid red 1px;` to the CSS of the `.my-centered-content` DIV to see what's happening as you try these things out.
46,354
<p>I'm trying to perform a SQL query through a linked SSAS server. The initial query works fine:</p> <pre><code>SELECT "Ugly OLAP name" as "Value" FROM OpenQuery( OLAP, 'OLAP Query') </code></pre> <p>But if I try to add:</p> <pre><code>WHERE "Value" &gt; 0 </code></pre> <p>I get an error</p> <blockquote> <p>Invalid column name 'Value'</p> </blockquote> <p>Any ideas what I might be doing wrong?</p> <hr> <p>So the problem was that the order in which elements of the query are processed are different that the order they are written. According to this source:</p> <p><a href="http://blogs.x2line.com/al/archive/2007/06/30/3187.aspx" rel="noreferrer">http://blogs.x2line.com/al/archive/2007/06/30/3187.aspx</a></p> <p>The order of evaluation in MSSQL is:</p> <ol> <li>FROM</li> <li>ON</li> <li>JOIN</li> <li>WHERE</li> <li>GROUP BY</li> <li>HAVING</li> <li>SELECT</li> <li>ORDER BY</li> </ol> <p>So the alias wasn't processed until after the WHERE and HAVING clauses.</p>
[ { "answer_id": 46375, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 0, "selected": false, "text": "<p>Oh, bummer. I just saw, you select AS FOO. Don't you need a HAVING claus in this case?</p>\n\n<pre><code>SELECT whatever AS v...
2008/09/05
[ "https://Stackoverflow.com/questions/46354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1807/" ]
I'm trying to perform a SQL query through a linked SSAS server. The initial query works fine: ``` SELECT "Ugly OLAP name" as "Value" FROM OpenQuery( OLAP, 'OLAP Query') ``` But if I try to add: ``` WHERE "Value" > 0 ``` I get an error > > Invalid column name 'Value' > > > Any ideas what I might be doing wrong? --- So the problem was that the order in which elements of the query are processed are different that the order they are written. According to this source: <http://blogs.x2line.com/al/archive/2007/06/30/3187.aspx> The order of evaluation in MSSQL is: 1. FROM 2. ON 3. JOIN 4. WHERE 5. GROUP BY 6. HAVING 7. SELECT 8. ORDER BY So the alias wasn't processed until after the WHERE and HAVING clauses.
This should work: ``` SELECT A.Value FROM ( SELECT "Ugly OLAP name" as "Value" FROM OpenQuery( OLAP, 'OLAP Query') ) AS a WHERE a.Value > 0 ``` It's not that Value is a reserved word, the problem is that it's a column alias, not the column name. By making it an inline view, "Value" becomes the column name and can then be used in a where clause.
46,365
<p>We have a SQL Server 2005 SP2 machine running a large number of databases, all of which contain full-text catalogs. Whenever we try to drop one of these databases or rebuild a full-text index, the drop or rebuild process hangs indefinitely with a MSSEARCH wait type. The process can’t be killed, and a server reboot is required to get things running again. Based on a Microsoft forums post<a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2681739&amp;SiteID=1" rel="noreferrer">1</a>, it appears that the problem might be an improperly removed full-text catalog. Can anyone recommend a way to determine which catalog is causing the problem, without having to remove all of them?</p> <p><a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2681739&amp;SiteID=1" rel="noreferrer">1</a> [<a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2681739&amp;SiteID=1]" rel="noreferrer">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2681739&amp;SiteID=1]</a> “Yes we did have full text catalogues in the database, but since I had disabled full text search for the database, and disabled msftesql, I didn't suspect them. I got however an article from Microsoft support, showing me how I could test for catalogues not properly removed. So I discovered that there still existed an old catalogue, which I ,after and only after re-enabling full text search, were able to delete, since then my backup has worked”</p>
[ { "answer_id": 49073, "author": "Booji Boy", "author_id": 1433, "author_profile": "https://Stackoverflow.com/users/1433", "pm_score": 1, "selected": false, "text": "<p>Have you tried running process monitor and when it hangs and see what the underlying error is? Using process moniter you...
2008/09/05
[ "https://Stackoverflow.com/questions/46365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4803/" ]
We have a SQL Server 2005 SP2 machine running a large number of databases, all of which contain full-text catalogs. Whenever we try to drop one of these databases or rebuild a full-text index, the drop or rebuild process hangs indefinitely with a MSSEARCH wait type. The process can’t be killed, and a server reboot is required to get things running again. Based on a Microsoft forums post[1](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2681739&SiteID=1), it appears that the problem might be an improperly removed full-text catalog. Can anyone recommend a way to determine which catalog is causing the problem, without having to remove all of them? [1](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2681739&SiteID=1) [<http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2681739&SiteID=1]> “Yes we did have full text catalogues in the database, but since I had disabled full text search for the database, and disabled msftesql, I didn't suspect them. I got however an article from Microsoft support, showing me how I could test for catalogues not properly removed. So I discovered that there still existed an old catalogue, which I ,after and only after re-enabling full text search, were able to delete, since then my backup has worked”
Here's a suggestion. I don't have any corrupted databases but you can try this: ``` declare @t table (name nvarchar(128)) insert into @t select name from sys.databases --where is_fulltext_enabled while exists(SELECT * FROM @t) begin declare @name nvarchar(128) select @name = name from @t declare @SQL nvarchar(4000) set @SQL = 'IF EXISTS(SELECT * FROM '+@name+'.sys.fulltext_catalogs) AND NOT EXISTS(SELECT * FROM sys.databases where is_fulltext_enabled=1 AND name='''+@name+''') PRINT ''' +@Name + ' Could be the culprit''' print @sql exec sp_sqlexec @SQL delete from @t where name = @name end ``` If it doesn't work, remove the filter checking `sys.databases`.
46,377
<p>What is the syntax for placing constraints on multiple types? The basic example:</p> <pre><code>class Animal&lt;SpeciesType&gt; where SpeciesType : Species </code></pre> <p>I would like to place constraints on both types in the following definition such that <code>SpeciesType</code> must inherit from <code>Species</code> and <code>OrderType</code> must inherit from <code>Order</code>:</p> <pre><code>class Animal&lt;SpeciesType, OrderType&gt; </code></pre>
[ { "answer_id": 46384, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 7, "selected": true, "text": "<pre><code>public class Animal&lt;SpeciesType,OrderType&gt;\n where SpeciesType : Species\n where OrderType : Order\n{\n...
2008/09/05
[ "https://Stackoverflow.com/questions/46377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ]
What is the syntax for placing constraints on multiple types? The basic example: ``` class Animal<SpeciesType> where SpeciesType : Species ``` I would like to place constraints on both types in the following definition such that `SpeciesType` must inherit from `Species` and `OrderType` must inherit from `Order`: ``` class Animal<SpeciesType, OrderType> ```
``` public class Animal<SpeciesType,OrderType> where SpeciesType : Species where OrderType : Order { } ```
46,385
<p>What's the best way to delete all rows from a table in sql but to keep n number of rows on the top? </p>
[ { "answer_id": 46386, "author": "Cory Foy", "author_id": 4083, "author_profile": "https://Stackoverflow.com/users/4083", "pm_score": 7, "selected": true, "text": "<pre><code>DELETE FROM Table WHERE ID NOT IN (SELECT TOP 10 ID FROM Table)\n</code></pre>\n\n<p><strong>Edit:</strong> </p>\n...
2008/09/05
[ "https://Stackoverflow.com/questions/46385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/298/" ]
What's the best way to delete all rows from a table in sql but to keep n number of rows on the top?
``` DELETE FROM Table WHERE ID NOT IN (SELECT TOP 10 ID FROM Table) ``` **Edit:** Chris brings up a good performance hit since the TOP 10 query would be run for each row. If this is a one time thing, then it may not be as big of a deal, but if it is a common thing, then I did look closer at it.
46,387
<p>I am using a perl script to POST to Google Appengine application. I post a text file containing some XML using the -F option.</p> <p><a href="http://www.cpan.org/authors/id/E/EL/ELIJAH/bget-1.1" rel="nofollow noreferrer">http://www.cpan.org/authors/id/E/EL/ELIJAH/bget-1.1</a></p> <p>There is a version 1.2, already tested and get the same issue. The post looks something like this.</p> <pre><code>Host: foo.appspot.com User-Agent: lwp-request/1.38 Content-Type: text/plain Content-Length: 202 &lt;XML&gt; &lt;BLAH&gt;Hello World&lt;/BLAH&gt; &lt;/XML&gt; </code></pre> <p>I have modified the example so the 202 isn't right, don't worry about that. On to the problem. The Content-Length matches the number of bytes on the file, however unless I manually increase the Content-Length it does not send all of the file, a few bytes get truncated. The number of bytes truncated is not the same for files of different sizes. I used the -r option on the script and I can see what it is sending and it is sending all of the file, but Google Appengine self.request.body shows that not everything is received. I think the solution is to get the right number for Content-Length and apparently it isn't as simple as number of bytes on the file or the perl script is mangling it somehow.</p> <p>Update: Thanks to Erickson for the right answer. I used printf to append characters to the end of the file and it always truncated exactly the number of lines in the file. I suppose I could figure out what is being added by iterating through every character on the server side but not worth it. This wasn't even answered over on the google groups set up for app engine!</p>
[ { "answer_id": 46405, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 3, "selected": true, "text": "<p>Is the number of extra bytes you need equal to the number of lines in the file? I ask because perhaps its possible that so...
2008/09/05
[ "https://Stackoverflow.com/questions/46387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4527/" ]
I am using a perl script to POST to Google Appengine application. I post a text file containing some XML using the -F option. <http://www.cpan.org/authors/id/E/EL/ELIJAH/bget-1.1> There is a version 1.2, already tested and get the same issue. The post looks something like this. ``` Host: foo.appspot.com User-Agent: lwp-request/1.38 Content-Type: text/plain Content-Length: 202 <XML> <BLAH>Hello World</BLAH> </XML> ``` I have modified the example so the 202 isn't right, don't worry about that. On to the problem. The Content-Length matches the number of bytes on the file, however unless I manually increase the Content-Length it does not send all of the file, a few bytes get truncated. The number of bytes truncated is not the same for files of different sizes. I used the -r option on the script and I can see what it is sending and it is sending all of the file, but Google Appengine self.request.body shows that not everything is received. I think the solution is to get the right number for Content-Length and apparently it isn't as simple as number of bytes on the file or the perl script is mangling it somehow. Update: Thanks to Erickson for the right answer. I used printf to append characters to the end of the file and it always truncated exactly the number of lines in the file. I suppose I could figure out what is being added by iterating through every character on the server side but not worth it. This wasn't even answered over on the google groups set up for app engine!
Is the number of extra bytes you need equal to the number of lines in the file? I ask because perhaps its possible that somehow carriage-returns are being introduced but not counted.
46,425
<p>I have a function that gets x(a value) and xs(a list) and removes all values that are bigger than x from the list. Well it doesn't work, can you tell me why?</p> <pre><code>(defun biggerElems(x xs) (let ((xst)) (dolist (elem xs) (if (&gt; x elem) (setf xst (remove elem xs)))) xst)) </code></pre>
[ { "answer_id": 46437, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 4, "selected": true, "text": "<p>I think it's this line that's not right:</p>\n\n<pre><code>(setf xst (remove elem xs))))\n</code></pre>\n\n<p>The first...
2008/09/05
[ "https://Stackoverflow.com/questions/46425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2450/" ]
I have a function that gets x(a value) and xs(a list) and removes all values that are bigger than x from the list. Well it doesn't work, can you tell me why? ``` (defun biggerElems(x xs) (let ((xst)) (dolist (elem xs) (if (> x elem) (setf xst (remove elem xs)))) xst)) ```
I think it's this line that's not right: ``` (setf xst (remove elem xs)))) ``` The first argument to `setf` is the place, followed by the value. It looks like you have it backwards (and `xst` is either `nil` or uninitialized). You might find it easier to do this: ``` (defun biggerElems (x xs) (remove-if (lambda (item) (> item x)) xs)) ```
46,454
<p>I am working on a simple chat application using a System.Windows.Forms.WebBrowser Control to display the messages between the user and the recipient. How do I get the control to automatically scroll to the bottom every time I update the DocumentText of the control?</p>
[ { "answer_id": 46463, "author": "Oded", "author_id": 1583, "author_profile": "https://Stackoverflow.com/users/1583", "pm_score": 2, "selected": false, "text": "<p>I would use the AutoScrollOffset property and set it the the bottom left of the WebBrowser control, so something like:</p>\n\...
2008/09/05
[ "https://Stackoverflow.com/questions/46454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1385358/" ]
I am working on a simple chat application using a System.Windows.Forms.WebBrowser Control to display the messages between the user and the recipient. How do I get the control to automatically scroll to the bottom every time I update the DocumentText of the control?
Thanks guys -- I voted you both up but neither would work out for my situation. What I ended up doing was ``` webCtrl.Document.Window.ScrollTo(0, int.MaxValue); ```
46,482
<p>Is there an easy way to read an entire Access file (.mdb) into a DataSet in .NET (specifically C# or VB)?</p> <p>Or at least to get a list of tables from an access file so that I can loop through it and add them one at a time into a DataSet?</p>
[ { "answer_id": 46490, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 2, "selected": false, "text": "<p>You should be able to access it using an <a href=\"http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbconnect...
2008/09/05
[ "https://Stackoverflow.com/questions/46482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1108/" ]
Is there an easy way to read an entire Access file (.mdb) into a DataSet in .NET (specifically C# or VB)? Or at least to get a list of tables from an access file so that I can loop through it and add them one at a time into a DataSet?
Thanks for the suggestions. I was able to use those samples to put together this code, which seems to achieve what I'm looking for. ``` Using cn = New OleDbConnection(connectionstring) cn.Open() Dim ds As DataSet = new DataSet() Dim Schema As DataTable = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"}) For i As Integer = 0 To Schema.Rows.Count - 1 Dim dt As DataTable = New DataTable(Schema.Rows(i)!TABLE_NAME.ToString()) Using adapter = New OleDbDataAdapter("SELECT * FROM " + Schema.Rows(i)!TABLE_NAME.ToString(), cn) adapter.Fill(dt) End Using ds.Tables.Add(dt) Next i End Using ```
46,483
<p>What are the differences between <code>htmlspecialchars()</code> and <code>htmlentities()</code>. When should I use one or the other?</p>
[ { "answer_id": 46491, "author": "Thomas Owens", "author_id": 572, "author_profile": "https://Stackoverflow.com/users/572", "pm_score": 10, "selected": true, "text": "<p>From the PHP documentation for <a href=\"http://us2.php.net/htmlentities\" rel=\"noreferrer\">htmlentities</a>:</p>\n\n...
2008/09/05
[ "https://Stackoverflow.com/questions/46483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4137/" ]
What are the differences between `htmlspecialchars()` and `htmlentities()`. When should I use one or the other?
From the PHP documentation for [htmlentities](http://us2.php.net/htmlentities): > > This function is identical to `htmlspecialchars()` in all ways, except with `htmlentities()`, all characters which have HTML character entity equivalents are translated into these entities. > > > From the PHP documentation for [htmlspecialchars](http://us.php.net/htmlspecialchars): > > Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use `htmlentities()` instead. > > > The difference is what gets encoded. The choices are everything (entities) or "special" characters, like ampersand, double and single quotes, less than, and greater than (specialchars). I prefer to use `htmlspecialchars` whenever possible. For example: ```php echo htmlentities('<Il était une fois un être>.'); // Output: &lt;Il &eacute;tait une fois un &ecirc;tre&gt;. // ^^^^^^^^ ^^^^^^^ echo htmlspecialchars('<Il était une fois un être>.'); // Output: &lt;Il était une fois un être&gt;. // ^ ^ ```
46,489
<p>In my web application I include all of my JavaScripts as js files that are embedded resources in the assembly, and add them to the page using <code>ClientScriptManager.GetWebResourceUrl()</code>. However, in some of my js files, I have references to other static assets like image urls. I would like to make those assembly resources as well. Is there a way to tokenize the reference to the resource? e.g.</p> <pre><code>this.drophint = document.createElement('img'); this.drophint.src = '/_layouts/images/dragdrophint.gif'; </code></pre> <p>Could become something like:</p> <pre><code>this.drophint = document.createElement('img'); this.drophint.src = '{resource:assembly.location.dragdrophint.gif}'; </code></pre>
[ { "answer_id": 47242, "author": "Jon", "author_id": 4764, "author_profile": "https://Stackoverflow.com/users/4764", "pm_score": 3, "selected": true, "text": "<p>I'd suggest that you emit the web resources as a dynamic javascript associative array.</p>\n\n<p>Server side code:</p>\n\n<pre>...
2008/09/05
[ "https://Stackoverflow.com/questions/46489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/67/" ]
In my web application I include all of my JavaScripts as js files that are embedded resources in the assembly, and add them to the page using `ClientScriptManager.GetWebResourceUrl()`. However, in some of my js files, I have references to other static assets like image urls. I would like to make those assembly resources as well. Is there a way to tokenize the reference to the resource? e.g. ``` this.drophint = document.createElement('img'); this.drophint.src = '/_layouts/images/dragdrophint.gif'; ``` Could become something like: ``` this.drophint = document.createElement('img'); this.drophint.src = '{resource:assembly.location.dragdrophint.gif}'; ```
I'd suggest that you emit the web resources as a dynamic javascript associative array. Server side code: ``` StringBuilder script = new StringBuilder(); script.Append("var imgResources = {};"); script.AppendFormat("imgResources['{0}'] = '{1}';", "drophint", Page.ClientScript.GetWebResourceUrl(Page.GetType(), "assembly.location.dragdrophint.gif")); script.AppendFormat("imgResources['{0}'] = '{1}';", "anotherimg", Page.ClientScript.GetWebResourceUrl(Page.GetType(), "assembly.location.anotherimg.gif")); Page.ClientScript.RegisterClientScriptBlock( Page.GetType(), "imgResources", script.ToString(), true); ``` Then your client side code looks like this: ``` this.drophint = document.createElement('img'); this.drophint.src = imgResources['drophint']; this.anotherimg = document.createElement('img'); this.anotherimg.src = imgResources['anotherimg']; ``` Hope this helps.
46,495
<p>Why can't you do this and is there are work around?</p> <p>You get this error.</p> <p>Msg 2714, Level 16, State 1, Line 13 There is already an object named '#temptable' in the database.</p> <pre><code>declare @x int set @x = 1 if (@x = 0) begin select 1 as Value into #temptable end else begin select 2 as Value into #temptable end select * from #temptable drop table #temptable </code></pre>
[ { "answer_id": 46527, "author": "Craig", "author_id": 2894, "author_profile": "https://Stackoverflow.com/users/2894", "pm_score": 0, "selected": false, "text": "<p>I am going to guess that the issue is that you haven't created the #temptable.</p>\n\n<p>Sorry I can't be more detailed but ...
2008/09/05
[ "https://Stackoverflow.com/questions/46495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2184/" ]
Why can't you do this and is there are work around? You get this error. Msg 2714, Level 16, State 1, Line 13 There is already an object named '#temptable' in the database. ``` declare @x int set @x = 1 if (@x = 0) begin select 1 as Value into #temptable end else begin select 2 as Value into #temptable end select * from #temptable drop table #temptable ```
This is a two-part question and while Kev Fairchild provides a good answer to the second question he totally ignores the first - *why is the error produced?* The answer lies in the way the preprocessor works. This ``` SELECT field-list INTO #symbol ... ``` is resolved into a parse-tree that is directly equivalent to ``` DECLARE #symbol_sessionid TABLE(field-list) INSERT INTO #symbol_sessionid SELECT field-list ... ``` and this puts #symbol into the local scope's name table. The business with \_sessionid is to provide each user session with a private namespace; if you specify two hashes (##symbol) this behaviour is suppressed. Munging and unmunging of the sessionid extension is (ovbiously) transparent. The upshot of all this is that multiple INTO #symbol clauses produce multiple declarations in the same scope, leading to Msg 2714.
46,532
<p>If I have an XElement that has child elements, and if I remove a child element from the parent, removing all references between the two, will the child XElement have the same namespaces as the parent?</p> <p>In other words, if I have the following XML:</p> <pre><code>&lt;parent xmlns:foo="abc"&gt; &lt;foo:child /&gt; &lt;/parent&gt; </code></pre> <p>and I remove the child element, will the child element's xml look like</p> <pre><code>&lt;child xmlns="abc" /&gt; </code></pre> <p>or like </p> <pre><code>&lt;child /&gt; </code></pre>
[ { "answer_id": 46637, "author": "xanadont", "author_id": 1886, "author_profile": "https://Stackoverflow.com/users/1886", "pm_score": 1, "selected": false, "text": "<p>Sure. Ultimately the image comes from a URL of some sort. Do a view-source on the web page and see what that URL looks ...
2008/09/05
[ "https://Stackoverflow.com/questions/46532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If I have an XElement that has child elements, and if I remove a child element from the parent, removing all references between the two, will the child XElement have the same namespaces as the parent? In other words, if I have the following XML: ``` <parent xmlns:foo="abc"> <foo:child /> </parent> ``` and I remove the child element, will the child element's xml look like ``` <child xmlns="abc" /> ``` or like ``` <child /> ```
Sure. Ultimately the image comes from a URL of some sort. Do a view-source on the web page and see what that URL looks like. With a certain amount of reverse-engineering, usage of System.Web.UI.HtmlTextWriter, perhaps an HttpHandler, etc. you should be able to get what you want.
46,571
<p>I have been tasked with going through a number of ColdFusion sites that have recently been the subject of a rather nasty SQL Injection attack. Basically my work involves adding <code>&lt;cfqueryparam</code>> tags to all of the inline sql. For the most part I've got it down, but can anybody tell me how to use cfqueryparam with the LIKE operator?</p> <p>If my query looks like this:</p> <pre><code>select * from Foo where name like '%Bob%' </code></pre> <p>what should my <code>&lt;cfqueryparam</code>> tag look like?</p>
[ { "answer_id": 47197, "author": "Adam Tuttle", "author_id": 751, "author_profile": "https://Stackoverflow.com/users/751", "pm_score": 7, "selected": true, "text": "<p>@Joel, I have to disagree.</p>\n\n<pre><code>select a,b,c\nfrom Foo\nwhere name like &lt;cfqueryparam cfsqltype=\"columnT...
2008/09/05
[ "https://Stackoverflow.com/questions/46571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3271/" ]
I have been tasked with going through a number of ColdFusion sites that have recently been the subject of a rather nasty SQL Injection attack. Basically my work involves adding `<cfqueryparam`> tags to all of the inline sql. For the most part I've got it down, but can anybody tell me how to use cfqueryparam with the LIKE operator? If my query looks like this: ``` select * from Foo where name like '%Bob%' ``` what should my `<cfqueryparam`> tag look like?
@Joel, I have to disagree. ``` select a,b,c from Foo where name like <cfqueryparam cfsqltype="columnType" value="%#variables.someName#%" /> ``` 1. Never suggest to someone that they should "select star." Bad form! Even for an example! (Even copied from the question!) 2. The query is pre-compiled and you should include the wild card character(s) as part of the parameter being passed to the query. This format is more readable and will run more efficiently. 3. When doing string concatenation, use the ampersand operator (&), not the plus sign. Technically, in most cases, plus will work just fine... until you throw a NumberFormat() in the middle of the string and start wondering why you're being told that you're not passing a valid number when you've checked and you are.
46,582
<p>We have the requirement to take a form submission and save some data, then redirect the user to a page offsite, but in redirecting, we need to "submit" a form with POST, not GET.</p> <p>I was hoping there was an easy way to accomplish this, but I'm starting to think there isn't. I think I must now create a simple other page, with just the form that I want, redirect to it, populate the form variables, then do a body.onload call to a script that merely calls document.forms[0].submit();</p> <p>Can anyone tell me if there is an alternative? We might need to tweak this later in the project, and it might get sort of complicated, so if there was an easy we could do this all non-other page dependent that would be fantastic.</p> <p>Anyway, thanks for any and all responses.</p>
[ { "answer_id": 46611, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 2, "selected": false, "text": "<p>PostbackUrl can be set on your asp button to post to a different page.</p>\n\n<p>if you need to do it in codebehind, try Ser...
2008/09/05
[ "https://Stackoverflow.com/questions/46582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/232/" ]
We have the requirement to take a form submission and save some data, then redirect the user to a page offsite, but in redirecting, we need to "submit" a form with POST, not GET. I was hoping there was an easy way to accomplish this, but I'm starting to think there isn't. I think I must now create a simple other page, with just the form that I want, redirect to it, populate the form variables, then do a body.onload call to a script that merely calls document.forms[0].submit(); Can anyone tell me if there is an alternative? We might need to tweak this later in the project, and it might get sort of complicated, so if there was an easy we could do this all non-other page dependent that would be fantastic. Anyway, thanks for any and all responses.
Doing this requires understanding how HTTP redirects work. When you use `Response.Redirect()`, you send a response (to the browser that made the request) with [HTTP Status Code 302](http://en.wikipedia.org/wiki/HTTP_302), which tells the browser where to go next. By definition, the browser will make that via a `GET` request, even if the original request was a `POST`. Another option is to use [HTTP Status Code 307](http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection), which specifies that the browser should make the redirect request in the same way as the original request, but to prompt the user with a security warning. To do that, you would write something like this: ``` public void PageLoad(object sender, EventArgs e) { // Process the post on your side Response.Status = "307 Temporary Redirect"; Response.AddHeader("Location", "http://example.com/page/to/post.to"); } ``` Unfortunately, this won't always work. [Different browsers implement this differently](http://ilia.ws/archives/152-Cross-Domain-POST-Redirection.html), since it is not a common status code. > > Alas, unlike the Opera and FireFox developers, the IE developers have never read the spec, and even the latest, most secure IE7 will redirect the POST request from domain A to domain B without any warnings or confirmation dialogs! Safari also acts in an interesting manner, while it does not raise a confirmation dialog and performs the redirect, it throws away the POST data, **effectively changing 307 redirect into the more common 302.** > > > So, as far as I know, the only way to implement something like this would be to use Javascript. There are two options I can think of off the top of my head: 1. Create the form and have its `action` attribute point to the third-party server. Then, add a click event to the submit button that first executes an AJAX request to your server with the data, and then allows the form to be submitted to the third-party server. 2. Create the form to post to your server. When the form is submitted, show the user a page that has a form in it with all of the data you want to pass on, all in hidden inputs. Just show a message like "Redirecting...". Then, add a javascript event to the page that submits the form to the third-party server. Of the two, I would choose the second, for two reasons. First, it is more reliable than the first because Javascript is not required for it to work; for those who don't have it enabled, you can always make the submit button for the hidden form visible, and instruct them to press it if it takes more than 5 seconds. Second, you can decide what data gets transmitted to the third-party server; if you use just process the form as it goes by, you will be passing along all of the post data, which is not always what you want. Same for the 307 solution, assuming it worked for all of your users. Hope this helps!
46,585
<p>From what I can gather, there are three categories:</p> <ol> <li>Never use <code>GET</code> and use <code>POST</code></li> <li>Never use <code>POST</code> and use <code>GET</code></li> <li>It doesn't matter which one you use.</li> </ol> <p>Am I correct in assuming those three cases? If so, what are some examples from each case?</p>
[ { "answer_id": 46591, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 3, "selected": false, "text": "<p>Use GET when you want the URL to reflect the state of the page. This is useful for viewing dynamically generated pages, ...
2008/09/05
[ "https://Stackoverflow.com/questions/46585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
From what I can gather, there are three categories: 1. Never use `GET` and use `POST` 2. Never use `POST` and use `GET` 3. It doesn't matter which one you use. Am I correct in assuming those three cases? If so, what are some examples from each case?
Use `POST` for destructive actions such as creation (I'm aware of the irony), editing, and deletion, because you can't hit a `POST` action in the address bar of your browser. Use `GET` when it's safe to allow a person to call an action. So a URL like: ``` http://myblog.org/admin/posts/delete/357 ``` Should bring you to a confirmation page, rather than simply deleting the item. It's far easier to avoid accidents this way. `POST` is also more secure than `GET`, because you aren't sticking information into a URL. And so using `GET` as the `method` for an HTML form that collects a password or other sensitive information is not the best idea. One final note: `POST` can transmit a larger amount of information than `GET`. 'POST' has no size restrictions for transmitted data, whilst 'GET' is limited to 2048 characters.
46,586
<p>Everyone is aware of Dijkstra's <a href="http://portal.acm.org/citation.cfm?doid=362947" rel="noreferrer">Letters to the editor: go to statement considered harmful</a> (also <a href="http://www.cs.utexas.edu/%7EEWD/transcriptions/EWD02xx/EWD215.html" rel="noreferrer">here</a> .html transcript and <a href="http://www.cs.utexas.edu/users/EWD/ewd02xx/EWD215.PDF" rel="noreferrer">here</a> .pdf) and there has been a formidable push since that time to eschew the goto statement whenever possible. While it's possible to use goto to produce unmaintainable, sprawling code, it nevertheless remains in <a href="http://msdn.microsoft.com/en-us/library/13940fs2(VS.71).aspx" rel="noreferrer">modern programming languages</a>. Even the advanced <a href="http://en.wikipedia.org/wiki/Goto#Continuations" rel="noreferrer">continuation</a> control structure in Scheme can be described as a sophisticated goto.</p> <p>What circumstances warrant the use of goto? When is it best to avoid?</p> <p>As a follow-up question: C provides a pair of functions, setjmp() and longjmp(), that provide the ability to goto not just within the current stack frame but within any of the calling frames. Should these be considered as dangerous as goto? More dangerous?</p> <hr /> <p>Dijkstra himself regretted that title, for which he was not responsible. At the end of <a href="http://www.cs.utexas.edu/%7EEWD/transcriptions/EWD13xx/EWD1308.html" rel="noreferrer">EWD1308</a> (also <a href="http://www.cs.utexas.edu/%7EEWD/ewd13xx/EWD1308.PDF" rel="noreferrer">here</a> .pdf) he wrote:</p> <blockquote> <p>Finally a short story for the record. In 1968, the Communications of the ACM published a text of mine under the title &quot;<em>The goto statement considered harmful</em>&quot;, which in later years would be most frequently referenced, regrettably, however, often by authors who had seen no more of it than its title, which became a cornerstone of my fame by becoming a template: we would see all sorts of articles under the title &quot;X considered harmful&quot; for almost any X, including one titled &quot;Dijkstra considered harmful&quot;. But what had happened? I had submitted a paper under the title &quot;<em><strong>A case against the goto statement</strong></em>&quot;, which, in order to speed up its publication, the editor had changed into a &quot;letter to the Editor&quot;, and in the process he had given it a new title of his own invention! The editor was Niklaus Wirth.</p> </blockquote> <p>A well thought out classic paper about this topic, to be matched to that of Dijkstra, is <a href="http://www.clifford.at/cfun/cliffdev/p261-knuth.pdf" rel="noreferrer">Structured Programming with go to Statements</a>, by Donald E. Knuth. Reading both helps to reestablish context and a non-dogmatic understanding of the subject. In this paper, Dijkstra's opinion on this case is reported and is even more strong:</p> <blockquote> <p><em>Donald E. Knuth:</em> I believe that by presenting such a view I am not in fact disagreeing sharply with Dijkstra's ideas, since he recently wrote the following: &quot;Please don't fall into the trap of believing that I am terribly dogmatical about [the go to statement]. <strong>I have the uncomfortable feeling that others are making a religion out of it, as if the conceptual problems of programming could be solved by a single trick, by a simple form of coding discipline!</strong>&quot;</p> </blockquote>
[ { "answer_id": 46597, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": false, "text": "<p>The original paper should be thought of as \"Unconditional GOTO Considered Harmful\". It was in particular advocatin...
2008/09/05
[ "https://Stackoverflow.com/questions/46586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658/" ]
Everyone is aware of Dijkstra's [Letters to the editor: go to statement considered harmful](http://portal.acm.org/citation.cfm?doid=362947) (also [here](http://www.cs.utexas.edu/%7EEWD/transcriptions/EWD02xx/EWD215.html) .html transcript and [here](http://www.cs.utexas.edu/users/EWD/ewd02xx/EWD215.PDF) .pdf) and there has been a formidable push since that time to eschew the goto statement whenever possible. While it's possible to use goto to produce unmaintainable, sprawling code, it nevertheless remains in [modern programming languages](http://msdn.microsoft.com/en-us/library/13940fs2(VS.71).aspx). Even the advanced [continuation](http://en.wikipedia.org/wiki/Goto#Continuations) control structure in Scheme can be described as a sophisticated goto. What circumstances warrant the use of goto? When is it best to avoid? As a follow-up question: C provides a pair of functions, setjmp() and longjmp(), that provide the ability to goto not just within the current stack frame but within any of the calling frames. Should these be considered as dangerous as goto? More dangerous? --- Dijkstra himself regretted that title, for which he was not responsible. At the end of [EWD1308](http://www.cs.utexas.edu/%7EEWD/transcriptions/EWD13xx/EWD1308.html) (also [here](http://www.cs.utexas.edu/%7EEWD/ewd13xx/EWD1308.PDF) .pdf) he wrote: > > Finally a short story for the record. > In 1968, the Communications of the ACM > published a text of mine under the > title "*The goto statement considered > harmful*", which in later years would > be most frequently referenced, > regrettably, however, often by authors > who had seen no more of it than its > title, which became a cornerstone of > my fame by becoming a template: we > would see all sorts of articles under > the title "X considered harmful" for > almost any X, including one titled > "Dijkstra considered harmful". But > what had happened? I had submitted a > paper under the title "***A case against > the goto statement***", which, in order > to speed up its publication, the > editor had changed into a "letter to > the Editor", and in the process he had > given it a new title of his own > invention! The editor was Niklaus > Wirth. > > > A well thought out classic paper about this topic, to be matched to that of Dijkstra, is [Structured Programming with go to Statements](http://www.clifford.at/cfun/cliffdev/p261-knuth.pdf), by Donald E. Knuth. Reading both helps to reestablish context and a non-dogmatic understanding of the subject. In this paper, Dijkstra's opinion on this case is reported and is even more strong: > > *Donald E. Knuth:* I believe that by presenting such a > view I am not in fact disagreeing > sharply with Dijkstra's ideas, since > he recently wrote the following: > "Please don't fall into the trap of > believing that I am terribly > dogmatical about [the go to > statement]. **I have the uncomfortable > feeling that others are making a > religion out of it, as if the > conceptual problems of programming > could be solved by a single trick, by > a simple form of coding discipline!**" > > >
The following statements are generalizations; while it is always possible to plead exception, it usually (in my experience and humble opinion) isn't worth the risks. 1. Unconstrained use of memory addresses (either GOTO or raw pointers) provides too many opportunities to make easily avoidable mistakes. 2. The more ways there are to arrive at a particular "location" in the code, the less confident one can be about what the state of the system is at that point. (See below.) 3. Structured programming IMHO is less about "avoiding GOTOs" and more about making the structure of the code match the structure of the data. For example, a repeating data structure (e.g. array, sequential file, etc.) is naturally processed by a repeated unit of code. Having built-in structures (e.g. while, for, until, for-each, etc.) allows the programmer to avoid the tedium of repeating the same cliched code patterns. 4. Even if GOTO is low-level implementation detail (not always the case!) it's below the level that the programmer should be thinking. How many programmers balance their personal checkbooks in raw binary? How many programmers worry about which sector on the disk contains a particular record, instead of just providing a key to a database engine (and how many ways could things go wrong if we really wrote all of our programs in terms of physical disk sectors)? Footnotes to the above: Regarding point 2, consider the following code: ```c a = b + 1 /* do something with a */ ``` At the "do something" point in the code, we can state with high confidence that `a` is greater than `b`. (Yes, I'm ignoring the possibility of untrapped integer overflow. Let's not bog down a simple example.) On the other hand, if the code had read this way: ```c ... goto 10 ... a = b + 1 10: /* do something with a */ ... goto 10 ... ``` The multiplicity of ways to get to label 10 means that we have to work much harder to be confident about the relationships between `a` and `b` at that point. (In fact, in the general case it's undecideable!) Regarding point 4, the whole notion of "going someplace" in the code is just a metaphor. Nothing is really "going" anywhere inside the CPU except electrons and photons (for the waste heat). Sometimes we give up a metaphor for another, more useful, one. I recall encountering (a few decades ago!) a language where ```c if (some condition) { action-1 } else { action-2 } ``` was implemented on a virtual machine by compiling action-1 and action-2 as out-of-line parameterless routines, then using a single two-argument VM opcode which used the boolean value of the condition to invoke one or the other. The concept was simply "choose what to invoke now" rather than "go here or go there". Again, just a change of metaphor.
46,636
<p>What's the best way to copy a file from a network share to the local file system using a Windows batch file? Normally, I would use "net use *" but using this approach how can I get the drive letter?</p>
[ { "answer_id": 46640, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 5, "selected": true, "text": "<p>Can you just use the full UNC path to the file?</p>\n\n<pre><code>copy \\\\myserver\\myshare\\myfolder\\myfile.txt c:\\myfi...
2008/09/05
[ "https://Stackoverflow.com/questions/46636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4778/" ]
What's the best way to copy a file from a network share to the local file system using a Windows batch file? Normally, I would use "net use \*" but using this approach how can I get the drive letter?
Can you just use the full UNC path to the file? ``` copy \\myserver\myshare\myfolder\myfile.txt c:\myfiles ```
46,663
<p>Is it possible to send an email from my Java application using a GMail account? I have configured my company mail server with Java app to send email, but that's not going to cut it when I distribute the application. Answers with any of using Hotmail, Yahoo or GMail are acceptable.</p>
[ { "answer_id": 46676, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 0, "selected": false, "text": "<p>An easy route would be to have the gmail account configured/enabled for POP3 access. This would allow you to send out ...
2008/09/05
[ "https://Stackoverflow.com/questions/46663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1288/" ]
Is it possible to send an email from my Java application using a GMail account? I have configured my company mail server with Java app to send email, but that's not going to cut it when I distribute the application. Answers with any of using Hotmail, Yahoo or GMail are acceptable.
First download the [JavaMail API](https://java.net/projects/javamail/pages/Home) and make sure the relevant jar files are in your classpath. Here's a full working example using GMail. ``` import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class Main { private static String USER_NAME = "*****"; // GMail user name (just the part before "@gmail.com") private static String PASSWORD = "********"; // GMail password private static String RECIPIENT = "lizard.bill@myschool.edu"; public static void main(String[] args) { String from = USER_NAME; String pass = PASSWORD; String[] to = { RECIPIENT }; // list of recipient email addresses String subject = "Java send mail example"; String body = "Welcome to JavaMail!"; sendFromGMail(from, pass, to, subject, body); } private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) { Properties props = System.getProperties(); String host = "smtp.gmail.com"; props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.user", from); props.put("mail.smtp.password", pass); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress(from)); InternetAddress[] toAddress = new InternetAddress[to.length]; // To get the array of addresses for( int i = 0; i < to.length; i++ ) { toAddress[i] = new InternetAddress(to[i]); } for( int i = 0; i < toAddress.length; i++) { message.addRecipient(Message.RecipientType.TO, toAddress[i]); } message.setSubject(subject); message.setText(body); Transport transport = session.getTransport("smtp"); transport.connect(host, from, pass); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (AddressException ae) { ae.printStackTrace(); } catch (MessagingException me) { me.printStackTrace(); } } } ``` Naturally, you'll want to do more in the `catch` blocks than print the stack trace as I did in the example code above. (Remove the `catch` blocks to see which method calls from the JavaMail API throw exceptions so you can better see how to properly handle them.) --- Thanks to [@jodonnel](https://stackoverflow.com/users/4223/jodonnell) and everyone else who answered. I'm giving him a bounty because his answer led me about 95% of the way to a complete answer.
46,704
<p>For the following HTML:</p> <pre><code>&lt;form name=&quot;myForm&quot;&gt; &lt;label&gt;One&lt;input name=&quot;area&quot; type=&quot;radio&quot; value=&quot;S&quot; /&gt;&lt;/label&gt; &lt;label&gt;Two&lt;input name=&quot;area&quot; type=&quot;radio&quot; value=&quot;R&quot; /&gt;&lt;/label&gt; &lt;label&gt;Three&lt;input name=&quot;area&quot; type=&quot;radio&quot; value=&quot;O&quot; /&gt;&lt;/label&gt; &lt;label&gt;Four&lt;input name=&quot;area&quot; type=&quot;radio&quot; value=&quot;U&quot; /&gt;&lt;/label&gt; &lt;/form&gt; </code></pre> <p>Changing from the following JavaScript code:</p> <pre><code>$(function() { var myForm = document.myForm; var radios = myForm.area; // Loop through radio buttons for (var i=0; i&lt;radios.length; i++) { if (radios[i].value == &quot;S&quot;) { radios[i].checked = true; // Selected when form displays radioClicks(); // Execute the function, initial setup } radios[i].onclick = radioClicks; // Assign to run when clicked } }); </code></pre> <p>Thanks</p> <p>EDIT: The response I selected answers the question I asked, however I like the answer that uses <code>bind()</code> because it also shows how to distinguish the group of radio buttons</p>
[ { "answer_id": 46715, "author": "Adam Cuzzort", "author_id": 4760, "author_profile": "https://Stackoverflow.com/users/4760", "pm_score": 1, "selected": false, "text": "<pre><code>$(function() {\n $('input[@type=\"radio\"]').click(radioClicks);\n});\n</code></pre>\n" }, { "answ...
2008/09/05
[ "https://Stackoverflow.com/questions/46704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ]
For the following HTML: ``` <form name="myForm"> <label>One<input name="area" type="radio" value="S" /></label> <label>Two<input name="area" type="radio" value="R" /></label> <label>Three<input name="area" type="radio" value="O" /></label> <label>Four<input name="area" type="radio" value="U" /></label> </form> ``` Changing from the following JavaScript code: ``` $(function() { var myForm = document.myForm; var radios = myForm.area; // Loop through radio buttons for (var i=0; i<radios.length; i++) { if (radios[i].value == "S") { radios[i].checked = true; // Selected when form displays radioClicks(); // Execute the function, initial setup } radios[i].onclick = radioClicks; // Assign to run when clicked } }); ``` Thanks EDIT: The response I selected answers the question I asked, however I like the answer that uses `bind()` because it also shows how to distinguish the group of radio buttons
``` $( function() { $("input:radio") .click(radioClicks) .filter("[value='S']") .attr("checked", "checked"); }); ```
46,718
<p>I'm just curious how most people make their ASP.NET pages printer-friendly? Do you create a separate printer-friendly version of the ASPX page, use CSS or something else? How do you handle situations like page breaks and wide tables?</p> <p>Is there one elegant solution that works for the majority of the cases? </p>
[ { "answer_id": 46724, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 5, "selected": true, "text": "<p>You basically make another CSS file that hide things or gives simpler \"printer-friendly\" style to things then add tha...
2008/09/05
[ "https://Stackoverflow.com/questions/46718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3329/" ]
I'm just curious how most people make their ASP.NET pages printer-friendly? Do you create a separate printer-friendly version of the ASPX page, use CSS or something else? How do you handle situations like page breaks and wide tables? Is there one elegant solution that works for the majority of the cases?
You basically make another CSS file that hide things or gives simpler "printer-friendly" style to things then add that with a `media="print"` so that it only applies to print media (when it is printed) ``` <link rel="stylesheet" type="text/css" media="print" href="print.css" /> ```
46,719
<p>I have a regex call that I need help with.</p> <p>I haven't posted my regex, because it is not relevant here. What I want to be able to do is, during the Replace, I also want to modify the ${test} portion by doing a Html.Encode on the entire text that is effecting the regex.</p> <p>Basically, wrap the entire text that is within the range of the regex with the bold tag, but also Html.Encode the text inbetween the bold tag.</p> <pre><code>RegexOptions regexOptions = RegexOptions.Compiled | RegexOptions.IgnoreCase; text = Regex.Replace(text, regexBold, @"&lt;b&gt;${text}&lt;/b&gt;", regexOptions); </code></pre>
[ { "answer_id": 46722, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 2, "selected": false, "text": "<p>Don't use Regex.Replace in this case... use..</p>\n\n<pre><code>foreach(Match in Regex.Matches(...))\n{\n //do y...
2008/09/05
[ "https://Stackoverflow.com/questions/46719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
I have a regex call that I need help with. I haven't posted my regex, because it is not relevant here. What I want to be able to do is, during the Replace, I also want to modify the ${test} portion by doing a Html.Encode on the entire text that is effecting the regex. Basically, wrap the entire text that is within the range of the regex with the bold tag, but also Html.Encode the text inbetween the bold tag. ``` RegexOptions regexOptions = RegexOptions.Compiled | RegexOptions.IgnoreCase; text = Regex.Replace(text, regexBold, @"<b>${text}</b>", regexOptions); ```
Heres an implementation of this I've used to pick out special replace strings from content and localize them. ``` protected string FindAndTranslateIn(string content) { return Regex.Replace(content, @"\{\^(.+?);(.+?)?}", new MatchEvaluator(TranslateHandler), RegexOptions.IgnoreCase); } public string TranslateHandler(Match m) { if (m.Success) { string key = m.Groups[1].Value; key = FindAndTranslateIn(key); string def = string.Empty; if (m.Groups.Count > 2) { def = m.Groups[2].Value; if(def.Length > 1) { def = FindAndTranslateIn(def); } } if (group == null) { return Translate(key, def); } else { return Translate(key, group, def); } } return string.Empty; } ``` From the match evaluator delegate you return everything you want replaced, so where I have returns you would have bold tags and an encode call, mine also supports recursion, so a little over complicated for your needs, but you can just pare down the example for your needs. This is equivalent to doing an iteration over the collection of matches and doing parts of the replace methods job. It just saves you some code, and you get to use a fancy shmancy delegate.
46,777
<p>I want to run a web application on php and mysql, using the CakePHP framework. And to keep the threshold of using the site at a very low place, I want to not use the standard login with username/password. (And I don't want to hassle my users with something like OpenID either. Goes to user type.)</p> <p>So I'm thinking that the users shall be able to log in by sending an email to login@domain.com with no subject or content required. And they will get, in reply, an email with a link that will log them in (it will contain a hash). Also I will let the users do some actions without even visiting the site at all, just send an email with command@domain.com and the command will be carried out. I will assume that the users and their email providers takes care of their email account security and as such there is no need for it on my site.</p> <p>Now, how do I go from an email is sent to an account that is not read by humans to there being fired off some script (basically a "dummy browser client" calls an url( and the cakephp will take care of the rest)?</p> <hr> <p>I have never used a cron job before, but I do think I understand their purpose or how they generally work. I can not have the script be called by random people visiting the site, as that solution won't work for several reasons. I think I would like to hear more about the possibility of having the script be run as response to an email coming in, if anyone has any input at all on that. If it's run as a cron job it would only check every X minutes and users would get a lag in their response (if i understand it correctly). </p> <p>Since there will be different email addresses for different commands, like <strong>login</strong>@domain.com and I know what to do and how to do it to based on the sender email, i dont even need the content, subject or any other headers from the email.</p> <hr> <p>There is a lot of worry about security of this application, I understand the issues, but without giving away my concept, I dont think it is a big issue for what I am doing. Also about the usability issue, there really isnt any. It's just gonna be login to provide changes on a users profile if/when they need that and one other command. And this is the main email and is very easy to remember and the outset of this whole concept.</p>
[ { "answer_id": 46792, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 2, "selected": false, "text": "<p>You'll need some sort of CronJob/Timer Service that checks the Mailbox regularly and then acts on it. Alternatively, you ...
2008/09/05
[ "https://Stackoverflow.com/questions/46777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4013/" ]
I want to run a web application on php and mysql, using the CakePHP framework. And to keep the threshold of using the site at a very low place, I want to not use the standard login with username/password. (And I don't want to hassle my users with something like OpenID either. Goes to user type.) So I'm thinking that the users shall be able to log in by sending an email to login@domain.com with no subject or content required. And they will get, in reply, an email with a link that will log them in (it will contain a hash). Also I will let the users do some actions without even visiting the site at all, just send an email with command@domain.com and the command will be carried out. I will assume that the users and their email providers takes care of their email account security and as such there is no need for it on my site. Now, how do I go from an email is sent to an account that is not read by humans to there being fired off some script (basically a "dummy browser client" calls an url( and the cakephp will take care of the rest)? --- I have never used a cron job before, but I do think I understand their purpose or how they generally work. I can not have the script be called by random people visiting the site, as that solution won't work for several reasons. I think I would like to hear more about the possibility of having the script be run as response to an email coming in, if anyone has any input at all on that. If it's run as a cron job it would only check every X minutes and users would get a lag in their response (if i understand it correctly). Since there will be different email addresses for different commands, like **login**@domain.com and I know what to do and how to do it to based on the sender email, i dont even need the content, subject or any other headers from the email. --- There is a lot of worry about security of this application, I understand the issues, but without giving away my concept, I dont think it is a big issue for what I am doing. Also about the usability issue, there really isnt any. It's just gonna be login to provide changes on a users profile if/when they need that and one other command. And this is the main email and is very easy to remember and the outset of this whole concept.
I have used the [pop3 php class](http://www.phpclasses.org/browse/file/3.html) with great success (there is also a [Pear POP3 module](http://pear.php.net/package/Net_POP3)). Using the pop3 class looks something like this: ``` require ('pop3.php'); $pop3 = new pop3_class(); $pop3->hostname = MAILHOST; $pop3->Open(); $pop3->Login('myemailaddress@mydomain.com', 'mypassword'); foreach($pop3->ListMessages("","") as $msgidx => $msgsize) { $headers = ""; $body = ""; $pop3->RetrieveMessage($msgidx, $headers, $body, -1); } ``` I use it to monitor a POP3 mailbox which feeds into a database. It gets called by a cronjob which uses wget to call the url to my php script. ``` */5 * * * * "wget -q --http-user=me --http-passwd=pass 'http://mydomain.com/mail.php'" >> /dev/null 2>&1 ``` **Edit** I've been thinking about your need to have users send certain site commands by email. Wouldn't it be easier to have a single address that multiple commands can be sent to rather than having multiple addresses? I think the security concerns are pretty valid too. Unless the commands are non-destructive or aren't doing anything user-specific, the system will be wide open to anyone who knows how to spoof an email address (which would be everyone :) ).
46,827
<p>Visual Studio 2005 doesn't provide an interface for creating relationships between tables in a SQL Server CE database (I'm using version 3.0) and you can't open a Compact Edition DB using Management Studio as far as I know. Any ideas?</p>
[ { "answer_id": 46832, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 7, "selected": true, "text": "<p>Unfortunately there is currently no designer support (unlike for SQL Server 2005) for building relationships between tables in...
2008/09/05
[ "https://Stackoverflow.com/questions/46827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1943/" ]
Visual Studio 2005 doesn't provide an interface for creating relationships between tables in a SQL Server CE database (I'm using version 3.0) and you can't open a Compact Edition DB using Management Studio as far as I know. Any ideas?
Unfortunately there is currently no designer support (unlike for SQL Server 2005) for building relationships between tables in SQL Server CE. To build relationships you need to use SQL commands such as: ``` ALTER TABLE Orders ADD CONSTRAINT FK_Customer_Order FOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId) ``` If you are doing CE development, i would recomend this FAQ: **EDIT**: In Visual Studio 2008 this is now possible to do in the GUI by right-clicking on your table.
46,841
<p>Occasionally, on a ASP (classic) site users will get this error:</p> <pre><code>[DBNETLIB][ConnectionRead (recv()).]General network error. </code></pre> <p>Seems to be random and not connected to any particular page. The SQL server is separated from the web server and my guess is that every once and a while the "link" goes down between the two. Router/switch issue... or has someone else ran into this problem before?</p>
[ { "answer_id": 47080, "author": "Grzegorz Gierlik", "author_id": 1483, "author_profile": "https://Stackoverflow.com/users/1483", "pm_score": 0, "selected": false, "text": "<p>I'd seen this error many times. It could be caused by many things including network errors too :).</p>\n\n<p>But ...
2008/09/05
[ "https://Stackoverflow.com/questions/46841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4835/" ]
Occasionally, on a ASP (classic) site users will get this error: ``` [DBNETLIB][ConnectionRead (recv()).]General network error. ``` Seems to be random and not connected to any particular page. The SQL server is separated from the web server and my guess is that every once and a while the "link" goes down between the two. Router/switch issue... or has someone else ran into this problem before?
Using the same setup as yours (ie separate web and database server), I've seen it from time to time and it has always been a connection problem between the servers - typically when the database server is being rebooted but sometimes when there's a comms problem somewhere in the system. I've not seen it triggered by any problems with the ASP code itself, which is why you're seeing it apparently at random and not connected to a particular page.
46,842
<p>What is the best way to determine duplicate records in a SQL Server table?</p> <p>For instance, I want to find the last duplicate email received in a table (table has primary key, receiveddate and email fields).</p> <p>Sample data:</p> <pre><code>1 01/01/2008 stuff@stuff.com 2 02/01/2008 stuff@stuff.com 3 01/12/2008 noone@stuff.com </code></pre>
[ { "answer_id": 46843, "author": "Rob Rolnick", "author_id": 4798, "author_profile": "https://Stackoverflow.com/users/4798", "pm_score": 0, "selected": false, "text": "<p>Couldn't you join the list on the e-mail field and then see what nulls you get in your result?</p>\n\n<p>Or better yet...
2008/09/05
[ "https://Stackoverflow.com/questions/46842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What is the best way to determine duplicate records in a SQL Server table? For instance, I want to find the last duplicate email received in a table (table has primary key, receiveddate and email fields). Sample data: ``` 1 01/01/2008 stuff@stuff.com 2 02/01/2008 stuff@stuff.com 3 01/12/2008 noone@stuff.com ```
something like this ``` select email ,max(receiveddate) as MaxDate from YourTable group by email having count(email) > 1 ```
46,863
<p>How do I concatenate together two strings, of unknown length, in COBOL? So for example:</p> <pre><code>WORKING-STORAGE. FIRST-NAME PIC X(15) VALUE SPACES. LAST-NAME PIC X(15) VALUE SPACES. FULL-NAME PIC X(31) VALUE SPACES. </code></pre> <p>If <code>FIRST-NAME = 'JOHN '</code> and <code>LAST-NAME = 'DOE '</code>, how can I get:</p> <pre><code>FULL-NAME = 'JOHN DOE ' </code></pre> <p>as opposed to:</p> <pre><code>FULL-NAME = 'JOHN DOE ' </code></pre>
[ { "answer_id": 46899, "author": "Eric H", "author_id": 4650, "author_profile": "https://Stackoverflow.com/users/4650", "pm_score": 2, "selected": false, "text": "<p>At first glance, the solution is to use reference modification to STRING together the two strings, including the space. The...
2008/09/05
[ "https://Stackoverflow.com/questions/46863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4650/" ]
How do I concatenate together two strings, of unknown length, in COBOL? So for example: ``` WORKING-STORAGE. FIRST-NAME PIC X(15) VALUE SPACES. LAST-NAME PIC X(15) VALUE SPACES. FULL-NAME PIC X(31) VALUE SPACES. ``` If `FIRST-NAME = 'JOHN '` and `LAST-NAME = 'DOE '`, how can I get: ``` FULL-NAME = 'JOHN DOE ' ``` as opposed to: ``` FULL-NAME = 'JOHN DOE ' ```
I believe the following will give you what you desire. ``` STRING FIRST-NAME DELIMITED BY " ", " ", LAST-NAME DELIMITED BY SIZE INTO FULL-NAME. ```
46,898
<p>If I have an object implementing the <code>Map</code> interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map?</p> <p>Will the ordering of elements depend on the specific map implementation that I have for the interface?</p>
[ { "answer_id": 46905, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 8, "selected": false, "text": "<p>Yes, the order depends on the specific Map implementation.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/46898/...
2008/09/05
[ "https://Stackoverflow.com/questions/46898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4807/" ]
If I have an object implementing the `Map` interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map? Will the ordering of elements depend on the specific map implementation that I have for the interface?
```java Map<String, String> map = ... for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println(entry.getKey() + "/" + entry.getValue()); } ``` On Java 10+: ```java for (var entry : map.entrySet()) { System.out.println(entry.getKey() + "/" + entry.getValue()); } ```
46,907
<pre><code>INSERT INTO tblExcel (ename, position, phone, email) VALUES ('Burton, Andrew', 'Web Developer / Network Assistant', '876-9259', 'aburton@wccs.edu') </code></pre> <p>I've got an Access table that has five fields: id, ename, position, phone, and email...each one is plain text field with 50 characters, save for position which is 255 and id which is an autoincrement field. I'm using a VB.NET to read data from an Excel table, which gets pushed into a simple class that's used to fill out that query. I do the same thing with two other tables, whose data are pulled from a DB2 table and a MySQL table through. The other two work, but this simple INSERT loop keeps failing, so I don't think it's my "InsertNoExe" function that handles all the OleDb stuff.</p> <p>So, um, does that query, any of the field titles, etc. look bogus? I can post other bits of code if anyone wants to see it.</p> <p><strong>EDIT:</strong> Fixed. I wasn't sure if the wide image counted as a Stack Overflow bug or not, which is why I left it.</p> <p><strong>EDIT 2:</strong> I'm dense. I use a try...catch to see the bogus query, and don't even check the ex.messsage. Gah.</p> <pre><code>INSERT INTO tblExcel (ename, position, phone, email) VALUES ('Burton, Andrew', 'Web Developer / Network Assistant', '876-9259', 'aburton@wccs.edu') at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(Int32 hr) at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object&amp; executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object&amp; executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object&amp; executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteNonQuery() at EmployeeList.EmployeeDatabase.ExeNonQuery(String sql) in C:\andy\html\code\vb\EmployeeList\EmployeeDatabase.vb:line 263 Syntax error in INSERT INTO statement. </code></pre> <p><strong>EDIT 3:</strong> Thank you, Chris.</p>
[ { "answer_id": 46916, "author": "Guy Starbuck", "author_id": 2194, "author_profile": "https://Stackoverflow.com/users/2194", "pm_score": 0, "selected": false, "text": "<p>The spacing of \"Web Developer / Network Assistant\" looks a little wonky, maybe there is a hidden character in there...
2008/09/05
[ "https://Stackoverflow.com/questions/46907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4252/" ]
``` INSERT INTO tblExcel (ename, position, phone, email) VALUES ('Burton, Andrew', 'Web Developer / Network Assistant', '876-9259', 'aburton@wccs.edu') ``` I've got an Access table that has five fields: id, ename, position, phone, and email...each one is plain text field with 50 characters, save for position which is 255 and id which is an autoincrement field. I'm using a VB.NET to read data from an Excel table, which gets pushed into a simple class that's used to fill out that query. I do the same thing with two other tables, whose data are pulled from a DB2 table and a MySQL table through. The other two work, but this simple INSERT loop keeps failing, so I don't think it's my "InsertNoExe" function that handles all the OleDb stuff. So, um, does that query, any of the field titles, etc. look bogus? I can post other bits of code if anyone wants to see it. **EDIT:** Fixed. I wasn't sure if the wide image counted as a Stack Overflow bug or not, which is why I left it. **EDIT 2:** I'm dense. I use a try...catch to see the bogus query, and don't even check the ex.messsage. Gah. ``` INSERT INTO tblExcel (ename, position, phone, email) VALUES ('Burton, Andrew', 'Web Developer / Network Assistant', '876-9259', 'aburton@wccs.edu') at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(Int32 hr) at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteNonQuery() at EmployeeList.EmployeeDatabase.ExeNonQuery(String sql) in C:\andy\html\code\vb\EmployeeList\EmployeeDatabase.vb:line 263 Syntax error in INSERT INTO statement. ``` **EDIT 3:** Thank you, Chris.
I beleive "position" is a reserved word. Try... INSERT into tblExcel (ename, [position], phone, email) VALUES (... [Reserved Words](http://office.microsoft.com/en-us/access/HP010322491033.aspx)
46,909
<p>I have a situation where I might have multiple instances of a program running at once, and it's important that just one specific function not be executing in more than one of these instances at once.</p> <p>Is this the proper way to use a mutex to prevent this from happening?</p> <pre><code>lock (this.GetType()) { _log.Info("Doing Sync"); DoSync(); _log.Info("Sync Completed"); } </code></pre>
[ { "answer_id": 46928, "author": "Jonathan Webb", "author_id": 1518, "author_profile": "https://Stackoverflow.com/users/1518", "pm_score": 3, "selected": false, "text": "<p>TheSeeker is correct.</p>\n\n<p>Jeff Richter's advice in <a href=\"http://books.google.com/books?id=C-V_AAAACAAJ&amp...
2008/09/05
[ "https://Stackoverflow.com/questions/46909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
I have a situation where I might have multiple instances of a program running at once, and it's important that just one specific function not be executing in more than one of these instances at once. Is this the proper way to use a mutex to prevent this from happening? ``` lock (this.GetType()) { _log.Info("Doing Sync"); DoSync(); _log.Info("Sync Completed"); } ```
You said multiple instances of one application, so we're talking about two program.exe's running, right? The lock statement won't lock across multiple programs, just within the program. If you want a true Mutex, look at the [System.Threading.Mutex](https://learn.microsoft.com/en-us/dotnet/api/system.threading.mutex) object. Here is a usage example: ``` bool createdNew; using (Mutex mtx = new Mutex(false, "MyAwesomeMutex", out createdNew)) { try { mtx.WaitOne(); MessageBox.Show("Click OK to release the mutex."); } finally { mtx.ReleaseMutex(); } } ``` The createdNew variable will let you know whether or not it was created the first time. It only tells you if it has been created, though. If you want to acquire the lock, you need to call WaitOne and then call ReleaseMutex to release it. If you just want to see if you created a Mutex, just constructing it is fine.
46,915
<p>As a follow up to this question: <a href="https://stackoverflow.com/questions/46873/developing-a-online-exam-application-how-do-i-prevent-cheaters">Developing a online exam application, how do I prevent cheaters?</a></p> <p>Can I detect when Flex application looses its focus? that is if a user has clicked onto another application or opened a browser tab?</p> <p>I read this: <a href="http://blog.flexmonkeypatches.com/2007/12/07/detecting-when-a-flex-application-loses-focus/" rel="nofollow noreferrer">Detecting when a Flex application loses focus</a> but was not very clear...</p>
[ { "answer_id": 47161, "author": "Raleigh Buckner", "author_id": 1153, "author_profile": "https://Stackoverflow.com/users/1153", "pm_score": 4, "selected": true, "text": "<p>The key part of the code at that link is the </p>\n\n<pre><code>systemManager.stage.addEventListener(Event.DEACTIVA...
2008/09/05
[ "https://Stackoverflow.com/questions/46915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
As a follow up to this question: [Developing a online exam application, how do I prevent cheaters?](https://stackoverflow.com/questions/46873/developing-a-online-exam-application-how-do-i-prevent-cheaters) Can I detect when Flex application looses its focus? that is if a user has clicked onto another application or opened a browser tab? I read this: [Detecting when a Flex application loses focus](http://blog.flexmonkeypatches.com/2007/12/07/detecting-when-a-flex-application-loses-focus/) but was not very clear...
The key part of the code at that link is the ``` systemManager.stage.addEventListener(Event.DEACTIVATE,deactivate); ``` The Flash player send outs activate and deactivate events when the focus enters and leaves the player. All you need to do is create a listenr for them and react appropriately. A more clear example of how to use to the activate and deactivate events can be seen at [blog.flexaxamples.com](http://blog.flexexamples.com/2008/02/29/determining-if-a-flex-application-has-focus-using-the-activate-and-deactivate-events/). Also, it looks like the activate and deactivate events have trouble in some browsers. [Colin Moock has more info on that here.](http://www.moock.org/blog/archives/000252.html)
46,924
<p>Suppose I want to implement a reasonably efficient 'keyword recognition algorithm', that is first given a list of keyword, and must then answer if another given word was in the list. </p> <p>In an imperative language, I would store the keywords in a tree (one node per character). Then, when receiving a word to test, I would scan my tree to test if the word is a keyword.</p> <p>I'd like to understand how such an algorithm would be coded in a functional language. How does one get the benefits of 'stateless' programming while keeping the efficiency of 'imperative' algorithms. Isn't it necessary to store the tree somewhere between the lookups if you don't want to rebuild it each time? </p>
[ { "answer_id": 46948, "author": "Rob Rolnick", "author_id": 4798, "author_profile": "https://Stackoverflow.com/users/4798", "pm_score": 0, "selected": false, "text": "<p>I imagine you'd want something like a tree with a list of children, as described <a href=\"http://csus.cs.mcgill.ca/wi...
2008/09/05
[ "https://Stackoverflow.com/questions/46924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4177/" ]
Suppose I want to implement a reasonably efficient 'keyword recognition algorithm', that is first given a list of keyword, and must then answer if another given word was in the list. In an imperative language, I would store the keywords in a tree (one node per character). Then, when receiving a word to test, I would scan my tree to test if the word is a keyword. I'd like to understand how such an algorithm would be coded in a functional language. How does one get the benefits of 'stateless' programming while keeping the efficiency of 'imperative' algorithms. Isn't it necessary to store the tree somewhere between the lookups if you don't want to rebuild it each time?
I think what you mean is a character per node... sort of like a simple hash tree scheme for keyword lookup. Assuming this or even another kind of tree... imagine doing something like this (in pseudo-LISP): ``` (defun buildtree (wordlist) ...code to build tree recursively returns the tree...) (define lookup (tree word) ...code to look up word using tree, returns t or nil...) (defun lookupmany (tree querylist) (if (eq querylist nil) nil (cons (lookup tree (car querylist)) (lookupmany tree (cdr querylist)) ) ) (defun main (wordlist querylist) ; the main entry point (lookupmany (buildtree wordlist) querylist) ) ``` if this is what you mean, this is fairly straight-forward functional programming. Is it really stateless? That's a matter of debate. Some people would say some forms of functional programming store what we normally call "state" on the stack. Moreover, Common LISP even since the first edition of the Steele book has had iterative constructs, and LISP has had setq for a long, long time. But in the theory of programming languages, what we mean by "stateless" is pretty much satisfied by the idea shown here. I think the above is something like the arrangement you mean.
46,933
<p>I'm having some inheritance issues as I've got a group of inter-related abstract classes that need to all be overridden together to create a client implementation. Ideally I would like to do something like the following:</p> <pre><code>abstract class Animal { public Leg GetLeg() {...} } abstract class Leg { } class Dog : Animal { public override DogLeg Leg() {...} } class DogLeg : Leg { } </code></pre> <p>This would allow anyone using the Dog class to automatically get DogLegs and anyone using the Animal class to get Legs. The problem is that the overridden function has to have the same type as the base class so this will not compile. I don't see why it shouldn't though, since DogLeg is implicitly castable to Leg. I know there are plenty of ways around this, but I'm more curious why this isn't possible/implemented in C#.</p> <p><strong>EDIT</strong>: I modified this somewhat, since I'm actually using properties instead of functions in my code. </p> <p><strong>EDIT</strong>: I changed it back to functions, because the answer only applies to that situation (covariance on the value parameter of a property's set function <strong>shouldn't</strong> work). Sorry for the fluctuations! I realize it makes a lot of the answers seem irrelevant.</p>
[ { "answer_id": 46935, "author": "shsteimer", "author_id": 292, "author_profile": "https://Stackoverflow.com/users/292", "pm_score": 2, "selected": false, "text": "<p>GetLeg() must return Leg to be an override. Your Dog class however, can still return DogLeg objects since they are a chil...
2008/09/05
[ "https://Stackoverflow.com/questions/46933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ]
I'm having some inheritance issues as I've got a group of inter-related abstract classes that need to all be overridden together to create a client implementation. Ideally I would like to do something like the following: ``` abstract class Animal { public Leg GetLeg() {...} } abstract class Leg { } class Dog : Animal { public override DogLeg Leg() {...} } class DogLeg : Leg { } ``` This would allow anyone using the Dog class to automatically get DogLegs and anyone using the Animal class to get Legs. The problem is that the overridden function has to have the same type as the base class so this will not compile. I don't see why it shouldn't though, since DogLeg is implicitly castable to Leg. I know there are plenty of ways around this, but I'm more curious why this isn't possible/implemented in C#. **EDIT**: I modified this somewhat, since I'm actually using properties instead of functions in my code. **EDIT**: I changed it back to functions, because the answer only applies to that situation (covariance on the value parameter of a property's set function **shouldn't** work). Sorry for the fluctuations! I realize it makes a lot of the answers seem irrelevant.
The short answer is that GetLeg is invariant in its return type. The long answer can be found here: [Covariance and contravariance](http://blogs.msdn.com/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx) I'd like to add that while inheritance is usually the first abstraction tool that most developers pull out of their toolbox, it is almost always possible to use composition instead. Composition is slightly more work for the API developer, but makes the API more useful for its consumers.
46,981
<p>I have an Image control with it's source bound to a property on an object(string url to an image). After making a service call, i update the data object with a new URL. The exception is thrown after it leaves my code, after invoking the PropertyChanged event.</p> <p>The data structure and the service logic are all done in a core dll that has no knowledge of the UI. How do I sync up with the UI thread when i cant access a Dispatcher? </p> <p>PS: Accessing Application.Current.RootVisual in order to get at a Dispatcher is not a solution because the root visual is on a different thread(causing the exact exception i need to prevent). </p> <p>PPS: This only is a problem with the image control, binding to any other ui element, the cross thread issue is handled for you.</p>
[ { "answer_id": 47294, "author": "Jonathan Parker", "author_id": 4504, "author_profile": "https://Stackoverflow.com/users/4504", "pm_score": 1, "selected": false, "text": "<p>Have you tried implementing <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropert...
2008/09/05
[ "https://Stackoverflow.com/questions/46981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/580/" ]
I have an Image control with it's source bound to a property on an object(string url to an image). After making a service call, i update the data object with a new URL. The exception is thrown after it leaves my code, after invoking the PropertyChanged event. The data structure and the service logic are all done in a core dll that has no knowledge of the UI. How do I sync up with the UI thread when i cant access a Dispatcher? PS: Accessing Application.Current.RootVisual in order to get at a Dispatcher is not a solution because the root visual is on a different thread(causing the exact exception i need to prevent). PPS: This only is a problem with the image control, binding to any other ui element, the cross thread issue is handled for you.
``` System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => {...}); ``` Also look [here.](https://stackoverflow.com/questions/1924408/invalid-cross-thread-access-issue/1925827#1925827)
47,007
<p>A question that occasionally arises is what is the best way to determine the changelist that you last synced to in Perforce. This is often needed for things like injecting the changelist number into the revision info by the automatic build system.</p>
[ { "answer_id": 47012, "author": "Greg Whitfield", "author_id": 2102, "author_profile": "https://Stackoverflow.com/users/2102", "pm_score": 5, "selected": false, "text": "<p>Just to answer this myself in keeping with Jeff's suggestion of using Stackoverflow as a place to keep technical sn...
2008/09/05
[ "https://Stackoverflow.com/questions/47007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2102/" ]
A question that occasionally arises is what is the best way to determine the changelist that you last synced to in Perforce. This is often needed for things like injecting the changelist number into the revision info by the automatic build system.
I recommend the opposite for automatic build systems: you should first get the latest changelist from the server using: ``` p4 changes -s submitted -m1 ``` then sync to that change and record it in the revision info. The reason is as follows. Although [Perforce recommends the following](https://portal.perforce.com/s/article/3458) to determine the changelist to which the workspace is synced: ``` p4 changes -m1 @clientname ``` they note a few gotchas: * This only works if you have not submitted anything from the workspace in question. * It is also possible that a client workspace is not synced to any specific changelist. and there's an additional gotcha they don't mention: * If the highest changelist to which the sync occured strictly deleted files from the workspace, the next-highest changelist will be reported (unless it, too, strictly deleted files). If you must sync first and record later, Perforce recommends running the following command to determine if you've been bit by the above gotchas; it should indicate nothing was synced or removed: ``` p4 sync -n @changelist_number ```
47,022
<p>I've somehow managed to get an SVN repository into a bad state. I've moved a directory and now I can't commit it in its new location.</p> <p>As far as <code>svn status</code> is concerned, the directory is unknown (the name of the directory is <code>type</code>).</p> <pre> $ svn status ? type </pre> <p>When I try to add the directory, the server says it already exists.</p> <pre> $ svn add type svn: warning: 'type' is already under version control </pre> <p>If I try to update the directory, it's gone again.</p> <pre> $ svn update type svn: '.' is not under version control </pre> <p>If I try to commit it, the server complains that it's old parent directory no longer exists.</p> <pre> $ svn commit type -m "Moving type" svn: Commit failed (details follow): svn: '/prior/trunk/src/nyu/prior/cvc3/theorem_prover/expression' path not found </pre> <p>To add to the mystery, the contents of the directory are marked as modified.</p> <pre> $ svn status type A + type M + type/IntegerType.java M + type/BooleanType.java M + type/Type.java M + type/RationalRangeType.java M + type/RationalType.java M + type/IntegerRangeType.java </pre> <p>If I try to update from within the directory, I get this.</p> <pre> $ cd type $ svn update svn: Two top-level reports with no target </pre> <p>Committing from within the directory gives the same <code>path not found</code> error as above.</p> <p>What's going on and how do I fix it?</p> <p>EDIT: @Rob Oxspring caught me out: I got too aggressive moving things around in Eclipse.</p> <p>UPDATE: I'm accepting @Rob Oxspring's answer of "don't do that/just start over" and taking his advice. I'd still be interested if anybody could tell me: (a) what the above error messages <em>mean</em> precisely and (b) how to actually <em>fix</em> the problem.</p>
[ { "answer_id": 47030, "author": "crashmstr", "author_id": 1441, "author_profile": "https://Stackoverflow.com/users/1441", "pm_score": 2, "selected": false, "text": "<p>Did you start by just copying/moving the directory with OS commands, or did you start with SVN stuff? If you just copied...
2008/09/05
[ "https://Stackoverflow.com/questions/47022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ]
I've somehow managed to get an SVN repository into a bad state. I've moved a directory and now I can't commit it in its new location. As far as `svn status` is concerned, the directory is unknown (the name of the directory is `type`). ``` $ svn status ? type ``` When I try to add the directory, the server says it already exists. ``` $ svn add type svn: warning: 'type' is already under version control ``` If I try to update the directory, it's gone again. ``` $ svn update type svn: '.' is not under version control ``` If I try to commit it, the server complains that it's old parent directory no longer exists. ``` $ svn commit type -m "Moving type" svn: Commit failed (details follow): svn: '/prior/trunk/src/nyu/prior/cvc3/theorem_prover/expression' path not found ``` To add to the mystery, the contents of the directory are marked as modified. ``` $ svn status type A + type M + type/IntegerType.java M + type/BooleanType.java M + type/Type.java M + type/RationalRangeType.java M + type/RationalType.java M + type/IntegerRangeType.java ``` If I try to update from within the directory, I get this. ``` $ cd type $ svn update svn: Two top-level reports with no target ``` Committing from within the directory gives the same `path not found` error as above. What's going on and how do I fix it? EDIT: @Rob Oxspring caught me out: I got too aggressive moving things around in Eclipse. UPDATE: I'm accepting @Rob Oxspring's answer of "don't do that/just start over" and taking his advice. I'd still be interested if anybody could tell me: (a) what the above error messages *mean* precisely and (b) how to actually *fix* the problem.
It looks to me like `type` was created by some Subversion-aware copy command, then moved into the current directory using a Subversion-unaware copy. In my experience, this sort of thing typically occurs when package refactoring operations have been chained together in Eclipse without commits in between. Typically, Subversion doesn't handle it well when you copy/move a locally copied/moved file or folder, although I think version 1.5 may handle it better. To avoid this in the future, commit between such steps. If you'd like to hide the intervening commits then I'd recommend doing the multi-step refactoring on a branch and then merging the changes back into the mainline in that single commit you were after. If it's not too much work, then I'd recommend getting back to a clean working copy and redoing your changes, committing after each step. If you're happy to lose the history, i.e. allowing the new `IntegerType.java` to not be linked at all to the old `IntegerType.java`, then you could take the approach suggested by BCS: * Move your changed files into some temporary location, stripping out any `.svn` directories * Update your working copy into a clean working state * Copy your changes back to where you want them to be * Commit the resulting working copy
47,045
<p>Printf got added to Java with the 1.5 release but I can't seem to find how to send the output to a string rather than a file (which is what sprintf does in C). Does anyone know how to do this? </p>
[ { "answer_id": 47049, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 10, "selected": true, "text": "<pre><code>// Store the formatted string in 'result'\nString result = String.format(\"%4d\", i * j);\n\n// Write the re...
2008/09/05
[ "https://Stackoverflow.com/questions/47045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4498/" ]
Printf got added to Java with the 1.5 release but I can't seem to find how to send the output to a string rather than a file (which is what sprintf does in C). Does anyone know how to do this?
``` // Store the formatted string in 'result' String result = String.format("%4d", i * j); // Write the result to standard output System.out.println( result ); ``` See [format](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format(java.lang.String,%20java.lang.Object...)) and its [syntax](http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax)
47,052
<p>I'm looking to convert a SQL like statement on the fly to the equivalent regex i.e. </p> <pre><code>LIKE '%this%' LIKE 'Sm_th' LIKE '[C-P]arsen' </code></pre> <p>What's the best approach to doing this?</p> <p>P.S. I'm looking to do this on the .Net Framework (C#).</p>
[ { "answer_id": 47075, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": -1, "selected": false, "text": "<p>I found a Perl module called <a href=\"http://search.cpan.org/dist/Regexp-Wildcards/lib/Regexp/Wildcards.pm\" rel=\...
2008/09/05
[ "https://Stackoverflow.com/questions/47052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4843/" ]
I'm looking to convert a SQL like statement on the fly to the equivalent regex i.e. ``` LIKE '%this%' LIKE 'Sm_th' LIKE '[C-P]arsen' ``` What's the best approach to doing this? P.S. I'm looking to do this on the .Net Framework (C#).
The following Regex converts an SQL like pattern into a Regex pattern with the help of a [`MatchEvaluator`](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator.aspx) delegate. It correctly handles square bracket blocks and escapes special Regex characters. ``` string regexPattern = "^" + Regex.Replace( likePattern, @"[%_]|\[[^]]*\]|[^%_[]+", match => { if (match.Value == "%") { return ".*"; } if (match.Value == "_") { return "."; } if (match.Value.StartsWith("[") && match.Value.EndsWith("]")) { return match.Value; } return Regex.Escape(match.Value); }) + "$"; ```
47,066
<p>I am writing a C program in Linux. Commands like execv() require a path in the form of a C string. Is there a command that will return the current path in the form of a C-style string?</p>
[ { "answer_id": 47071, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 5, "selected": true, "text": "<p><a href=\"http://www.opengroup.org/onlinepubs/009695399/functions/getcwd.html\" rel=\"nofollow noreferrer\">getcwd()<...
2008/09/05
[ "https://Stackoverflow.com/questions/47066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/159/" ]
I am writing a C program in Linux. Commands like execv() require a path in the form of a C string. Is there a command that will return the current path in the form of a C-style string?
[getcwd()](http://www.opengroup.org/onlinepubs/009695399/functions/getcwd.html): > > ### *SYNOPSIS* > > > > ``` > #include <unistd.h> > > char *getcwd(char *buf, size_t size); > > ``` > > ### *DESCRIPTION* > > > The *getcwd()* function shall place an absolute pathname of the current working directory in the array pointed to by *buf, and return buf*. The pathname copied to the array shall contain no components that are symbolic links. The *size* argument is the size in bytes of the character array pointed to by the *buf* argument. If *buf* is a null pointer, the behavior of getcwd() is unspecified. > > > ### *RETURN VALUE* > > > Upon successful completion, *getcwd()* shall return the *buf* argument. Otherwise, *getcwd()* shall return a null pointer and set *errno* to indicate the error. The contents of the array pointed to by *buf* are then undefined.... > > >
47,078
<p>We are currently using the ExtJS tree view in an application - a requirement has arisen requiring a user to select multiple nodes (which the tree view supports currently through a pluggable selection model) - but you can not then drag the multiple selections to another part of the tree.</p> <p>Does anyone know of an ajax control (commercial or non-commercial) that supports multiple-selection drag / drop - or a example of enabling this functionality in ExtJS?</p>
[ { "answer_id": 48901, "author": "Candidasa", "author_id": 5010, "author_profile": "https://Stackoverflow.com/users/5010", "pm_score": 2, "selected": false, "text": "<p>Check out this post in the ExtJS forum that details how you can enable multi-select in a Javascript tree.</p>\n\n<p><a h...
2008/09/05
[ "https://Stackoverflow.com/questions/47078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4843/" ]
We are currently using the ExtJS tree view in an application - a requirement has arisen requiring a user to select multiple nodes (which the tree view supports currently through a pluggable selection model) - but you can not then drag the multiple selections to another part of the tree. Does anyone know of an ajax control (commercial or non-commercial) that supports multiple-selection drag / drop - or a example of enabling this functionality in ExtJS?
Got the same issue. I just found the solution : ``` ..new Ext.tree.TreePanel({ ... selModel : new Ext.tree.MultiSelectionModel() ... }) ```
47,089
<p>About 6 months ago I rolled out a site where every request needed to be over https. The only way at the time I could find to ensure that every request to a page was over https was to check it in the page load event. If the request was not over http I would response.redirect("<a href="https://example.com" rel="noreferrer">https://example.com</a>")</p> <p>Is there a better way -- ideally some setting in the web.config?</p>
[ { "answer_id": 47095, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 9, "selected": true, "text": "<p>Please use <a href=\"https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security\" rel=\"noreferrer\">HSTS</a> (HTTP St...
2008/09/05
[ "https://Stackoverflow.com/questions/47089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4846/" ]
About 6 months ago I rolled out a site where every request needed to be over https. The only way at the time I could find to ensure that every request to a page was over https was to check it in the page load event. If the request was not over http I would response.redirect("<https://example.com>") Is there a better way -- ideally some setting in the web.config?
Please use [HSTS](https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security) (HTTP Strict Transport Security) from <http://www.hanselman.com/blog/HowToEnableHTTPStrictTransportSecurityHSTSInIIS7.aspx> ``` <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <rules> <rule name="HTTP to HTTPS redirect" stopProcessing="true"> <match url="(.*)" /> <conditions> <add input="{HTTPS}" pattern="off" ignoreCase="true" /> </conditions> <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" /> </rule> </rules> <outboundRules> <rule name="Add Strict-Transport-Security when HTTPS" enabled="true"> <match serverVariable="RESPONSE_Strict_Transport_Security" pattern=".*" /> <conditions> <add input="{HTTPS}" pattern="on" ignoreCase="true" /> </conditions> <action type="Rewrite" value="max-age=31536000" /> </rule> </outboundRules> </rewrite> </system.webServer> </configuration> ``` **Original Answer** (replaced with the above on 4 December 2015) basically ``` protected void Application_BeginRequest(Object sender, EventArgs e) { if (HttpContext.Current.Request.IsSecureConnection.Equals(false) && HttpContext.Current.Request.IsLocal.Equals(false)) { Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"] + HttpContext.Current.Request.RawUrl); } } ``` that would go in the global.asax.cs (or global.asax.vb) i dont know of a way to specify it in the web.config
47,104
<p>Can anyone explain this behavior or how to get around it?</p> <p>If you execute this query:</p> <pre><code>select * from TblA left join freetexttable ( TblB, *, 'query' ) on TblA.ID = [Key] inner join DifferentDbCatalog.dbo.TblC on TblA.ID = TblC.TblAID </code></pre> <p>It will be very very very slow.</p> <p>If you change that query to use two inner joins instead of a left join, it will be very fast. If you change it to use two left joins instead of an inner join, it will be very fast.</p> <p>You can observe this same behavior if you use a sql table variable instead of the freetexttable as well. </p> <p>The performance problem arises any time you have a table variable (or freetexttable) and a table in a different database catalog where one is in an inner join and the other is in a left join.</p> <p>Does anyone know why this is slow, or how to speed it up?</p>
[ { "answer_id": 47109, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Index the field you use to perform the join.</p>\n\n<p>A good rule of thumb is to assign an index to any commonly referenced...
2008/09/05
[ "https://Stackoverflow.com/questions/47104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4407/" ]
Can anyone explain this behavior or how to get around it? If you execute this query: ``` select * from TblA left join freetexttable ( TblB, *, 'query' ) on TblA.ID = [Key] inner join DifferentDbCatalog.dbo.TblC on TblA.ID = TblC.TblAID ``` It will be very very very slow. If you change that query to use two inner joins instead of a left join, it will be very fast. If you change it to use two left joins instead of an inner join, it will be very fast. You can observe this same behavior if you use a sql table variable instead of the freetexttable as well. The performance problem arises any time you have a table variable (or freetexttable) and a table in a different database catalog where one is in an inner join and the other is in a left join. Does anyone know why this is slow, or how to speed it up?
A general rule of thumb is that OUTER JOINs cause the number of rows in a result set to *increase,* while INNER JOINs cause the number of rows in a result set to *decrease.* Of course, there are plenty of scenarios where the opposite is true as well, but it's more likely to work this way than not. What you want to do for performance is keep the size of the result set (working set) as small as possible for as long as possible. Since both joins match on the first table, changing up the order won't effect the accuracy of the results. Therefore, you probably want to do the INNER JOIN before the LEFT JOIN: ``` SELECT * FROM TblA INNER JOIN DifferentDbCatalog.dbo.TblC on TblA.ID = TblC.TblAID LEFT JOIN freetexttable ( TblB, *, 'query' ) on TblA.ID = [Key] ``` As a practical matter, the query optimizer *should* be smart enough to compile to use the faster option, regardless of which order you specified for the joins. However, it's good practice to pretend that you have a dumb query optimizer, and that query operations happen in order. This helps future maintainers spot potential errors or assumptions about the nature of the tables. Because the optimizer should re-write things, this probably isn't good enough to fully explain the behavior you're seeing, so you'll still want to *examine the execution plan* used for each query, and probably add an index as suggested earlier. This is still a good principle to learn, though.
47,107
<p>Is there a way to disallow publishing of debug builds with ClickOnce?</p> <p>I only want to allow release builds through, but right now human error causes a debug build to slip through once in a while. </p> <p>We're publishing the build from within Visual Studio.</p>
[ { "answer_id": 865822, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 3, "selected": false, "text": "<p>One thing you can do is add a condition to the .csproj or .vbproj file that MSBuild will check when doing a b...
2008/09/05
[ "https://Stackoverflow.com/questions/47107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3641/" ]
Is there a way to disallow publishing of debug builds with ClickOnce? I only want to allow release builds through, but right now human error causes a debug build to slip through once in a while. We're publishing the build from within Visual Studio.
I have started to modify the .csproj files to include the following code to throw an error for debug deploys, effectively preventing the deploy from happening: ``` <!-- The following makes sure we don’t try to publish a configuration that defines the DEBUG constant --> <Target Name="BeforePublish"> <Error Condition="'$(DebugSymbols)' == 'true'" Text="You attempted to publish a configuration that defines the DEBUG constant!" /> </Target> ``` Just place it at the end of the file, right before the `</Project>` tag. (original source: <http://www.nathanpjones.com/wp/2010/05/preventing-clickonce-publishing-a-debug-configuration/comment-page-1/#comment-625>)
47,144
<p>In my C# program, I have a thread that represents a running test, which can be aborted by a click on a button labeled "Interrupt execution". In order for the thread (and therefore the test) to terminate in an elegant manner (and do some vital work beforehand), this button is enabled only in some well-defined moments, in which I catch <code>ThreadAbortedException</code>, do <code>Thread.ResetAbort()</code> and die beautifully (that is, the thread).</p> <p>The problem is that, in the time window in which aborting is possible, there are some tasks that need to be done from start to finish once initiated, and, so, I fear TAE. Locks don't provide a solution for this, and, although finally blocks do, I don't find it elegant to wrap important code in the following manner:</p> <pre><code>try { } finally { // vital code } </code></pre> <p>However, I didn't find any other solution.</p> <p>Is this another way to delay the interference of <code>ThreadAbortException</code> until the end of the block?</p>
[ { "answer_id": 47147, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 3, "selected": true, "text": "<p>The situations under which a ThreadAbortException will be generated can be complex. A better option might be to ask why ...
2008/09/06
[ "https://Stackoverflow.com/questions/47144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4850/" ]
In my C# program, I have a thread that represents a running test, which can be aborted by a click on a button labeled "Interrupt execution". In order for the thread (and therefore the test) to terminate in an elegant manner (and do some vital work beforehand), this button is enabled only in some well-defined moments, in which I catch `ThreadAbortedException`, do `Thread.ResetAbort()` and die beautifully (that is, the thread). The problem is that, in the time window in which aborting is possible, there are some tasks that need to be done from start to finish once initiated, and, so, I fear TAE. Locks don't provide a solution for this, and, although finally blocks do, I don't find it elegant to wrap important code in the following manner: ``` try { } finally { // vital code } ``` However, I didn't find any other solution. Is this another way to delay the interference of `ThreadAbortException` until the end of the block?
The situations under which a ThreadAbortException will be generated can be complex. A better option might be to ask why you are using ThreadAbortExceptions at all. A better pattern would be to simply use a flag to indicate to the running thread that it should abort, and then test the flag regularly while it is working. If it is set you can throw an exception at that point if you want. With this pattern you are totally in control of when the thread will act on the abort, and don't have to worry about the critical operations being interrupted.
47,169
<p>I'd like to enable/disable some other controls based on how many items are in my <code>ListView</code> control. I can't find any event that would do this, either on the <code>ListView</code> itself or on the <code>ListViewItemCollection</code>. Maybe there's a way to generically watch any collection in C# for changes?</p> <p>I'd be happy with other events too, even ones that sometimes fire when the items don't change, but for example the <code>ControlAdded</code> and <code>Layout</code> events didn't work :(.</p>
[ { "answer_id": 47178, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 0, "selected": false, "text": "<p>I can't find any events that you could use. Perhaps you could subclass ListViewItemCollection, and raise your own event wh...
2008/09/06
[ "https://Stackoverflow.com/questions/47169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3191/" ]
I'd like to enable/disable some other controls based on how many items are in my `ListView` control. I can't find any event that would do this, either on the `ListView` itself or on the `ListViewItemCollection`. Maybe there's a way to generically watch any collection in C# for changes? I'd be happy with other events too, even ones that sometimes fire when the items don't change, but for example the `ControlAdded` and `Layout` events didn't work :(.
@Domenic Not too sure, Never quite got that far in the thought process. Another solution might be to extend ListView, and when adding and removing stuff, instead of calling .items.add, and items.remove, you call your other functions. It would still be possible to add and remove without events being raised, but with a little code review to make sure .items.add and .items.remove weren't called directly, it could work out quite well. Here's a little example. I only showed 1 Add function, but there are 6 you would have to implement, if you wanted to have use of all the available add functions. There's also .AddRange, and .Clear that you might want to take a look at. ``` Public Class MonitoredListView Inherits ListView Public Event ItemAdded() Public Event ItemRemoved() Public Sub New() MyBase.New() End Sub Public Function AddItem(ByVal Text As String) As ListViewItem RaiseEvent ItemAdded() MyBase.Items.Add(Text) End Function Public Sub RemoveItem(ByVal Item As ListViewItem) RaiseEvent ItemRemoved() MyBase.Items.Remove(Item) End Sub End Class ```
47,207
<p>Can i print out a url <code>/admin/manage/products/add</code> of a certain view in a template?</p> <p>Here is the rule i want to create a link for</p> <pre><code>(r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), </code></pre> <p>I would like to have /manage/products/add in a template without hardcoding it. How can i do this?</p> <p><strong>Edit:</strong> I am not using the default admin (well, i am but it is at another url), this is my own</p>
[ { "answer_id": 47212, "author": "Peter Hoffmann", "author_id": 720, "author_profile": "https://Stackoverflow.com/users/720", "pm_score": 2, "selected": false, "text": "<p>If you use <a href=\"https://docs.djangoproject.com/en/1.2/topics/http/urls/#naming-url-patterns\" rel=\"nofollow nor...
2008/09/06
[ "https://Stackoverflow.com/questions/47207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2592/" ]
Can i print out a url `/admin/manage/products/add` of a certain view in a template? Here is the rule i want to create a link for ``` (r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), ``` I would like to have /manage/products/add in a template without hardcoding it. How can i do this? **Edit:** I am not using the default admin (well, i am but it is at another url), this is my own
You can use `get_absolute_url`, but that will only work for a particular object. Since your object hasn't been created yet, it won't work in this case. You want to use [named URL patterns](https://docs.djangoproject.com/en/1.2/topics/http/urls/#naming-url-patterns). Here's a quick intro: Change the line in your urls.py to: ``` (r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}, "create-product"), ``` Then, in your template you use this to display the URL: ``` {% url create-product %} ``` If you're using Django 1.5 or higher you need this: ``` {% url 'create-product' %} ``` You can do some more powerful things with named URL patterns, they're very handy. Note that they are only in the development version (and also 1.0).
47,239
<p>Does anyone know a way to auto-generate database tables for a given class? I'm not looking for an entire persistence layer - I already have a data access solution I'm using, but I suddenly have to store a lot of information from a large number of classes and I really don't want to have to create all these tables by hand. For example, given the following class:</p> <pre><code>class Foo { private string property1; public string Property1 { get { return property1; } set { property1 = value; } } private int property2; public int Property2 { get { return property2; } set { property2 = value; } } } </code></pre> <p>I'd expect the following SQL:</p> <pre><code>CREATE TABLE Foo ( Property1 VARCHAR(500), Property2 INT ) </code></pre> <p>I'm also wondering how you could handle complex types. For example, in the previously cited class, if we changed that to be :</p> <pre><code>class Foo { private string property1; public string Property1 { get { return property1; } set { property1 = value; } } private System.Management.ManagementObject property2; public System.Management.ManagementObject Property2 { get { return property2; } set { property2 = value; } } } </code></pre> <p></p> <p>How could I handle this?</p> <p>I've looked at trying to auto-generate the database scripts by myself using reflection to enumerate through each class' properties, but it's clunky and the complex data types have me stumped.</p>
[ { "answer_id": 47251, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "<p>For complex types, you can recursively convert each one that you come across into a table of its own and then attempt ...
2008/09/06
[ "https://Stackoverflow.com/questions/47239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4550/" ]
Does anyone know a way to auto-generate database tables for a given class? I'm not looking for an entire persistence layer - I already have a data access solution I'm using, but I suddenly have to store a lot of information from a large number of classes and I really don't want to have to create all these tables by hand. For example, given the following class: ``` class Foo { private string property1; public string Property1 { get { return property1; } set { property1 = value; } } private int property2; public int Property2 { get { return property2; } set { property2 = value; } } } ``` I'd expect the following SQL: ``` CREATE TABLE Foo ( Property1 VARCHAR(500), Property2 INT ) ``` I'm also wondering how you could handle complex types. For example, in the previously cited class, if we changed that to be : ``` class Foo { private string property1; public string Property1 { get { return property1; } set { property1 = value; } } private System.Management.ManagementObject property2; public System.Management.ManagementObject Property2 { get { return property2; } set { property2 = value; } } } ``` How could I handle this? I've looked at trying to auto-generate the database scripts by myself using reflection to enumerate through each class' properties, but it's clunky and the complex data types have me stumped.
It's really late, and I only spent about 10 minutes on this, so its extremely sloppy, however it does work and will give you a good jumping off point: ``` using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace TableGenerator { class Program { static void Main(string[] args) { List<TableClass> tables = new List<TableClass>(); // Pass assembly name via argument Assembly a = Assembly.LoadFile(args[0]); Type[] types = a.GetTypes(); // Get Types in the assembly. foreach (Type t in types) { TableClass tc = new TableClass(t); tables.Add(tc); } // Create SQL for each table foreach (TableClass table in tables) { Console.WriteLine(table.CreateTableScript()); Console.WriteLine(); } // Total Hacked way to find FK relationships! Too lazy to fix right now foreach (TableClass table in tables) { foreach (KeyValuePair<String, Type> field in table.Fields) { foreach (TableClass t2 in tables) { if (field.Value.Name == t2.ClassName) { // We have a FK Relationship! Console.WriteLine("GO"); Console.WriteLine("ALTER TABLE " + table.ClassName + " WITH NOCHECK"); Console.WriteLine("ADD CONSTRAINT FK_" + field.Key + " FOREIGN KEY (" + field.Key + ") REFERENCES " + t2.ClassName + "(ID)"); Console.WriteLine("GO"); } } } } } } public class TableClass { private List<KeyValuePair<String, Type>> _fieldInfo = new List<KeyValuePair<String, Type>>(); private string _className = String.Empty; private Dictionary<Type, String> dataMapper { get { // Add the rest of your CLR Types to SQL Types mapping here Dictionary<Type, String> dataMapper = new Dictionary<Type, string>(); dataMapper.Add(typeof(int), "BIGINT"); dataMapper.Add(typeof(string), "NVARCHAR(500)"); dataMapper.Add(typeof(bool), "BIT"); dataMapper.Add(typeof(DateTime), "DATETIME"); dataMapper.Add(typeof(float), "FLOAT"); dataMapper.Add(typeof(decimal), "DECIMAL(18,0)"); dataMapper.Add(typeof(Guid), "UNIQUEIDENTIFIER"); return dataMapper; } } public List<KeyValuePair<String, Type>> Fields { get { return this._fieldInfo; } set { this._fieldInfo = value; } } public string ClassName { get { return this._className; } set { this._className = value; } } public TableClass(Type t) { this._className = t.Name; foreach (PropertyInfo p in t.GetProperties()) { KeyValuePair<String, Type> field = new KeyValuePair<String, Type>(p.Name, p.PropertyType); this.Fields.Add(field); } } public string CreateTableScript() { System.Text.StringBuilder script = new StringBuilder(); script.AppendLine("CREATE TABLE " + this.ClassName); script.AppendLine("("); script.AppendLine("\t ID BIGINT,"); for (int i = 0; i < this.Fields.Count; i++) { KeyValuePair<String, Type> field = this.Fields[i]; if (dataMapper.ContainsKey(field.Value)) { script.Append("\t " + field.Key + " " + dataMapper[field.Value]); } else { // Complex Type? script.Append("\t " + field.Key + " BIGINT"); } if (i != this.Fields.Count - 1) { script.Append(","); } script.Append(Environment.NewLine); } script.AppendLine(")"); return script.ToString(); } } } ``` I put these classes in an assembly to test it: ``` public class FakeDataClass { public int AnInt { get; set; } public string AString { get; set; } public float AFloat { get; set; } public FKClass AFKReference { get; set; } } public class FKClass { public int AFKInt { get; set; } } ``` And it generated the following SQL: ``` CREATE TABLE FakeDataClass ( ID BIGINT, AnInt BIGINT, AString NVARCHAR(255), AFloat FLOAT, AFKReference BIGINT ) CREATE TABLE FKClass ( ID BIGINT, AFKInt BIGINT ) GO ALTER TABLE FakeDataClass WITH NOCHECK ADD CONSTRAINT FK_AFKReference FOREIGN KEY (AFKReference) REFERENCES FKClass(ID) GO ``` Some further thoughts...I'd consider adding an attribute such as [SqlTable] to your classes, that way it only generates tables for the classes you want. Also, this can be cleaned up a ton, bugs fixed, optimized (the FK Checker is a joke) etc etc...Just to get you started.