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
148,951
<p>I'm trying to use <code>mysqldump</code> to dump a schema, and it mostly works but I ran into one curiosity: the <code>-p</code> or <code>--password</code> option seems like it is doing something other than setting the password (as the <code>man</code> page and <code>--help</code> output say it should).</p> <p>Specifically, it looks like it's doing what is indicated here: <a href="http://snippets.dzone.com/posts/show/360" rel="noreferrer">http://snippets.dzone.com/posts/show/360</a> - that is, setting the database to dump.</p> <p>To support my somewhat outlandish claim, I can tell you that if I do not specify the <code>--password</code> (or <code>-p</code>) option, the command prints the usage statement and exits with an error. If I do specify it, I am immediately prompted to enter a password (!), and then the database specified in the <code>--password</code> option is dumped (or an error is given in the usual case that a password not matching any database name was specified).</p> <p>Here's a transcript:</p> <pre> $ mysqldump -u test -h myhost --no-data --tables --password lose Enter password: -- MySQL dump 10.10 mysqldump: Got error: 1044: Access denied for user 'test'@'%' to database 'lose' when selecting the database </pre> <p>So, what gives? Is this the way this is supposed to work? It surely does not appear to make sense nor does it match the official documentation. And finally, if this just the way it works, how am I meant to specify the password to be used in an automated job? Using <code>expect</code>???</p> <p>I'm using <code>mysqldump Ver 10.10 Distrib 5.0.22, for pc-linux-gnu (i486)</code>.</p>
[ { "answer_id": 148969, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 2, "selected": false, "text": "<p>Did you try --password=whatever-password-is ?</p>\n\n<p>Perhaps I'm missing the question, but that is what I do to run th...
2008/09/29
[ "https://Stackoverflow.com/questions/148951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4323/" ]
I'm trying to use `mysqldump` to dump a schema, and it mostly works but I ran into one curiosity: the `-p` or `--password` option seems like it is doing something other than setting the password (as the `man` page and `--help` output say it should). Specifically, it looks like it's doing what is indicated here: <http://snippets.dzone.com/posts/show/360> - that is, setting the database to dump. To support my somewhat outlandish claim, I can tell you that if I do not specify the `--password` (or `-p`) option, the command prints the usage statement and exits with an error. If I do specify it, I am immediately prompted to enter a password (!), and then the database specified in the `--password` option is dumped (or an error is given in the usual case that a password not matching any database name was specified). Here's a transcript: ``` $ mysqldump -u test -h myhost --no-data --tables --password lose Enter password: -- MySQL dump 10.10 mysqldump: Got error: 1044: Access denied for user 'test'@'%' to database 'lose' when selecting the database ``` So, what gives? Is this the way this is supposed to work? It surely does not appear to make sense nor does it match the official documentation. And finally, if this just the way it works, how am I meant to specify the password to be used in an automated job? Using `expect`??? I'm using `mysqldump Ver 10.10 Distrib 5.0.22, for pc-linux-gnu (i486)`.
From man mysqldump: > > --password[=password], -p[password] > > > The password to use when connecting to the server. If you use > the short option form (-p), you cannot have a space between the option > and the password. If you omit the password value following the > --password or -p option on the command line, you are prompted for > one. > > Specifying a password on the command line should be considered > insecure. See Section 6.6, "Keeping Your Password Secure". > > > Syntactically, you are not using the --password switch correctly. As such, the command line parser is seeing your use of "lose" as a stand-alone argument which mysqldump interprets as the database name as it would if you were to attempt a simpler command like `mysqldump lose` To correct this, try using `--password=lose` or `-plose` or simply use `-p` or `--password` and type the password when prompted.
148,955
<p>I want the 2 columns to touch ie. remove the margins, how can I do this?</p> <p>My code:</p> <pre><code> &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"&gt; &lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;testing&lt;/TITLE&gt; &lt;!-- css --&gt; &lt;link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.2/build/reset-fonts-grids/reset-fonts-grids.css"&gt; &lt;!-- js --&gt; &lt;script type="text/javascript" src="http://yui.yahooapis.com/combo?2.5.2/build/utilities/utilities.js"&gt;&lt;/script&gt; &lt;style&gt; .yui-b { background-color: #eeeeee; } &lt;/style&gt; &lt;/HEAD&gt; &lt;BODY&gt; &lt;div id="doc3" class="yui-t1"&gt; &lt;!-- change class to change preset --&gt; &lt;div id="hd"&gt;header&lt;/div&gt; &lt;div id="bd"&gt; &lt;div id="yui-main"&gt; &lt;div class="yui-b"&gt; bd.main &lt;/div&gt; &lt;/div&gt; &lt;div class="yui-b"&gt;bd.other&lt;/div&gt; &lt;/div&gt; &lt;div id="ft"&gt;footer&lt;/div&gt; &lt;/div&gt; &lt;/BODY&gt; &lt;/HTML&gt; </code></pre>
[ { "answer_id": 148973, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 1, "selected": false, "text": "<p>Add a class to the right column and set margin-left to 0. </p>\n\n<p>If that doesn't work you might have to i...
2008/09/29
[ "https://Stackoverflow.com/questions/148955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want the 2 columns to touch ie. remove the margins, how can I do this? My code: ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>testing</TITLE> <!-- css --> <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.2/build/reset-fonts-grids/reset-fonts-grids.css"> <!-- js --> <script type="text/javascript" src="http://yui.yahooapis.com/combo?2.5.2/build/utilities/utilities.js"></script> <style> .yui-b { background-color: #eeeeee; } </style> </HEAD> <BODY> <div id="doc3" class="yui-t1"> <!-- change class to change preset --> <div id="hd">header</div> <div id="bd"> <div id="yui-main"> <div class="yui-b"> bd.main </div> </div> <div class="yui-b">bd.other</div> </div> <div id="ft">footer</div> </div> </BODY> </HTML> ```
Add a class to the right column and set margin-left to 0. If that doesn't work you might have to increase the width by 1 or 2%. You can use firebug to check the applied styles and change them on the fly.
148,982
<p>I have a function that passes an array to another function as an argument, there will be multiple data types in this array but I want to know how to pass a function or a reference to a function so the other function can call it at any time.</p> <p>ex.</p> <p>function A:</p> <pre><code>add(new Array("hello", some function)); </code></pre> <p>function B:</p> <pre><code>public function b(args:Array) { var myString = args[0]; var myFunc = args[1]; } </code></pre>
[ { "answer_id": 148990, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 3, "selected": false, "text": "<p>This is very easy in ActionScript:</p>\n\n<pre><code>function someFunction(foo, bar) {\n ...\n}\n\nfunction a() {\n b...
2008/09/29
[ "https://Stackoverflow.com/questions/148982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a function that passes an array to another function as an argument, there will be multiple data types in this array but I want to know how to pass a function or a reference to a function so the other function can call it at any time. ex. function A: ``` add(new Array("hello", some function)); ``` function B: ``` public function b(args:Array) { var myString = args[0]; var myFunc = args[1]; } ```
Simply pass the function name as an argument, no, just like in AS2 or JavaScript? ``` function functionToPass() { } function otherFunction( f:Function ) { // passed-in function available here f(); } otherFunction( functionToPass ); ```
148,988
<p>I need to create an XML schema that validates a tree structure of an XML document. I don't know exactly the occurrences or depth level of the tree.</p> <p>XML example:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;node&gt; &lt;attribute/&gt; &lt;node&gt; &lt;attribute/&gt; &lt;node/&gt; &lt;/node&gt; &lt;/node&gt; </code></pre> <p>Which is the best way to validate it? Recursion?</p>
[ { "answer_id": 149003, "author": "Michael Brown", "author_id": 14359, "author_profile": "https://Stackoverflow.com/users/14359", "pm_score": 5, "selected": false, "text": "<p>XSD does indeed allow for recursion of elements. Here <a href=\"https://web.archive.org/web/20140421153734/http:/...
2008/09/29
[ "https://Stackoverflow.com/questions/148988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19012/" ]
I need to create an XML schema that validates a tree structure of an XML document. I don't know exactly the occurrences or depth level of the tree. XML example: ``` <?xml version="1.0" encoding="utf-8"?> <node> <attribute/> <node> <attribute/> <node/> </node> </node> ``` Which is the best way to validate it? Recursion?
if you need a recursive type declaration, here is an example that might help: ``` <xs:schema id="XMLSchema1" targetNamespace="http://tempuri.org/XMLSchema1.xsd" elementFormDefault="qualified" xmlns="http://tempuri.org/XMLSchema1.xsd" xmlns:mstns="http://tempuri.org/XMLSchema1.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" > <xs:element name="node" type="nodeType"></xs:element> <xs:complexType name="nodeType"> <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:element name="node" type="nodeType"></xs:element> </xs:sequence> </xs:complexType> </xs:schema> ``` As you can see, this defines a recursive schema with only one node named "node" which can be as deep as desired.
149,008
<p>I have an object that I'm testing that raises an event. What is the best way of using Rhino Mocks to check that it was raised? </p> <p>Best I could come up with (I am certain it gets better than this):</p> <pre><code>public void MyCallback(object sender, EventArgs e) { _flag = true;} [Test] public void DoSomethingRaisesEvent() { _flag = false; using(_mocks.Record()) { Expect.Call(delegeate { _obj.DoSomething();}); } using(_mocks.Playback()) { _obj = new SomethingDoer(); _obj.SomethingWasDoneEvent += new EventHandler(MyHandler); Assert.IsTrue(_flag); } } </code></pre>
[ { "answer_id": 149077, "author": "casademora", "author_id": 5619, "author_profile": "https://Stackoverflow.com/users/5619", "pm_score": 0, "selected": false, "text": "<p>I'm not sure how your test actually calls the DoSomething() Method. Maybe you're missing something to fire the event. ...
2008/09/29
[ "https://Stackoverflow.com/questions/149008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
I have an object that I'm testing that raises an event. What is the best way of using Rhino Mocks to check that it was raised? Best I could come up with (I am certain it gets better than this): ``` public void MyCallback(object sender, EventArgs e) { _flag = true;} [Test] public void DoSomethingRaisesEvent() { _flag = false; using(_mocks.Record()) { Expect.Call(delegeate { _obj.DoSomething();}); } using(_mocks.Playback()) { _obj = new SomethingDoer(); _obj.SomethingWasDoneEvent += new EventHandler(MyHandler); Assert.IsTrue(_flag); } } ```
I found [this article by Phil Haack on how to test events using anonymous delegates](http://haacked.com/archive/2006/12/13/tip_jar_unit_test_events_with_anonymous_delegates.aspx) Here is the code, ripped directly from his blog for those too lazy to click through: ``` [Test] public void SettingValueRaisesEvent() { bool eventRaised = false; Parameter param = new Parameter("num", "int", "1"); param.ValueChanged += delegate(object sender, ValueChangedEventArgs e) { Assert.AreEqual("42", e.NewValue); Assert.AreEqual("1", e.OldValue); Assert.AreEqual("num", e.ParameterName); eventRaised = true; }; param.Value = "42"; //should fire event. Assert.IsTrue(eventRaised, "Event was not raised"); } ```
149,037
<p><P>How can I instantiate a JMS queue listener in java (JRE /JDK / J2EE 1.4) that only receives messages that match a given JMSCorrelationID? The messages that I'm looking to pick up have been published to a queue and not a topic, although that can change if needed.</P> Here's the code that I'm currently using to put the message in the queue:</p> <pre><code>/** * publishResponseToQueue publishes Requests to the Queue. * * @param jmsQueueFactory -Name of the queue-connection-factory * @param jmsQueue -The queue name for the request * @param response -A response object that needs to be published * * @throws ServiceLocatorException -An exception if a request message * could not be published to the Topic */ private void publishResponseToQueue( String jmsQueueFactory, String jmsQueue, Response response ) throws ServiceLocatorException { if ( logger.isInfoEnabled() ) { logger.info( "Begin publishRequestToQueue: " + jmsQueueFactory + "," + jmsQueue + "," + response ); } logger.assertLog( jmsQueue != null &amp;&amp; !jmsQueue.equals(""), "jmsQueue cannot be null" ); logger.assertLog( jmsQueueFactory != null &amp;&amp; !jmsQueueFactory.equals(""), "jmsQueueFactory cannot be null" ); logger.assertLog( response != null, "Request cannot be null" ); try { Queue queue = (Queue)_context.lookup( jmsQueue ); QueueConnectionFactory factory = (QueueConnectionFactory) _context.lookup( jmsQueueFactory ); QueueConnection connection = factory.createQueueConnection(); connection.start(); QueueSession session = connection.createQueueSession( false, QueueSession.AUTO_ACKNOWLEDGE ); ObjectMessage objectMessage = session.createObjectMessage(); objectMessage.setJMSCorrelationID(response.getID()); objectMessage.setObject( response ); session.createSender( queue ).send( objectMessage ); session.close(); connection.close(); } catch ( Exception e ) { //XC3.2 Added/Modified BEGIN logger.error( "ServiceLocator.publishResponseToQueue - Could not publish the " + "Response to the Queue - " + e.getMessage() ); throw new ServiceLocatorException( "ServiceLocator.publishResponseToQueue " + "- Could not publish the " + "Response to the Queue - " + e.getMessage() ); //XC3.2 Added/Modified END } if ( logger.isInfoEnabled() ) { logger.info( "End publishResponseToQueue: " + jmsQueueFactory + "," + jmsQueue + response ); } } // end of publishResponseToQueue method </code></pre>
[ { "answer_id": 149167, "author": "Robin", "author_id": 21925, "author_profile": "https://Stackoverflow.com/users/21925", "pm_score": 5, "selected": true, "text": "<p>The queue connection setup is the same, but once you have the QueueSession, you set the selector when creating a receiver....
2008/09/29
[ "https://Stackoverflow.com/questions/149037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/231627/" ]
How can I instantiate a JMS queue listener in java (JRE /JDK / J2EE 1.4) that only receives messages that match a given JMSCorrelationID? The messages that I'm looking to pick up have been published to a queue and not a topic, although that can change if needed. Here's the code that I'm currently using to put the message in the queue: ``` /** * publishResponseToQueue publishes Requests to the Queue. * * @param jmsQueueFactory -Name of the queue-connection-factory * @param jmsQueue -The queue name for the request * @param response -A response object that needs to be published * * @throws ServiceLocatorException -An exception if a request message * could not be published to the Topic */ private void publishResponseToQueue( String jmsQueueFactory, String jmsQueue, Response response ) throws ServiceLocatorException { if ( logger.isInfoEnabled() ) { logger.info( "Begin publishRequestToQueue: " + jmsQueueFactory + "," + jmsQueue + "," + response ); } logger.assertLog( jmsQueue != null && !jmsQueue.equals(""), "jmsQueue cannot be null" ); logger.assertLog( jmsQueueFactory != null && !jmsQueueFactory.equals(""), "jmsQueueFactory cannot be null" ); logger.assertLog( response != null, "Request cannot be null" ); try { Queue queue = (Queue)_context.lookup( jmsQueue ); QueueConnectionFactory factory = (QueueConnectionFactory) _context.lookup( jmsQueueFactory ); QueueConnection connection = factory.createQueueConnection(); connection.start(); QueueSession session = connection.createQueueSession( false, QueueSession.AUTO_ACKNOWLEDGE ); ObjectMessage objectMessage = session.createObjectMessage(); objectMessage.setJMSCorrelationID(response.getID()); objectMessage.setObject( response ); session.createSender( queue ).send( objectMessage ); session.close(); connection.close(); } catch ( Exception e ) { //XC3.2 Added/Modified BEGIN logger.error( "ServiceLocator.publishResponseToQueue - Could not publish the " + "Response to the Queue - " + e.getMessage() ); throw new ServiceLocatorException( "ServiceLocator.publishResponseToQueue " + "- Could not publish the " + "Response to the Queue - " + e.getMessage() ); //XC3.2 Added/Modified END } if ( logger.isInfoEnabled() ) { logger.info( "End publishResponseToQueue: " + jmsQueueFactory + "," + jmsQueue + response ); } } // end of publishResponseToQueue method ```
The queue connection setup is the same, but once you have the QueueSession, you set the selector when creating a receiver. ``` QueueReceiver receiver = session.createReceiver(myQueue, "JMSCorrelationID='theid'"); ``` then ``` receiver.receive() ``` or ``` receiver.setListener(myListener); ```
149,040
<p>Assume the following:</p> <p><em>models.py</em></p> <pre><code>class Entry(models.Model): title = models.CharField(max_length=50) slug = models.CharField(max_length=50, unique=True) body = models.CharField(max_length=200) </code></pre> <p><em>admin.py</em></p> <pre><code>class EntryAdmin(admin.ModelAdmin): prepopulated_fields = {'slug':('title',)} </code></pre> <p>I want the slug to be pre-populated by the title, but I dont want the user to be able to edit it from the admin. I assumed that adding the fields=[] to the admin object and not including the slug would have worked, but it didnt. I also tried setting editable=False in the model, but that also didnt work (infact, stops the page from rendering).</p> <p>Thoughts? </p>
[ { "answer_id": 149067, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 0, "selected": false, "text": "<p>I'm not sure what you're asking for IS possible. Your best bet is probably to hide the slug from the admin interfa...
2008/09/29
[ "https://Stackoverflow.com/questions/149040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22306/" ]
Assume the following: *models.py* ``` class Entry(models.Model): title = models.CharField(max_length=50) slug = models.CharField(max_length=50, unique=True) body = models.CharField(max_length=200) ``` *admin.py* ``` class EntryAdmin(admin.ModelAdmin): prepopulated_fields = {'slug':('title',)} ``` I want the slug to be pre-populated by the title, but I dont want the user to be able to edit it from the admin. I assumed that adding the fields=[] to the admin object and not including the slug would have worked, but it didnt. I also tried setting editable=False in the model, but that also didnt work (infact, stops the page from rendering). Thoughts?
For this particular case you can override your save method to slugify (it's built-in method, look at django source) the title and store it in slug field. Also from there you can easily check if this slug is indeed unique and change it somehow if it's not. Consider this example: ``` def save(self): from django.template.defaultfilters import slugify if not self.slug: self.slug = slugify(self.title) super(Your_Model_Name,self).save() ```
149,055
<p>I would like to format a price in JavaScript. I'd like a function which takes a <code>float</code> as an argument and returns a <code>string</code> formatted like this:</p> <pre><code>&quot;$ 2,500.00&quot; </code></pre> <p>How can I do this?</p>
[ { "answer_id": 149080, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 5, "selected": false, "text": "<p>The main part is inserting the thousand-separators, and that could be done like this:</p>\n<pre><code>&lt;script type=...
2008/09/29
[ "https://Stackoverflow.com/questions/149055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3314/" ]
I would like to format a price in JavaScript. I'd like a function which takes a `float` as an argument and returns a `string` formatted like this: ``` "$ 2,500.00" ``` How can I do this?
Ok, based on what you said, I'm using this: ``` var DecimalSeparator = Number("1.2").toLocaleString().substr(1,1); var AmountWithCommas = Amount.toLocaleString(); var arParts = String(AmountWithCommas).split(DecimalSeparator); var intPart = arParts[0]; var decPart = (arParts.length > 1 ? arParts[1] : ''); decPart = (decPart + '00').substr(0,2); return '£ ' + intPart + DecimalSeparator + decPart; ``` I'm open to improvement suggestions (I'd prefer not to include [YUI](https://en.wikipedia.org/wiki/Yahoo!_UI_Library) just to do this :-) ) I already know I should be detecting the "." instead of just using it as the decimal separator...
149,057
<p>How can you remove all of the trailing whitespace of an entire project? Starting at a root directory, and removing the trailing whitespace from all files in all folders.</p> <p>Also, I want to to be able to modify the file directly, and not just print everything to stdout.</p>
[ { "answer_id": 149070, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 5, "selected": false, "text": "<p>In Bash:</p>\n\n<p><code>find dir -type f -exec sed -i 's/ *$//' '{}' ';'</code></p>\n\n<p>Note: If you're using ...
2008/09/29
[ "https://Stackoverflow.com/questions/149057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19718/" ]
How can you remove all of the trailing whitespace of an entire project? Starting at a root directory, and removing the trailing whitespace from all files in all folders. Also, I want to to be able to modify the file directly, and not just print everything to stdout.
Here is an OS X >= 10.6 Snow Leopard solution. **It Ignores .git and .svn folders** and their contents. Also it won't leave a backup file. ``` (export LANG=C LC_CTYPE=C find . -not \( -name .svn -prune -o -name .git -prune \) -type f -print0 | perl -0ne 'print if -T' | xargs -0 sed -Ei 's/[[:blank:]]+$//' ) ``` The enclosing parenthesis preserves the `L*` variables of current shell – executing in subshell.
149,073
<p>I want to see the stack trace in any function of my code, so i made somthing like this to call it and print the stack trace:</p> <pre><code>public function PrintStackTrace() { try { throw new Error('StackTrace'); } catch (e:Error) { trace(e.getStackTrace()); } } </code></pre> <p>I like to know if there are other way to do this. In some place, the Error class creates the stack trace, but maybe it didn't do it with ActionScript 3.0 so maybe it's not posible, but i want to know.</p> <p>Thanks!</p>
[ { "answer_id": 149188, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 7, "selected": true, "text": "<p>As far as I know, the only way to make the stack trace available to your own code is via the <a href=\"http://livedocs.adob...
2008/09/29
[ "https://Stackoverflow.com/questions/149073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20601/" ]
I want to see the stack trace in any function of my code, so i made somthing like this to call it and print the stack trace: ``` public function PrintStackTrace() { try { throw new Error('StackTrace'); } catch (e:Error) { trace(e.getStackTrace()); } } ``` I like to know if there are other way to do this. In some place, the Error class creates the stack trace, but maybe it didn't do it with ActionScript 3.0 so maybe it's not posible, but i want to know. Thanks!
As far as I know, the only way to make the stack trace available to your own code is via the [getStackTrace()](http://livedocs.adobe.com/flex/3/langref/Error.html#getStackTrace()) method in the Error class, just like you're already doing. In response to the example in your question, though, I would mention that you don't actually have to throw the Error -- you can just create it and call the method on it: ``` var tempError:Error = new Error(); var stackTrace:String = tempError.getStackTrace(); ``` Also, like the documentation says, this only works in the debug version of Flash Player, so you can wrap this functionality in an if-block that checks the value of [Capabilities.isDebugger](http://livedocs.adobe.com/flex/3/langref/flash/system/Capabilities.html#isDebugger) if you want.
149,078
<p>Suppose I have a database table with two fields, "foo" and "bar". Neither of them are unique, but each of them are indexed. However, rather than being indexed together, they each have a separate index.</p> <p>Now suppose I perform a query such as <code>SELECT * FROM sometable WHERE foo='hello' AND bar='world';</code> My table a huge number of rows for which foo is 'hello' and a small number of rows for which bar is 'world'.</p> <p>So the most efficient thing for the database server to do under the hood is use the bar index to find all fields where bar is 'world', then return only those rows for which foo is 'hello'. This is <code>O(n)</code> where n is the number of rows where bar is 'world'.</p> <p>However, I imagine it's possible that the process would happen in reverse, where the fo index was used and the results searched. This would be <code>O(m)</code> where m is the number of rows where foo is 'hello'.</p> <p>So is Oracle smart enough to search efficiently here? What about other databases? Or is there some way I can tell it in my query to search in the proper order? Perhaps by putting <code>bar='world'</code> first in the <code>WHERE</code> clause?</p>
[ { "answer_id": 149104, "author": "Georgi", "author_id": 13209, "author_profile": "https://Stackoverflow.com/users/13209", "pm_score": 2, "selected": false, "text": "<p>Yes, you can give \"hints\" with the query to Oracle. These hints are disguised as comments (\"/* HINT */\") to the data...
2008/09/29
[ "https://Stackoverflow.com/questions/149078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1694/" ]
Suppose I have a database table with two fields, "foo" and "bar". Neither of them are unique, but each of them are indexed. However, rather than being indexed together, they each have a separate index. Now suppose I perform a query such as `SELECT * FROM sometable WHERE foo='hello' AND bar='world';` My table a huge number of rows for which foo is 'hello' and a small number of rows for which bar is 'world'. So the most efficient thing for the database server to do under the hood is use the bar index to find all fields where bar is 'world', then return only those rows for which foo is 'hello'. This is `O(n)` where n is the number of rows where bar is 'world'. However, I imagine it's possible that the process would happen in reverse, where the fo index was used and the results searched. This would be `O(m)` where m is the number of rows where foo is 'hello'. So is Oracle smart enough to search efficiently here? What about other databases? Or is there some way I can tell it in my query to search in the proper order? Perhaps by putting `bar='world'` first in the `WHERE` clause?
Oracle will almost certainly use the most selective index to drive the query, and you can check that with the explain plan. Furthermore, Oracle can combine the use of both indexes in a couple of ways -- it can convert btree indexes to bitmaps and perform a bitmap ANd operation on them, or it can perform a hash join on the rowid's returned by the two indexes. One important consideration here might be any correlation between the values being queried. If foo='hello' accounts for 80% of values in the table and bar='world' accounts for 10%, then Oracle is going to estimate that the query will return 0.8\*0.1= 8% of the table rows. However this may not be correct - the query may actually return 10% of the rwos or even 0% of the rows depending on how correlated the values are. Now, depending on the distribution of those rows throughout the table it may not be efficient to use an index to find them. You may still need to access (say) 70% or the table blocks to retrieve the required rows (google for "clustering factor"), in which case Oracle is going to perform a ful table scan if it gets the estimation correct. In 11g you can collect multicolumn statistics to help with this situation I believe. In 9i and 10g you can use dynamic sampling to get a very good estimation of the number of rows to be retrieved. To get the execution plan do this: ``` explain plan for SELECT * FROM sometable WHERE foo='hello' AND bar='world' / select * from table(dbms_xplan.display) / ``` Contrast that with: ``` explain plan for SELECT /*+ dynamic_sampling(4) */ * FROM sometable WHERE foo='hello' AND bar='world' / select * from table(dbms_xplan.display) / ```
149,092
<p>I have backups of files archived in optical media (CDs and DVDs). These all have par2 recovery files, stored on separate media. Even in cases where there are no par2 files, minor errors when reading on one optical drive can be read fine on another drive.</p> <p>The thing is, when reading faulty media, the read time is very, very long, because devices tend to retry multiple times.</p> <p>The question is: how can I control the number of retries (ie set to no retries or only one try)? Some system call? A library I can download? Do I have to work on the SCSI layer?</p> <p>The question is mainly about Linux, but any Win32 pointers will be more than welcome too.</p>
[ { "answer_id": 149840, "author": "Daniel Papasian", "author_id": 7548, "author_profile": "https://Stackoverflow.com/users/7548", "pm_score": -1, "selected": false, "text": "<p>dd(1) is your friend.</p>\n\n<p>dd if=/dev/cdrom of=image bs=2352 conv=noerror,notrunc</p>\n\n<p>The drive may s...
2008/09/29
[ "https://Stackoverflow.com/questions/149092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6899/" ]
I have backups of files archived in optical media (CDs and DVDs). These all have par2 recovery files, stored on separate media. Even in cases where there are no par2 files, minor errors when reading on one optical drive can be read fine on another drive. The thing is, when reading faulty media, the read time is very, very long, because devices tend to retry multiple times. The question is: how can I control the number of retries (ie set to no retries or only one try)? Some system call? A library I can download? Do I have to work on the SCSI layer? The question is mainly about Linux, but any Win32 pointers will be more than welcome too.
`man readom`, a program that comes with cdrecord: ``` -noerror Do not abort if the high level error checking in readom found an uncorrectable error in the data stream. -nocorr Switch the drive into a mode where it ignores read errors in data sectors that are a result of uncorrectable ECC/EDC errors before reading. If readom completes, the error recovery mode of the drive is switched back to the remembered old mode. ... retries=# Set the retry count for high level retries in readom to #. The default is to do 128 retries which may be too much if you like to read a CD with many unreadable sectors. ```
149,102
<p>How can I capture the event in Excel when a user clicks on a cell. I want to be able to use this event to trigger some code to count how many times the user clicks on several different cells in a column.</p>
[ { "answer_id": 149109, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 1, "selected": false, "text": "<p>Use the <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.worksheet.selectionchange(VS...
2008/09/29
[ "https://Stackoverflow.com/questions/149102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22376/" ]
How can I capture the event in Excel when a user clicks on a cell. I want to be able to use this event to trigger some code to count how many times the user clicks on several different cells in a column.
Check out the Worksheet\_SelectionChange event. In that event you could use Intersect() with named ranges to figure out if a specific range were clicked. Here's some code that might help you get started. ``` Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range) If Not Intersect(Target, Range("SomeNamedRange")) Is Nothing Then 'Your counting code End If End Sub ```
149,132
<p>I'm not sure if this is something I should do in T-SQL or not, and I'm pretty sure using the word 'iterate' was wrong in this context, since you should never iterate anything in sql. It should be a set based operation, correct? Anyway, here's the scenario:</p> <p>I have a stored proc that returns many uniqueidentifiers (single column results). These ids are the primary keys of records in a another table. I need to set a flag on all the corresponding records in that table.</p> <p>How do I do this without the use of cursors? Should be an easy one for you sql gurus!</p>
[ { "answer_id": 149152, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 5, "selected": true, "text": "<p>This may not be the most efficient, but I would create a temp table to hold the results of the stored proc and then ...
2008/09/29
[ "https://Stackoverflow.com/questions/149132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5469/" ]
I'm not sure if this is something I should do in T-SQL or not, and I'm pretty sure using the word 'iterate' was wrong in this context, since you should never iterate anything in sql. It should be a set based operation, correct? Anyway, here's the scenario: I have a stored proc that returns many uniqueidentifiers (single column results). These ids are the primary keys of records in a another table. I need to set a flag on all the corresponding records in that table. How do I do this without the use of cursors? Should be an easy one for you sql gurus!
This may not be the most efficient, but I would create a temp table to hold the results of the stored proc and then use that in a join against the target table. For example: ``` CREATE TABLE #t (uniqueid int) INSERT INTO #t EXEC p_YourStoredProc UPDATE TargetTable SET a.FlagColumn = 1 FROM TargetTable a JOIN #t b ON a.uniqueid = b.uniqueid DROP TABLE #t ```
149,153
<p>I'm trying to create a ImageIcon from a animated gif stored in a jar file.</p> <pre><code>ImageIcon imageIcon = new ImageIcon(ImageIO.read(MyClass.class.getClassLoader().getResourceAsStream("animated.gif"))); </code></pre> <p>The image loads, but only the first frame of the animated gif. The animation does not play. </p> <p>If I load the animated gif from a file on the filesystem, everything works as expected. The animation plays through all the of frames. So this works:</p> <pre><code>ImageIcon imageIcon = new ImageIcon("/path/on/filesystem/animated.gif"); </code></pre> <p>How can I load an animated gif into an ImageIcon from a jar file?</p> <p>EDIT: Here is a complete test case, why doesn't this display the animation?</p> <pre><code>import javax.imageio.ImageIO; import javax.swing.*; public class AnimationTest extends JFrame { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { AnimationTest test = new AnimationTest(); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); test.setVisible(true); } }); } public AnimationTest() { super(); try { JLabel label = new JLabel(); ImageIcon imageIcon = new ImageIcon(ImageIO.read(AnimationTest.class.getClassLoader().getResourceAsStream("animated.gif"))); label.setIcon(imageIcon); imageIcon.setImageObserver(label); add(label); pack(); } catch (Exception e) { e.printStackTrace(); } } } </code></pre>
[ { "answer_id": 149182, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 3, "selected": false, "text": "<p>You have to use getClass().getResource(imgName); to get a URL to the image file. Check out <a href=\"http://www....
2008/09/29
[ "https://Stackoverflow.com/questions/149153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/739/" ]
I'm trying to create a ImageIcon from a animated gif stored in a jar file. ``` ImageIcon imageIcon = new ImageIcon(ImageIO.read(MyClass.class.getClassLoader().getResourceAsStream("animated.gif"))); ``` The image loads, but only the first frame of the animated gif. The animation does not play. If I load the animated gif from a file on the filesystem, everything works as expected. The animation plays through all the of frames. So this works: ``` ImageIcon imageIcon = new ImageIcon("/path/on/filesystem/animated.gif"); ``` How can I load an animated gif into an ImageIcon from a jar file? EDIT: Here is a complete test case, why doesn't this display the animation? ``` import javax.imageio.ImageIO; import javax.swing.*; public class AnimationTest extends JFrame { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { AnimationTest test = new AnimationTest(); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); test.setVisible(true); } }); } public AnimationTest() { super(); try { JLabel label = new JLabel(); ImageIcon imageIcon = new ImageIcon(ImageIO.read(AnimationTest.class.getClassLoader().getResourceAsStream("animated.gif"))); label.setIcon(imageIcon); imageIcon.setImageObserver(label); add(label); pack(); } catch (Exception e) { e.printStackTrace(); } } } ```
This reads gif animation from inputStream ``` InputStream in = ...; Image image = Toolkit.getDefaultToolkit().createImage(org.apache.commons.io.IOUtils.toByteArray(in)); ```
149,191
<p>I am seeing some rather weird behavior with PowerShell, it looks like custom functions might need a "parenthesis wrapper" to evaluate as you might expect them. Given a simple PowerShell function:</p> <pre><code>function Return-True { return $true } </code></pre> <p>and then some sample code to invoke it:</p> <pre><code>PS C:\&gt; Return-True True PS C:\&gt; Return-True -eq $false True PS C:\&gt; (Return-True) -eq $false False </code></pre> <p>Ideas? Comments? </p>
[ { "answer_id": 149373, "author": "hurcane", "author_id": 21363, "author_profile": "https://Stackoverflow.com/users/21363", "pm_score": 3, "selected": false, "text": "<p>The second line is not doing a boolean evaluation. Look at what happens if you do the same thing with strings.</p>\n\n<...
2008/09/29
[ "https://Stackoverflow.com/questions/149191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/243/" ]
I am seeing some rather weird behavior with PowerShell, it looks like custom functions might need a "parenthesis wrapper" to evaluate as you might expect them. Given a simple PowerShell function: ``` function Return-True { return $true } ``` and then some sample code to invoke it: ``` PS C:\> Return-True True PS C:\> Return-True -eq $false True PS C:\> (Return-True) -eq $false False ``` Ideas? Comments?
When PowerShell sees the token `Return-True` it identifies it as a command and until evaluation or end of the statement, everything else is an argument which is passed to the function `Return-True`. You can see this in action if you do: ``` PS > function Return-True { "The arguments are: $args"; return $true } PS > Return-True -eq $false The arguments are: -eq False True ``` That's why all of the following return 'True', because all you are seeing is the result of calling `Return-True` with various arguments: ``` PS > Return-True -eq $false True PS > Return-True -ne $false True PS > Return-True -eq $true True PS > Return-True -ne $true True ``` Using `(Return-True)` forces PowerShell to evaluate the function (with no arguments).
149,198
<p>I use Tortoise SVN usuallly, but I have been looking into Mercurial since it is a distributed revision control system. </p> <p>What I am looking for, in both systems, is a tool that let me pick only parts of a file and commit them. If I want to do this now, I have to copy to a temp version of the file and keep only the changes I want to commit in the current version, and then copy the temp version to the current version again after committing. It's just such a hassle and the program should be able to do this for me.</p> <p>I heard Git supports this, please let me know if this is correct.</p>
[ { "answer_id": 149270, "author": "Nicholas Riley", "author_id": 6372, "author_profile": "https://Stackoverflow.com/users/6372", "pm_score": 6, "selected": true, "text": "<p>Mercurial can do this with the <a href=\"https://www.mercurial-scm.org/wiki/RecordExtension\" rel=\"nofollow norefe...
2008/09/29
[ "https://Stackoverflow.com/questions/149198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6752/" ]
I use Tortoise SVN usuallly, but I have been looking into Mercurial since it is a distributed revision control system. What I am looking for, in both systems, is a tool that let me pick only parts of a file and commit them. If I want to do this now, I have to copy to a temp version of the file and keep only the changes I want to commit in the current version, and then copy the temp version to the current version again after committing. It's just such a hassle and the program should be able to do this for me. I heard Git supports this, please let me know if this is correct.
Mercurial can do this with the [record](https://www.mercurial-scm.org/wiki/RecordExtension) extension. It'll prompt you for each file and each diff hunk. For example: ``` % hg record diff --git a/prelim.tex b/prelim.tex 2 hunks, 4 lines changed examine changes to 'prelim.tex'? [Ynsfdaq?] @@ -12,7 +12,7 @@ \setmonofont[Scale=0.88]{Consolas} % missing from xunicode.sty \DeclareUTFcomposite[\UTFencname]{x00ED}{\'}{\i} -\else +\else foo \usepackage[pdftex]{graphicx} \fi record this change to 'prelim.tex'? [Ynsfdaq?] @@ -1281,3 +1281,5 @@ %% Local variables: %% mode: latex %% End: + +foo \ No newline at end of file record this change to 'prelim.tex'? [Ynsfdaq?] n Waiting for Emacs... ``` After the commit, the remaining diff will be left behind: ``` % hg di diff --git a/prelim.tex b/prelim.tex --- a/prelim.tex +++ b/prelim.tex @@ -1281,3 +1281,5 @@ %% Local variables: %% mode: latex %% End: + +foo \ No newline at end of file ``` Alternatively, you may find it easier to use MQ (Mercurial Queues) to separate the individual changes in your repository into patches. There is a MQ variant of record (qrecord), too. **Update:** Also try the [crecord](http://bitbucket.org/edgimar/crecord/wiki/Home) extension, which provides a curses interface to hunk/line selection. ![crecord screenshot](https://i.stack.imgur.com/wRcie.png)
149,206
<p>I have a XML response from an HTTPService call with the e4x result format.</p> <pre> <code> &lt;?xml version="1.0" encoding="utf-8"?> &lt;Validation Error="Invalid Username/Password Combination" /> </code> </pre> <p>I have tried:</p> <pre> <code> private function callback(event:ResultEvent):void { if(event.result..@Error) { // error attr present } else { // error attr not present } } </code> </pre> <p>This does not seem to work (it always thinks that the error attribute exits) what is the best way to do this? thanks.</p> <p><b>EDIT:</b> I have also tried to compare the attribute to null and an empty string without such success...</p>
[ { "answer_id": 149291, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 1, "selected": false, "text": "<p>I have figured out a solution, I'm still interested if there is a better way to do this...</p>\n\n<p>This will work:</p>\...
2008/09/29
[ "https://Stackoverflow.com/questions/149206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
I have a XML response from an HTTPService call with the e4x result format. ``` <?xml version="1.0" encoding="utf-8"?> <Validation Error="Invalid Username/Password Combination" /> ``` I have tried: ``` private function callback(event:ResultEvent):void { if(event.result..@Error) { // error attr present } else { // error attr not present } } ``` This does not seem to work (it always thinks that the error attribute exits) what is the best way to do this? thanks. **EDIT:** I have also tried to compare the attribute to null and an empty string without such success...
You have found the best way to do it: ``` event.result.attribute("Error").length() > 0 ``` The `attribute` method is the preferred way to retrieve attributes if you don't know if they are there or not.
149,268
<p>Since I have started using this site, I keep hearing about the Boost library. I am wondering what are some of the major benefits of the Boost library (hence why should I use it) and how portable is the Boost library?</p>
[ { "answer_id": 149277, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 4, "selected": false, "text": "<p>Boost is a collection of C++ libraries. 10 of which are being included in tr1 of C++0x.</p>\n\n<p>You can <a href...
2008/09/29
[ "https://Stackoverflow.com/questions/149268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20229/" ]
Since I have started using this site, I keep hearing about the Boost library. I am wondering what are some of the major benefits of the Boost library (hence why should I use it) and how portable is the Boost library?
Boost is organized by several members of the standard committee. So it is a breeding ground for libraries that will be in the next standard. 1. It is an extension to the STL (it fills in the bits left out) 2. It is well documented. 3. It is well peer-reviewed. 4. It has high activity so bugs are found and fixed quickly. 5. It is platform neutral and works everywhere. 6. It is free to use. With tr1 coming up soon it is nice to know that boost already has a lot of the ground covered. A lot of the libraries in tr1 are basically adapted directly from boost originals and thus have been tried and tested. The difference is that they have been moved into the std::tr1 namespace (rather than boost). All that you need to do is add the following to your compilers default [include search path](http://www.boost.org/doc/libs/1_37_0/doc/html/boost_tr1/usage.html): ``` <boost-install-path>/boost/tr1/tr1 ``` Then when you include the standard headers boost will automatically import all the required stuff into the namespace std::tr1 ### For Example: To use std::tr1::share\_ptr you just need to include <memory>. This will give you all the smart pointers with one file.
149,311
<p>When adding an EditItemTemplate of some complexity (mulitple fields in one template), and then parsing the controls from the RowUpdating event, the controls that were manually entered by the user have no values. My guess is there is something going on with when the data is bound, but I've had instances where simply adding and attribute to a control in codebehind started the behavior and removing that code made the code work. As a work-around, I can Request(controlname.UniqueId) to get it's value, but that is rather a hack.</p> <p><strong>Edit</strong> When I access the value like so</p> <pre><code>TextBox txtValue = gvwSettings.SelectedRow.FindControl("txtValue") as TextBox; </code></pre> <p>the text box is found, but the .Text is not the user input.</p>
[ { "answer_id": 149392, "author": "Elijah Manor", "author_id": 4481, "author_profile": "https://Stackoverflow.com/users/4481", "pm_score": 0, "selected": false, "text": "<p>You should be able to use the GridViewUpdateEventArgs to retrieve the inputted value, for example: </p>\n\n<pre><cod...
2008/09/29
[ "https://Stackoverflow.com/questions/149311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2017/" ]
When adding an EditItemTemplate of some complexity (mulitple fields in one template), and then parsing the controls from the RowUpdating event, the controls that were manually entered by the user have no values. My guess is there is something going on with when the data is bound, but I've had instances where simply adding and attribute to a control in codebehind started the behavior and removing that code made the code work. As a work-around, I can Request(controlname.UniqueId) to get it's value, but that is rather a hack. **Edit** When I access the value like so ``` TextBox txtValue = gvwSettings.SelectedRow.FindControl("txtValue") as TextBox; ``` the text box is found, but the .Text is not the user input.
Did you turn off ViewState? Did you add control programmatically in the template? If so, did you create them at the correct stage?
149,324
<p>Is there a way set flags on a per-file basis with automake?<br> In particular, if I have a c++ project and want to compile with -WAll all the files except one for which I want to disable a particular warning, what could I do?</p> <p>I tried something like:</p> <pre><code>CXXFLAGS = -WAll ... bin_PROGRAMS = test test_SOURCES = main.cpp utility.cpp utility_o_CXXFLAGS = $(CXXFLAGS) -Wno-unused-value </code></pre> <p>but it didn't work.</p> <p>EDITED: removed reference to automake manual, which was actually misleading (thanks to Douglas Leeder).</p>
[ { "answer_id": 149642, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 2, "selected": false, "text": "<p>You've got confused - that section is referring to options to automake itself.</p>\n\n<p>It's a way of setting the...
2008/09/29
[ "https://Stackoverflow.com/questions/149324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15622/" ]
Is there a way set flags on a per-file basis with automake? In particular, if I have a c++ project and want to compile with -WAll all the files except one for which I want to disable a particular warning, what could I do? I tried something like: ``` CXXFLAGS = -WAll ... bin_PROGRAMS = test test_SOURCES = main.cpp utility.cpp utility_o_CXXFLAGS = $(CXXFLAGS) -Wno-unused-value ``` but it didn't work. EDITED: removed reference to automake manual, which was actually misleading (thanks to Douglas Leeder).
Automake only supports per-target flags, while you want per-object flags. One way around is to create a small library that contains your object: ``` CXXFLAGS = -Wall ... bin_PROGRAMS = test test_SOURCES = main.cpp test_LDADD = libutility.a noinst_LIBRARIES = libutility.a libutility_a_SOURCES = utility.cpp libutility_a_CXXFLAGS = $(CXXFLAGS) -Wno-unused-value ```
149,337
<p>Is it possible to create a .NET equivalent to the following code?</p> <pre><code>&lt;?php if (!isset($_SERVER['PHP_AUTH_USER'])) { header('WWW-Authenticate: Basic realm="My Realm"'); header('HTTP/1.0 401 Unauthorized'); echo 'Text to send if user hits Cancel button'; exit; } else { echo "&lt;p&gt;Hello {$_SERVER['PHP_AUTH_USER']}.&lt;/p&gt;"; echo "&lt;p&gt;You entered {$_SERVER['PHP_AUTH_PW']} as your password.&lt;/p&gt;"; } ?&gt; </code></pre> <p>I would like to be able to define a static user/password in the web.config as well. This is very easy to do in PHP, haven't seen anything explaining how to do this in MSDN.</p> <hr> <p>All I want is this:</p> <p><img src="https://i.stack.imgur.com/IJE1b.png" alt="https://i.stack.imgur.com/IJE1b.png"></p>
[ { "answer_id": 149353, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 0, "selected": false, "text": "<p>Yes, you can add to web.config and use forms authentication. I dont know php, so i cant help witjh the rest of your qu...
2008/09/29
[ "https://Stackoverflow.com/questions/149337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/795/" ]
Is it possible to create a .NET equivalent to the following code? ``` <?php if (!isset($_SERVER['PHP_AUTH_USER'])) { header('WWW-Authenticate: Basic realm="My Realm"'); header('HTTP/1.0 401 Unauthorized'); echo 'Text to send if user hits Cancel button'; exit; } else { echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>"; echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>"; } ?> ``` I would like to be able to define a static user/password in the web.config as well. This is very easy to do in PHP, haven't seen anything explaining how to do this in MSDN. --- All I want is this: ![https://i.stack.imgur.com/IJE1b.png](https://i.stack.imgur.com/IJE1b.png)
The easiest way to achieve the same as with the PHP code would be to directly send the same headers via [Reponse.AppendHeader()](http://msdn.microsoft.com/en-us/library/system.web.httpresponse.appendheader(VS.80).aspx). Still I would suggest you to read an [ASP.NET Forms Authentication Tutorial](http://www.asp.net/Learn/Security/).
149,379
<p>I want to create Code39 encoded barcodes from my application. </p> <p>I know I can use a font for this, but I'd prefer not to as I'd have to register the font on the server and I've had some pretty bad experiences with that.</p> <p><em>An example of what I've produced after asking this question is in the answers</em></p>
[ { "answer_id": 149412, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 3, "selected": false, "text": "<p>If you choose Code39, you could probably code up from this code I wrote</p>\n\n<p><a href=\"http://www.atalasoft.com/c...
2008/09/29
[ "https://Stackoverflow.com/questions/149379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5018/" ]
I want to create Code39 encoded barcodes from my application. I know I can use a font for this, but I'd prefer not to as I'd have to register the font on the server and I've had some pretty bad experiences with that. *An example of what I've produced after asking this question is in the answers*
This is my current codebehind, with lots of comments: ``` Option Explicit On Option Strict On Imports System.Drawing Imports System.Drawing.Imaging Imports System.Drawing.Bitmap Imports System.Drawing.Graphics Imports System.IO Partial Public Class Barcode Inherits System.Web.UI.Page 'Sebastiaan Janssen - 20081001 - TINT-30584 'Most of the code is based on this example: 'http://www.atalasoft.com/cs/blogs/loufranco/archive/2008/04/25/writing-code-39-barcodes-with-javascript.aspx-generation.aspx 'With a bit of this thrown in: 'http://www.atalasoft.com/cs/blogs/loufranco/archive/2008/03/24/code-39-barcode Private _encoding As Hashtable = New Hashtable Private Const _wideBarWidth As Short = 8 Private Const _narrowBarWidth As Short = 2 Private Const _barHeight As Short = 100 Sub BarcodeCode39() _encoding.Add("*", "bWbwBwBwb") _encoding.Add("-", "bWbwbwBwB") _encoding.Add("$", "bWbWbWbwb") _encoding.Add("%", "bwbWbWbWb") _encoding.Add(" ", "bWBwbwBwb") _encoding.Add(".", "BWbwbwBwb") _encoding.Add("/", "bWbWbwbWb") _encoding.Add("+", "bWbwbWbWb") _encoding.Add("0", "bwbWBwBwb") _encoding.Add("1", "BwbWbwbwB") _encoding.Add("2", "bwBWbwbwB") _encoding.Add("3", "BwBWbwbwb") _encoding.Add("4", "bwbWBwbwB") _encoding.Add("5", "BwbWBwbwb") _encoding.Add("6", "bwBWBwbwb") _encoding.Add("7", "bwbWbwBwB") _encoding.Add("8", "BwbWbwBwb") _encoding.Add("9", "bwBWbwBwb") _encoding.Add("A", "BwbwbWbwB") _encoding.Add("B", "bwBwbWbwB") _encoding.Add("C", "BwBwbWbwb") _encoding.Add("D", "bwbwBWbwB") _encoding.Add("E", "BwbwBWbwb") _encoding.Add("F", "bwBwBWbwb") _encoding.Add("G", "bwbwbWBwB") _encoding.Add("H", "BwbwbWBwb") _encoding.Add("I", "bwBwbWBwb") _encoding.Add("J", "bwbwBWBwb") _encoding.Add("K", "BwbwbwbWB") _encoding.Add("L", "bwBwbwbWB") _encoding.Add("M", "BwBwbwbWb") _encoding.Add("N", "bwbwBwbWB") _encoding.Add("O", "BwbwBwbWb") _encoding.Add("P", "bwBwBwbWb") _encoding.Add("Q", "bwbwbwBWB") _encoding.Add("R", "BwbwbwBWb") _encoding.Add("S", "bwBwbwBWb") _encoding.Add("T", "bwbwBwBWb") _encoding.Add("U", "BWbwbwbwB") _encoding.Add("V", "bWBwbwbwB") _encoding.Add("W", "BWBwbwbwb") _encoding.Add("X", "bWbwBwbwB") _encoding.Add("Y", "BWbwBwbwb") _encoding.Add("Z", "bWBwBwbwb") End Sub Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load BarcodeCode39() Dim barcode As String = String.Empty If Not IsNothing(Request("barcode")) AndAlso Not (Request("barcode").Length = 0) Then barcode = Request("barcode") Response.ContentType = "image/png" Response.AddHeader("Content-Disposition", String.Format("attachment; filename=barcode_{0}.png", barcode)) 'TODO: Depending on the length of the string, determine how wide the image will be GenerateBarcodeImage(250, 140, barcode).WriteTo(Response.OutputStream) End If End Sub Protected Function getBCSymbolColor(ByVal symbol As String) As System.Drawing.Brush getBCSymbolColor = Brushes.Black If symbol = "W" Or symbol = "w" Then getBCSymbolColor = Brushes.White End If End Function Protected Function getBCSymbolWidth(ByVal symbol As String) As Short getBCSymbolWidth = _narrowBarWidth If symbol = "B" Or symbol = "W" Then getBCSymbolWidth = _wideBarWidth End If End Function Protected Overridable Function GenerateBarcodeImage(ByVal imageWidth As Short, ByVal imageHeight As Short, ByVal Code As String) As MemoryStream 'create a new bitmap Dim b As New Bitmap(imageWidth, imageHeight, Imaging.PixelFormat.Format32bppArgb) 'create a canvas to paint on Dim canvas As New Rectangle(0, 0, imageWidth, imageHeight) 'draw a white background Dim g As Graphics = Graphics.FromImage(b) g.FillRectangle(Brushes.White, 0, 0, imageWidth, imageHeight) 'write the unaltered code at the bottom 'TODO: truely center this text Dim textBrush As New SolidBrush(Color.Black) g.DrawString(Code, New Font("Courier New", 12), textBrush, 100, 110) 'Code has to be surrounded by asterisks to make it a valid Code39 barcode Dim UseCode As String = String.Format("{0}{1}{0}", "*", Code) 'Start drawing at 10, 10 Dim XPosition As Short = 10 Dim YPosition As Short = 10 Dim invalidCharacter As Boolean = False Dim CurrentSymbol As String = String.Empty For j As Short = 0 To CShort(UseCode.Length - 1) CurrentSymbol = UseCode.Substring(j, 1) 'check if symbol can be used If Not IsNothing(_encoding(CurrentSymbol)) Then Dim EncodedSymbol As String = _encoding(CurrentSymbol).ToString For i As Short = 0 To CShort(EncodedSymbol.Length - 1) Dim CurrentCode As String = EncodedSymbol.Substring(i, 1) g.FillRectangle(getBCSymbolColor(CurrentCode), XPosition, YPosition, getBCSymbolWidth(CurrentCode), _barHeight) XPosition = XPosition + getBCSymbolWidth(CurrentCode) Next 'After each written full symbol we need a whitespace (narrow width) g.FillRectangle(getBCSymbolColor("w"), XPosition, YPosition, getBCSymbolWidth("w"), _barHeight) XPosition = XPosition + getBCSymbolWidth("w") Else invalidCharacter = True End If Next 'errorhandling when an invalidcharacter is found If invalidCharacter Then g.FillRectangle(Brushes.White, 0, 0, imageWidth, imageHeight) g.DrawString("Invalid characters found,", New Font("Courier New", 8), textBrush, 0, 0) g.DrawString("no barcode generated", New Font("Courier New", 8), textBrush, 0, 10) g.DrawString("Input was: ", New Font("Courier New", 8), textBrush, 0, 30) g.DrawString(Code, New Font("Courier New", 8), textBrush, 0, 40) End If 'write the image into a memorystream Dim ms As New MemoryStream Dim encodingParams As New EncoderParameters encodingParams.Param(0) = New EncoderParameter(Encoder.Quality, 100) Dim encodingInfo As ImageCodecInfo = FindCodecInfo("PNG") b.Save(ms, encodingInfo, encodingParams) 'dispose of the object we won't need any more g.Dispose() b.Dispose() Return ms End Function Protected Overridable Function FindCodecInfo(ByVal codec As String) As ImageCodecInfo Dim encoders As ImageCodecInfo() = ImageCodecInfo.GetImageEncoders For Each e As ImageCodecInfo In encoders If e.FormatDescription.Equals(codec) Then Return e Next Return Nothing End Function End Class ```
149,380
<p>This is an issue that I've spent hours researching in the past. It seems to me to be something that should have been addressed by modern <a href="http://en.wikipedia.org/wiki/Relational_database_management_system" rel="noreferrer">RDBMS</a> solutions but as yet I have not found anything that really addresses what I see to be an incredibly common need in any Web or Windows application with a database back-end.</p> <p>I speak of dynamic sorting. In my fantasy world, it should be as simple as something like:</p> <pre><code>ORDER BY @sortCol1, @sortCol2 </code></pre> <p>This is the canonical example given by newbie SQL and <a href="http://en.wikipedia.org/wiki/Stored_procedure" rel="noreferrer">Stored Procedure</a> developers all over forums across the Internet. "Why isn't this possible?" they ask. Invariably, somebody eventually comes along to lecture them about the compiled nature of stored procedures, of execution plans in general, and all sorts of other reasons why it isn't possible to put a parameter directly into an <code>ORDER BY</code> clause.</p> <hr> <p>I know what some of you are already thinking: "Let the client do the sorting, then." Naturally, this offloads the work from your database. In our case though, our database servers aren't even breaking a sweat 99% of the time and they aren't even multi-core yet or any of the other myriad improvements to system architecture that happen every 6 months. For this reason alone, having our databases handle sorting wouldn't be a problem. Additionally, databases are <em>very</em> good at sorting. They are optimized for it and have had years to get it right, the language for doing it is incredibly flexible, intuitive, and simple and above all any beginner SQL writer knows how to do it and even more importantly they know how to edit it, make changes, do maintenance, etc. When your databases are far from being taxed and you just want to simplify (and shorten!) development time this seems like an obvious choice.</p> <p>Then there's the web issue. I've played around with JavaScript that will do client-side sorting of HTML tables, but they inevitably aren't flexible enough for my needs and, again, since my databases aren't overly taxed and can do sorting really <em>really</em> easily, I have a hard time justifying the time it would take to re-write or roll-my-own JavaScript sorter. The same generally goes for server-side sorting, though it is already probably much preferred over JavaScript. I'm not one that particularly likes the overhead of DataSets, so sue me.</p> <p>But this brings back the point that it isn't possible &mdash; or rather, not easily. I've done, with prior systems, an incredibly hack way of getting dynamic sorting. It wasn't pretty, nor intuitive, simple, or flexible and a beginner SQL writer would be lost within seconds. Already this is looking to be not so much a "solution" but a "complication."</p> <hr> <p>The following examples are not meant to expose any sort of best practices or good coding style or anything, nor are they indicative of my abilities as a T-SQL programmer. They are what they are and I fully admit they are confusing, bad form, and just plain hack.</p> <p>We pass an integer value as a parameter to a stored procedure (let's call the parameter just "sort") and from that we determine a bunch of other variables. For example... let's say sort is 1 (or the default):</p> <pre><code>DECLARE @sortCol1 AS varchar(20) DECLARE @sortCol2 AS varchar(20) DECLARE @dir1 AS varchar(20) DECLARE @dir2 AS varchar(20) DECLARE @col1 AS varchar(20) DECLARE @col2 AS varchar(20) SET @col1 = 'storagedatetime'; SET @col2 = 'vehicleid'; IF @sort = 1 -- Default sort. BEGIN SET @sortCol1 = @col1; SET @dir1 = 'asc'; SET @sortCol2 = @col2; SET @dir2 = 'asc'; END ELSE IF @sort = 2 -- Reversed order default sort. BEGIN SET @sortCol1 = @col1; SET @dir1 = 'desc'; SET @sortCol2 = @col2; SET @dir2 = 'desc'; END </code></pre> <p>You can already see how if I declared more @colX variables to define other columns I could really get creative with the columns to sort on based on the value of "sort"... to use it, it usually ends up looking like the following incredibly messy clause:</p> <pre><code>ORDER BY CASE @dir1 WHEN 'desc' THEN CASE @sortCol1 WHEN @col1 THEN [storagedatetime] WHEN @col2 THEN [vehicleid] END END DESC, CASE @dir1 WHEN 'asc' THEN CASE @sortCol1 WHEN @col1 THEN [storagedatetime] WHEN @col2 THEN [vehicleid] END END, CASE @dir2 WHEN 'desc' THEN CASE @sortCol2 WHEN @col1 THEN [storagedatetime] WHEN @col2 THEN [vehicleid] END END DESC, CASE @dir2 WHEN 'asc' THEN CASE @sortCol2 WHEN @col1 THEN [storagedatetime] WHEN @col2 THEN [vehicleid] END END </code></pre> <p>Obviously this is a very stripped down example. The real stuff, since we usually have four or five columns to support sorting on, each with possible secondary or even a third column to sort on in addition to that (for example date descending then sorted secondarily by name ascending) and each supporting bi-directional sorting which effectively doubles the number of cases. Yeah... it gets hairy really quick.</p> <p>The idea is that one could "easily" change the sort cases such that vehicleid gets sorted before the storagedatetime... but the pseudo-flexibility, at least in this simple example, really ends there. Essentially, each case that fails a test (because our sort method doesn't apply to it this time around) renders a NULL value. And thus you end up with a clause that functions like the following:</p> <pre><code>ORDER BY NULL DESC, NULL, [storagedatetime] DESC, blah blah </code></pre> <p>You get the idea. It works because SQL Server effectively ignores null values in order by clauses. This is incredibly hard to maintain, as anyone with any basic working knowledge of SQL can probably see. If I've lost any of you, don't feel bad. It took us a long time to get it working and we still get confused trying to edit it or create new ones like it. Thankfully it doesn't need changing often, otherwise it would quickly become "not worth the trouble."</p> <p>Yet it <em>did</em> work.</p> <hr> <p>My question is then: <strong>is there a better way?</strong></p> <p>I'm okay with solutions other than Stored Procedure ones, as I realize it may just not be the way to go. Preferably, I'd like to know if anyone can do it better within the Stored Procedure, but if not, how do you all handle letting the user dynamically sort tables of data (bi-directionally, too) with ASP.NET?</p> <p>And thank you for reading (or at least skimming) such a long question!</p> <p>PS: Be glad I didn't show my example of a stored procedure that supports dynamic sorting, dynamic filtering/text-searching of columns, pagination via ROWNUMBER() OVER, <em>AND</em> try...catch with transaction rollbacking on errors... "behemoth-sized" doesn't even begin to describe them.</p> <hr> <p><strong>Update:</strong></p> <ul> <li>I would like to <strong>avoid dynamic SQL</strong>. Parsing a string together and running an EXEC on it defeats a lot of the purpose of having a stored procedure in the first place. Sometimes I wonder though if the cons of doing such a thing wouldn't be worth it, at least in these special dynamic sorting cases. Still, I always feel dirty whenever I do dynamic SQL strings like that &mdash; like I'm still living in the Classic ASP world.</li> <li>A lot of the reason we want stored procedures in the first place is for <strong>security</strong>. I don't get to make the call on security concerns, only suggest solutions. With SQL Server 2005 we can set permissions (on a per-user basis if need be) at the schema level on individual stored procedures and then deny any queries against the tables directly. Critiquing the pros and cons of this approach is perhaps for another question, but again it's not my decision. I'm just the lead code monkey. :)</li> </ul>
[ { "answer_id": 149391, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 1, "selected": false, "text": "<p>How about handling sorting on the stuff displaying the results -- grids, reports, etc. rather than on SQL?</p>\n\...
2008/09/29
[ "https://Stackoverflow.com/questions/149380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7290/" ]
This is an issue that I've spent hours researching in the past. It seems to me to be something that should have been addressed by modern [RDBMS](http://en.wikipedia.org/wiki/Relational_database_management_system) solutions but as yet I have not found anything that really addresses what I see to be an incredibly common need in any Web or Windows application with a database back-end. I speak of dynamic sorting. In my fantasy world, it should be as simple as something like: ``` ORDER BY @sortCol1, @sortCol2 ``` This is the canonical example given by newbie SQL and [Stored Procedure](http://en.wikipedia.org/wiki/Stored_procedure) developers all over forums across the Internet. "Why isn't this possible?" they ask. Invariably, somebody eventually comes along to lecture them about the compiled nature of stored procedures, of execution plans in general, and all sorts of other reasons why it isn't possible to put a parameter directly into an `ORDER BY` clause. --- I know what some of you are already thinking: "Let the client do the sorting, then." Naturally, this offloads the work from your database. In our case though, our database servers aren't even breaking a sweat 99% of the time and they aren't even multi-core yet or any of the other myriad improvements to system architecture that happen every 6 months. For this reason alone, having our databases handle sorting wouldn't be a problem. Additionally, databases are *very* good at sorting. They are optimized for it and have had years to get it right, the language for doing it is incredibly flexible, intuitive, and simple and above all any beginner SQL writer knows how to do it and even more importantly they know how to edit it, make changes, do maintenance, etc. When your databases are far from being taxed and you just want to simplify (and shorten!) development time this seems like an obvious choice. Then there's the web issue. I've played around with JavaScript that will do client-side sorting of HTML tables, but they inevitably aren't flexible enough for my needs and, again, since my databases aren't overly taxed and can do sorting really *really* easily, I have a hard time justifying the time it would take to re-write or roll-my-own JavaScript sorter. The same generally goes for server-side sorting, though it is already probably much preferred over JavaScript. I'm not one that particularly likes the overhead of DataSets, so sue me. But this brings back the point that it isn't possible — or rather, not easily. I've done, with prior systems, an incredibly hack way of getting dynamic sorting. It wasn't pretty, nor intuitive, simple, or flexible and a beginner SQL writer would be lost within seconds. Already this is looking to be not so much a "solution" but a "complication." --- The following examples are not meant to expose any sort of best practices or good coding style or anything, nor are they indicative of my abilities as a T-SQL programmer. They are what they are and I fully admit they are confusing, bad form, and just plain hack. We pass an integer value as a parameter to a stored procedure (let's call the parameter just "sort") and from that we determine a bunch of other variables. For example... let's say sort is 1 (or the default): ``` DECLARE @sortCol1 AS varchar(20) DECLARE @sortCol2 AS varchar(20) DECLARE @dir1 AS varchar(20) DECLARE @dir2 AS varchar(20) DECLARE @col1 AS varchar(20) DECLARE @col2 AS varchar(20) SET @col1 = 'storagedatetime'; SET @col2 = 'vehicleid'; IF @sort = 1 -- Default sort. BEGIN SET @sortCol1 = @col1; SET @dir1 = 'asc'; SET @sortCol2 = @col2; SET @dir2 = 'asc'; END ELSE IF @sort = 2 -- Reversed order default sort. BEGIN SET @sortCol1 = @col1; SET @dir1 = 'desc'; SET @sortCol2 = @col2; SET @dir2 = 'desc'; END ``` You can already see how if I declared more @colX variables to define other columns I could really get creative with the columns to sort on based on the value of "sort"... to use it, it usually ends up looking like the following incredibly messy clause: ``` ORDER BY CASE @dir1 WHEN 'desc' THEN CASE @sortCol1 WHEN @col1 THEN [storagedatetime] WHEN @col2 THEN [vehicleid] END END DESC, CASE @dir1 WHEN 'asc' THEN CASE @sortCol1 WHEN @col1 THEN [storagedatetime] WHEN @col2 THEN [vehicleid] END END, CASE @dir2 WHEN 'desc' THEN CASE @sortCol2 WHEN @col1 THEN [storagedatetime] WHEN @col2 THEN [vehicleid] END END DESC, CASE @dir2 WHEN 'asc' THEN CASE @sortCol2 WHEN @col1 THEN [storagedatetime] WHEN @col2 THEN [vehicleid] END END ``` Obviously this is a very stripped down example. The real stuff, since we usually have four or five columns to support sorting on, each with possible secondary or even a third column to sort on in addition to that (for example date descending then sorted secondarily by name ascending) and each supporting bi-directional sorting which effectively doubles the number of cases. Yeah... it gets hairy really quick. The idea is that one could "easily" change the sort cases such that vehicleid gets sorted before the storagedatetime... but the pseudo-flexibility, at least in this simple example, really ends there. Essentially, each case that fails a test (because our sort method doesn't apply to it this time around) renders a NULL value. And thus you end up with a clause that functions like the following: ``` ORDER BY NULL DESC, NULL, [storagedatetime] DESC, blah blah ``` You get the idea. It works because SQL Server effectively ignores null values in order by clauses. This is incredibly hard to maintain, as anyone with any basic working knowledge of SQL can probably see. If I've lost any of you, don't feel bad. It took us a long time to get it working and we still get confused trying to edit it or create new ones like it. Thankfully it doesn't need changing often, otherwise it would quickly become "not worth the trouble." Yet it *did* work. --- My question is then: **is there a better way?** I'm okay with solutions other than Stored Procedure ones, as I realize it may just not be the way to go. Preferably, I'd like to know if anyone can do it better within the Stored Procedure, but if not, how do you all handle letting the user dynamically sort tables of data (bi-directionally, too) with ASP.NET? And thank you for reading (or at least skimming) such a long question! PS: Be glad I didn't show my example of a stored procedure that supports dynamic sorting, dynamic filtering/text-searching of columns, pagination via ROWNUMBER() OVER, *AND* try...catch with transaction rollbacking on errors... "behemoth-sized" doesn't even begin to describe them. --- **Update:** * I would like to **avoid dynamic SQL**. Parsing a string together and running an EXEC on it defeats a lot of the purpose of having a stored procedure in the first place. Sometimes I wonder though if the cons of doing such a thing wouldn't be worth it, at least in these special dynamic sorting cases. Still, I always feel dirty whenever I do dynamic SQL strings like that — like I'm still living in the Classic ASP world. * A lot of the reason we want stored procedures in the first place is for **security**. I don't get to make the call on security concerns, only suggest solutions. With SQL Server 2005 we can set permissions (on a per-user basis if need be) at the schema level on individual stored procedures and then deny any queries against the tables directly. Critiquing the pros and cons of this approach is perhaps for another question, but again it's not my decision. I'm just the lead code monkey. :)
Yeah, it's a pain, and the way you're doing it looks similar to what I do: ``` order by case when @SortExpr = 'CustomerName' and @SortDir = 'ASC' then CustomerName end asc, case when @SortExpr = 'CustomerName' and @SortDir = 'DESC' then CustomerName end desc, ... ``` This, to me, is still much better than building dynamic SQL from code, which turns into a scalability and maintenance nightmare for DBAs. What I do from code is refactor the paging and sorting so I at least don't have a lot of repetition there with populating values for `@SortExpr` and `@SortDir`. As far as the SQL is concerned, keep the design and formatting the same between different stored procedures, so it's at least neat and recognizable when you go in to make changes.
149,388
<p>Was wondering if anyone knows, or has pointers to good documentation that discusses, the low-level implementation details of Cocoa's 'performSelectorOnMainThread:' method.</p> <p>My best guess, and one I think is probably pretty close, is that it uses mach ports or an abstraction on top of them to provide intra-thread communication, passing selector information along as part of the mach message.</p> <p>Right? Wrong? Thanks!</p> <p><strong>Update 09:39AMPST</strong></p> <p>Thank you Evan DiBiase and Mecki for the answers, but to clarify: I understand what happens in the run loop, but what I'm looking for an answer to is; "<em>where</em> is the method getting queued? <em>how</em> is the selector information getting passed into the queue?" Looking for more than Apple's doc info: I've read 'em</p> <p><strong>Update 14:21PST</strong></p> <p>Chris Hanson brings up a good point in a comment: my objective here is not to learn the underlying mechanisms in order to take advantage of them in my own code. Rather, I'm just interested in a better conceptual understanding of the process of signaling another thread to execute code. As I said, my own research leads me to believe that it's takes advantage of mach messaging for IPC to pass selector information between threads, but I'm specifically looking for <strong>concrete</strong> information on what is happening, so I can be sure I'm understanding things <em>correctly</em>. Thanks! </p> <p><strong>Update 03/06/09</strong></p> <p>I've opened a bounty on this question because I'd really like to see it answered, but if you are trying to collect please make sure you read <strong>everything</strong>, including all currently posed answers, comments to both these answers and to my original question, and the update text I posted above. I'm look for the <strong>lowest-level detail</strong> of the mechanism used by <code>performSelectorOnMainThread:</code> and the like, and as I mentioned earlier, I suspect it has something to do with Mach ports but I'd really like to know for sure. The bounty will not be awarded unless I can <strong>confirm</strong> the answer given is correct. Thanks everyone!</p>
[ { "answer_id": 149448, "author": "Evan DiBiase", "author_id": 2399475, "author_profile": "https://Stackoverflow.com/users/2399475", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Refer...
2008/09/29
[ "https://Stackoverflow.com/questions/149388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23498/" ]
Was wondering if anyone knows, or has pointers to good documentation that discusses, the low-level implementation details of Cocoa's 'performSelectorOnMainThread:' method. My best guess, and one I think is probably pretty close, is that it uses mach ports or an abstraction on top of them to provide intra-thread communication, passing selector information along as part of the mach message. Right? Wrong? Thanks! **Update 09:39AMPST** Thank you Evan DiBiase and Mecki for the answers, but to clarify: I understand what happens in the run loop, but what I'm looking for an answer to is; "*where* is the method getting queued? *how* is the selector information getting passed into the queue?" Looking for more than Apple's doc info: I've read 'em **Update 14:21PST** Chris Hanson brings up a good point in a comment: my objective here is not to learn the underlying mechanisms in order to take advantage of them in my own code. Rather, I'm just interested in a better conceptual understanding of the process of signaling another thread to execute code. As I said, my own research leads me to believe that it's takes advantage of mach messaging for IPC to pass selector information between threads, but I'm specifically looking for **concrete** information on what is happening, so I can be sure I'm understanding things *correctly*. Thanks! **Update 03/06/09** I've opened a bounty on this question because I'd really like to see it answered, but if you are trying to collect please make sure you read **everything**, including all currently posed answers, comments to both these answers and to my original question, and the update text I posted above. I'm look for the **lowest-level detail** of the mechanism used by `performSelectorOnMainThread:` and the like, and as I mentioned earlier, I suspect it has something to do with Mach ports but I'd really like to know for sure. The bounty will not be awarded unless I can **confirm** the answer given is correct. Thanks everyone!
Yes, it does use Mach ports. What happens is this: 1. A block of data encapsulating the perform info (the target object, the selector, the optional object argument to the selector, etc.) is enqueued in the thread's run loop info. This is done using `@synchronized`, which ultimately uses `pthread_mutex_lock`. 2. CFRunLoopSourceSignal is called to signal that the source is ready to fire. 3. CFRunLoopWakeUp is called to let the main thread's run loop know it's time to wake up. This is done using mach\_msg. From the Apple docs: > > Version 1 sources are managed by the run loop and kernel. These sources use Mach ports to signal when the sources are ready to fire. A source is automatically signaled by the kernel when a message arrives on the source’s Mach port. The contents of the message are given to the source to process when the source is fired. The run loop sources for CFMachPort and CFMessagePort are currently implemented as version 1 sources. > > > I'm looking at a stack trace right now, and this is what it shows: ``` 0 mach_msg 1 CFRunLoopWakeUp 2 -[NSThread _nq:] 3 -[NSObject(NSThreadPerformAdditions) performSelector:onThread:withObject:waitUntilDone:modes:] 4 -[NSObject(NSThreadPerformAdditions) performSelectorOnMainThread:withObject:waitUntilDone:] ``` Set a breakpoint on mach\_msg and you'll be able to confirm it.
149,394
<p>I have a winforms application, the issue has to do with threading. Since I am calling 'MyCustomCode() which creates a new thread, and calls the method 'SomeMethod()' which then accesses MessageBox.Show(...).</p> <p>The problem has to do with threading, since the newly created thread is trying to access a control that was created on another thread.</p> <p>I am getting the error:</p> <p>Cross-thread operation not valid: Control 'TestForm' accessed from a thread other than the thread it was created on.</p> <pre><code>public TestForm() { InitializeComponent(); // custom code // MyCustomCode(); } public void SomeMethod() { // ***** This causes an error **** MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } private void InitializeAutoUpdater() { // Seperate thread is spun to keep polling for updates ThreadStart ts = new ThreadStart(SomeMethod); pollThread = new Thread(ts); pollThread.Start(); } </code></pre> <p><b>Update</b></p> <p>If you look at this example <a href="http://www.codeproject.com/KB/cs/vanillaupdaterblock.aspx" rel="noreferrer">http://www.codeproject.com/KB/cs/vanillaupdaterblock.aspx</a>, the method CheckAndUpdate is calling MessageBox.Show(..) that is what my problem is. I would have thought that code was good to go!</p> <p><b>Funny thing</b> is that this code was working just fine on Friday???</p>
[ { "answer_id": 149404, "author": "albertein", "author_id": 23020, "author_profile": "https://Stackoverflow.com/users/23020", "pm_score": 3, "selected": false, "text": "<p>You cannot acces UI elements from multiple threads.</p>\n\n<p>One way to solve this is to call the Invoke method of a...
2008/09/29
[ "https://Stackoverflow.com/questions/149394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a winforms application, the issue has to do with threading. Since I am calling 'MyCustomCode() which creates a new thread, and calls the method 'SomeMethod()' which then accesses MessageBox.Show(...). The problem has to do with threading, since the newly created thread is trying to access a control that was created on another thread. I am getting the error: Cross-thread operation not valid: Control 'TestForm' accessed from a thread other than the thread it was created on. ``` public TestForm() { InitializeComponent(); // custom code // MyCustomCode(); } public void SomeMethod() { // ***** This causes an error **** MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } private void InitializeAutoUpdater() { // Seperate thread is spun to keep polling for updates ThreadStart ts = new ThreadStart(SomeMethod); pollThread = new Thread(ts); pollThread.Start(); } ``` **Update** If you look at this example <http://www.codeproject.com/KB/cs/vanillaupdaterblock.aspx>, the method CheckAndUpdate is calling MessageBox.Show(..) that is what my problem is. I would have thought that code was good to go! **Funny thing** is that this code was working just fine on Friday???
You cannot acces UI elements from multiple threads. One way to solve this is to call the Invoke method of a control with a delegate to the function wich use the UI elements (like the message box). Somethin like: ``` public delegate void InvokeDelegate(); public void SomeMethod() { button1.Invoke((InvokeDelegate)doUIStuff); } void doUIStuff() { MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } ```
149,395
<p>We have a Windows machine running SQL Server 2005, and we need to be able to run some database queries on it from a Linux box. What are some of the recommended ways of doing this? Ideally, we would want a command-line utility similar to sqlcmd on Windows.</p>
[ { "answer_id": 149418, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 6, "selected": true, "text": "<p><a href=\"http://www.freetds.org\" rel=\"noreferrer\">FreeTDS</a> + <a href=\"http://www.unixodbc.org\" rel=\"nore...
2008/09/29
[ "https://Stackoverflow.com/questions/149395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4828/" ]
We have a Windows machine running SQL Server 2005, and we need to be able to run some database queries on it from a Linux box. What are some of the recommended ways of doing this? Ideally, we would want a command-line utility similar to sqlcmd on Windows.
[FreeTDS](http://www.freetds.org) + [unixODBC](http://www.unixodbc.org) or [iODBC](http://www.iodbc.org) Install first FreeTDS, then configure one of the two ODBC engines to use FreeTDS as its ODBC driver. Then use the commandline interface of the ODBC engine. unixODBC has isql, iODBC has iodbctest You can also use your favorite programming language (I've successfully used Perl, C, Python and Ruby to connect to MSSQL) I'm personally using FreeTDS + iODBC: ``` $more /etc/freetds/freetds.conf [10.0.1.251] host = 10.0.1.251 port = 1433 tds version = 8.0 $ more /etc/odbc.ini [ACCT] Driver = /usr/local/freetds/lib/libtdsodbc.so Description = ODBC to SQLServer via FreeTDS Trace = No Servername = 10.0.1.251 Database = accounts_ver8 ```
149,416
<p>I have a curious question about efficiency. Say I have a field on a database that is just a numeric digit that represents something else. Like, a value of 1 means the term is 30 days.</p> <p>Would it be better (more efficient) to code a SELECT statement like this...</p> <pre><code>SELECT CASE TermId WHEN 1 THEN '30 days' WHEN 2 THEN '60 days' END AS Term FROM MyTable </code></pre> <p>...and bind the results directly to the GridView, or would it be better to evaluate the TermId field in RowDataBound event of the GridView and change the cell text accordingly?</p> <p>Don't worry about extensibility or anything like that, I am only concerned about the differences in overall efficiency. For what it's worth, the database resides on the web server.</p>
[ { "answer_id": 149469, "author": "hurcane", "author_id": 21363, "author_profile": "https://Stackoverflow.com/users/21363", "pm_score": 0, "selected": false, "text": "<p>For a number of reasons, I would process the translation in the grid view.</p>\n\n<p>Reason #1: SQL resource is shared....
2008/09/29
[ "https://Stackoverflow.com/questions/149416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/54420/" ]
I have a curious question about efficiency. Say I have a field on a database that is just a numeric digit that represents something else. Like, a value of 1 means the term is 30 days. Would it be better (more efficient) to code a SELECT statement like this... ``` SELECT CASE TermId WHEN 1 THEN '30 days' WHEN 2 THEN '60 days' END AS Term FROM MyTable ``` ...and bind the results directly to the GridView, or would it be better to evaluate the TermId field in RowDataBound event of the GridView and change the cell text accordingly? Don't worry about extensibility or anything like that, I am only concerned about the differences in overall efficiency. For what it's worth, the database resides on the web server.
Efficiency probably wouldn't matter here - code maintainability does though. Ask yourself - will these values change? What if they do? What would I need to do after 2 years of use if these values change? If it becomes evident that scripting them in SQL would mean better maintainability (easier to change), then do it in a stored Procedure. If it's easier to change them in code later, then do that. The benefits from doing either are quite low, as the code doesn't look complex at all.
149,439
<p>How can you avoid circular dependencies when you're designing two classes with a producer/consumer relationship? Here ListenerImpl needs a reference to Broadcaster in order to register/unregister itself, and Broadcaster needs a reference back to the Listeners in order to send messages. This example is in Java but it can apply to any OO language.</p> <pre><code>public interface Listener { void callBack(Object arg); } public class ListenerImpl implements Listener { public ListenerImpl(Broadcaster b) { b.register(this); } public void callBack(Object arg) { ... } public void shutDown() { b.unregister(this); } } public class Broadcaster { private final List listeners = new ArrayList(); public void register(Listener lis) { listeners.add(lis); } public void unregister(Listener lis) {listeners.remove(lis); } public void broadcast(Object arg) { for (Listener lis : listeners) { lis.callBack(arg); } } } </code></pre>
[ { "answer_id": 149457, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 4, "selected": true, "text": "<p>I don't see that being a circular dependency.</p>\n\n<p>Listener depends on nothing.</p>\n\n<p>ListenerImpl depends on Liste...
2008/09/29
[ "https://Stackoverflow.com/questions/149439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16399/" ]
How can you avoid circular dependencies when you're designing two classes with a producer/consumer relationship? Here ListenerImpl needs a reference to Broadcaster in order to register/unregister itself, and Broadcaster needs a reference back to the Listeners in order to send messages. This example is in Java but it can apply to any OO language. ``` public interface Listener { void callBack(Object arg); } public class ListenerImpl implements Listener { public ListenerImpl(Broadcaster b) { b.register(this); } public void callBack(Object arg) { ... } public void shutDown() { b.unregister(this); } } public class Broadcaster { private final List listeners = new ArrayList(); public void register(Listener lis) { listeners.add(lis); } public void unregister(Listener lis) {listeners.remove(lis); } public void broadcast(Object arg) { for (Listener lis : listeners) { lis.callBack(arg); } } } ```
I don't see that being a circular dependency. Listener depends on nothing. ListenerImpl depends on Listener and Broadcaster Broadcaster depends on Listener. ``` Listener ^ ^ / \ / \ Broadcaster <-- ListenerImpl ``` All arrows end at Listener. There's no cycle. So, I think you're OK.
149,463
<p>I have this code inside a class:</p> <pre><code>void SendStones() { int currenthole = hole; int lastplace = 0; for(int i=0;i&lt;stns.size();i++) { while(1) {//Calculate new currenthole if(currenthole == 13) { currenthole = 7; break;} if(currenthole == 14) { currenthole = 6; break;} if((currenthole&lt;=12 &amp;&amp; currenthole &gt; 7) || (currenthole&lt;=6 &amp;&amp; currenthole &gt; 1)) { currenthole--; break;} } lastplace = stns.size()-1; hole[currenthole]-&gt;ReciveStone(stns[lastplace]);//PROBLEM stns.pop_back(); } } vector&lt;Stones*&gt; stns; </code></pre> <p>so it makes this error: invalid types `int[int]' for array subscript </p> <p>what's the problem?i don't understand. Thanks.</p>
[ { "answer_id": 149482, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 2, "selected": false, "text": "<p>It looks like hole is a simple int, and you're trying to subscript it. Is that what you mean to do? Where is ho...
2008/09/29
[ "https://Stackoverflow.com/questions/149463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have this code inside a class: ``` void SendStones() { int currenthole = hole; int lastplace = 0; for(int i=0;i<stns.size();i++) { while(1) {//Calculate new currenthole if(currenthole == 13) { currenthole = 7; break;} if(currenthole == 14) { currenthole = 6; break;} if((currenthole<=12 && currenthole > 7) || (currenthole<=6 && currenthole > 1)) { currenthole--; break;} } lastplace = stns.size()-1; hole[currenthole]->ReciveStone(stns[lastplace]);//PROBLEM stns.pop_back(); } } vector<Stones*> stns; ``` so it makes this error: invalid types `int[int]' for array subscript what's the problem?i don't understand. Thanks.
It looks like hole is a simple int, and you're trying to subscript it. Is that what you mean to do? Where is hole declared?
149,474
<p>This XML file contained archived news stories for all of last year. I was asked to sort these stories by story categor[y|ies] into new XML files.</p> <pre><code>big_story_export.xml </code></pre> <p>turns into</p> <pre><code>lifestyles.xml food.xml nascar.xml </code></pre> <p>...and so on.</p> <p>I got the job done using a one-off python script, <em>however</em>, <strong>I originally attempted this using XSLT</strong>. This resulted in frustration as my XPATH selections were crapping the bed. Test files were transformed perfectly, but putting the big file up against my style sheet resulted in ...<em>nothing</em>.</p> <p>What strategies do you recommend for ensuring that files like this will run through XSLT? <em>This was handed to me by a vendor, so imagine that I don't have a lot of leverage when it comes to defining the structure of this file.</em></p> <p>If you guys want code samples, I'll put some together. </p> <p>If anything, I'd be satisfied with some tips for making XML+XSLT work together smoothly.</p> <hr> <p>@Sklivvz</p> <p>I was using python's libxml2 &amp; libxslt to process this. I'm looking into xsltproc now. </p> <p>It seems like a good tool for these one-off situations. Thanks!</p> <hr> <p>@diomidis-spinellis</p> <p>It's well-formed, though (as mentioned) I don't have faculties to discover it's validity.</p> <p>As for writing a Schema, I like the idea. </p> <p>The amount of time I invest in getting this one file validated would be impractical if it were a one-time thing, though I foresee having to handle more files like this from our vendor.</p> <p>Writing a schema (and submitting it to the vendor) would be an excellent long-term strategy for managing XML funk like this. Thanks!</p>
[ { "answer_id": 149495, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 2, "selected": false, "text": "<p>What language/parser were you using?<br>\nFor large files I try to use Unix command line tools.<br>\nThey are usually muc...
2008/09/29
[ "https://Stackoverflow.com/questions/149474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22491/" ]
This XML file contained archived news stories for all of last year. I was asked to sort these stories by story categor[y|ies] into new XML files. ``` big_story_export.xml ``` turns into ``` lifestyles.xml food.xml nascar.xml ``` ...and so on. I got the job done using a one-off python script, *however*, **I originally attempted this using XSLT**. This resulted in frustration as my XPATH selections were crapping the bed. Test files were transformed perfectly, but putting the big file up against my style sheet resulted in ...*nothing*. What strategies do you recommend for ensuring that files like this will run through XSLT? *This was handed to me by a vendor, so imagine that I don't have a lot of leverage when it comes to defining the structure of this file.* If you guys want code samples, I'll put some together. If anything, I'd be satisfied with some tips for making XML+XSLT work together smoothly. --- @Sklivvz I was using python's libxml2 & libxslt to process this. I'm looking into xsltproc now. It seems like a good tool for these one-off situations. Thanks! --- @diomidis-spinellis It's well-formed, though (as mentioned) I don't have faculties to discover it's validity. As for writing a Schema, I like the idea. The amount of time I invest in getting this one file validated would be impractical if it were a one-time thing, though I foresee having to handle more files like this from our vendor. Writing a schema (and submitting it to the vendor) would be an excellent long-term strategy for managing XML funk like this. Thanks!
This sounds like a bug in the large XML file or the XSLT processor. There are two things you should check on your file. 1. Is the file well-formed XML? That is, are all tags and attributes properly terminated and matched? An XML processor, like [xmlstarlet](http://xmlstar.sourceforge.net/), can tell you that. 2. Does the file contain valid XML? For this you need a schema and an XML validator ([xmlstarlet](http://xmlstar.sourceforge.net/) can do this trick as well). I suggest you invest some effort to write the schema definition of your file. It will simplify a lot your debugging, because you can then easily pinpoint the exact source of problems you may be having. If the file is well-formed and valid, but the XSLT processor still refuses to give you the results you would expect, you can be sure that the problem lies in the processor, and you should try a different one.
149,479
<p>Well, it seems simple enough, but I can't find a way to add a caption to an equation. The caption is needed to explain the variables used in the equation, so some kind of table-like structure to keep it all aligned and pretty would be great.</p>
[ { "answer_id": 149494, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 4, "selected": false, "text": "<p>You may want to look at <a href=\"http://tug.ctan.org/tex-archive/macros/latex/contrib/float/\" re...
2008/09/29
[ "https://Stackoverflow.com/questions/149479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2841/" ]
Well, it seems simple enough, but I can't find a way to add a caption to an equation. The caption is needed to explain the variables used in the equation, so some kind of table-like structure to keep it all aligned and pretty would be great.
The `\caption` command is restricted to floats: you will need to place the equation in a figure or table environment (or a new kind of floating environment). For example: ``` \begin{figure} \[ E = m c^2 \] \caption{A famous equation} \end{figure} ``` The point of floats is that you let LaTeX determine their placement. If you want to equation to appear in a fixed position, don't use a float. The `\captionof` command of the [caption package](http://www.tex.ac.uk/tex-archive/macros/latex/contrib/caption/caption-eng.pdf) can be used to place a caption outside of a floating environment. It is used like this: ``` \[ E = m c^2 \] \captionof{figure}{A famous equation} ``` This will also produce an entry for the `\listoffigures`, if your document has one. To align parts of an equation, take a look at the [`eqnarray` environment](http://www.eng.cam.ac.uk/help/tpl/textprocessing/teTeX/latex/latex2e-html/ltx-223.html), or some of the environments of the [amsmath](http://www.ams.org/tex/amslatex.html) package: align, gather, multiline,...
149,484
<p>I want to create a VB.NET generic factory method that creates instances of classes (as a home-grown inversion of control container). If I pass the interface IDoSomething as the generic parameter, I want to return an instance of DoSomething (that implements IDoSomething). I cannot figure out the syntax of the if statement. I want to write something like:</p> <pre><code>Public Function Build(Of T) as T If T Is IDoSomething then Return New DoSomething() ElseIf T Is IAndSoOn Then Return New AndSoOn() Else Throw New WhatWereYouThinkingException("Bad") End If End Sub </code></pre> <p>But this code does not compile.</p>
[ { "answer_id": 149536, "author": "codeConcussion", "author_id": 1321, "author_profile": "https://Stackoverflow.com/users/1321", "pm_score": 2, "selected": false, "text": "<pre><code>Public Function Build(Of T) As T\n Dim foo As Type = GetType(T)\n\n If foo Is GetType(IDoSomething) Then...
2008/09/29
[ "https://Stackoverflow.com/questions/149484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want to create a VB.NET generic factory method that creates instances of classes (as a home-grown inversion of control container). If I pass the interface IDoSomething as the generic parameter, I want to return an instance of DoSomething (that implements IDoSomething). I cannot figure out the syntax of the if statement. I want to write something like: ``` Public Function Build(Of T) as T If T Is IDoSomething then Return New DoSomething() ElseIf T Is IAndSoOn Then Return New AndSoOn() Else Throw New WhatWereYouThinkingException("Bad") End If End Sub ``` But this code does not compile.
``` Public Function Build(Of T) As T Dim foo As Type = GetType(T) If foo Is GetType(IDoSomething) Then Return New DoSomething() ... End If End Function ```
149,485
<p>Like many projects, we deploy to many environments, QA, UA, Developer trunks, etc..</p> <p>What is the best way to store sensitive configuration parameters in SVN? Or, should you not and just maintain a smaller unversioned file with credentials in it on the server?</p> <p>Mainly, we do not want to expose production credentials to every developer.</p>
[ { "answer_id": 149497, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 0, "selected": false, "text": "<p>I would not store configuration information in the repository at all. That way you don't have to worry about SVN...
2008/09/29
[ "https://Stackoverflow.com/questions/149485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Like many projects, we deploy to many environments, QA, UA, Developer trunks, etc.. What is the best way to store sensitive configuration parameters in SVN? Or, should you not and just maintain a smaller unversioned file with credentials in it on the server? Mainly, we do not want to expose production credentials to every developer.
I'd rather provide configuration examples than real config files. In my project there is `setup.default.php` file in root directory that every user need to copy as `setup.php` and amend to match local environment. Additionally, to prevent checking in back customised setup files there is a rule for it in `.svnignore`. ``` $ echo 'setup.php' > .svnignore $ svn propset svn:ignore -F .svnignore . ```
149,491
<p>I've been arguing with my coworkers about Pascal casing (upper camel case) vs. lower <a href="http://en.wikipedia.org/wiki/CamelCase" rel="noreferrer">CamelCasing</a>. They are used to lower camel casing for everything from table names in SQL databases to property naming in C# code but I like Pascal casing better, lower camel casing for variables and Pascal casing for properties:</p> <pre><code>string firstName; public string FirstName { ... } </code></pre> <p>But they are used to this:</p> <pre><code>string _firstname; public string firstName { ... } </code></pre> <p>I try to keep up with their "standard" so the code looks the same but I just don't like it.</p> <p>I've seen that at least the .NET framework uses this convention and that is how I try to keep my code, e.g.:</p> <pre><code>System.Console.WriteLine("string") </code></pre> <p>What do you use/prefer and why? I'm sorry if somebody else asked this question but I searched and did not find anything.</p> <p><strong>Update:</strong> I've given a method example and not a property but it's the same. As I stated in the first paragraph my colleagues use the Pascal convention for everything (variables, methods, table names, etc.)</p>
[ { "answer_id": 149507, "author": "Dennis S.", "author_id": 22250, "author_profile": "https://Stackoverflow.com/users/22250", "pm_score": 2, "selected": false, "text": "<p>I (and my team) prefer to reserve initial capitals for class names. </p>\n\n<p>Why? Java standards propagating, I th...
2008/09/29
[ "https://Stackoverflow.com/questions/149491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14533/" ]
I've been arguing with my coworkers about Pascal casing (upper camel case) vs. lower [CamelCasing](http://en.wikipedia.org/wiki/CamelCase). They are used to lower camel casing for everything from table names in SQL databases to property naming in C# code but I like Pascal casing better, lower camel casing for variables and Pascal casing for properties: ``` string firstName; public string FirstName { ... } ``` But they are used to this: ``` string _firstname; public string firstName { ... } ``` I try to keep up with their "standard" so the code looks the same but I just don't like it. I've seen that at least the .NET framework uses this convention and that is how I try to keep my code, e.g.: ``` System.Console.WriteLine("string") ``` What do you use/prefer and why? I'm sorry if somebody else asked this question but I searched and did not find anything. **Update:** I've given a method example and not a property but it's the same. As I stated in the first paragraph my colleagues use the Pascal convention for everything (variables, methods, table names, etc.)
I use what the Framework uses, as it's the de-facto best practice. However, so long as the code in your company is **consistently** using their style, then you're much better off getting used to it. If every developer has their own standard, then there's no standard at all.
149,500
<p>What does the following code do in C/C++?</p> <pre><code>if (blah(), 5) { //do something } </code></pre>
[ { "answer_id": 149514, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 7, "selected": true, "text": "<p>Comma operator is applied and the value 5 is used to determine the conditional's true/false.</p>\n\n<p>It will execute bla...
2008/09/29
[ "https://Stackoverflow.com/questions/149500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20630/" ]
What does the following code do in C/C++? ``` if (blah(), 5) { //do something } ```
Comma operator is applied and the value 5 is used to determine the conditional's true/false. It will execute blah() and get something back (presumably), then the comma operator is employed and 5 will be the only thing that is used to determine the true/false value for the expression. --- Note that the , operator could be overloaded for the return type of the blah() function (which wasn't specified), making the result non-obvious.
149,506
<p>I'm investigating an annotation-based approach to validating Spring beans using <a href="https://springmodules.dev.java.net/" rel="nofollow noreferrer">spring modules</a>. In <a href="http://wheelersoftware.com/articles/spring-bean-validation-framework.html" rel="nofollow noreferrer">this tutorial</a>, the following bean (getters and setters omitted) is used as an example:</p> <pre><code>public final class User { @NotBlank @Length(max = 80) private String name; @NotBlank @Email @Length(max = 80) private String email; @NotBlank @Length(max = 4000) private String text; } </code></pre> <p>The error message that is used if a particular validation rule is disobeyed should follow this format:</p> <pre><code>bean-class.bean-propery[validation-rule]=Validation Error message </code></pre> <p>Examples for the class shown above include:</p> <pre><code>User.email[not.blank]=Please enter your e-mail address. User.email[email]=Please enter a valid e-mail address. User.email[length]=Please enter no more than {2} characters. </code></pre> <p>The fact that the message keys contain the class name presents a couple of problems:</p> <ol> <li>If the class is renamed, the message keys also need to be changed</li> <li><p>If I have another class (e.g. Person) with an email property that is validated identically to User.email, I need to duplicate the messages, e.g.</p> <p>Person.email[not.blank]=Please enter your e-mail address.<br> Person.email[email]=Please enter a valid e-mail address.<br> Person.email[length]=Please enter no more than {2} characters.</p></li> </ol> <p>In fact, the documentation claims that is possible to configure a default message for a particular rule (e.g. @Email) like this:</p> <pre><code>email=email address is invalid </code></pre> <p>This default message should be used if a bean-specific message for the rule cannot be found. However, my experience is that this simply does not work. </p> <p>An alternative mechanism for avoiding duplicate messages is to pass the key of the error message to the rule annotation. For example, assume I have defined the following default error message for the @Email rule</p> <pre><code>badEmail=Email address is invalid </code></pre> <p>This message should be used if I annotate the relevant property like this:</p> <pre><code>@Email(errorCode="badEmail") private String email; </code></pre> <p>However I tried this, out and again, it just doesn't seem to work. Has anyone found a way to avoid duplicating error messages when using this validation framework?</p>
[ { "answer_id": 176039, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 4, "selected": true, "text": "<p>I took a quick look at the <a href=\"https://springmodules.dev.java.net/source/browse/%2Acheckout%2A/springmodules/www/doc...
2008/09/29
[ "https://Stackoverflow.com/questions/149506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
I'm investigating an annotation-based approach to validating Spring beans using [spring modules](https://springmodules.dev.java.net/). In [this tutorial](http://wheelersoftware.com/articles/spring-bean-validation-framework.html), the following bean (getters and setters omitted) is used as an example: ``` public final class User { @NotBlank @Length(max = 80) private String name; @NotBlank @Email @Length(max = 80) private String email; @NotBlank @Length(max = 4000) private String text; } ``` The error message that is used if a particular validation rule is disobeyed should follow this format: ``` bean-class.bean-propery[validation-rule]=Validation Error message ``` Examples for the class shown above include: ``` User.email[not.blank]=Please enter your e-mail address. User.email[email]=Please enter a valid e-mail address. User.email[length]=Please enter no more than {2} characters. ``` The fact that the message keys contain the class name presents a couple of problems: 1. If the class is renamed, the message keys also need to be changed 2. If I have another class (e.g. Person) with an email property that is validated identically to User.email, I need to duplicate the messages, e.g. Person.email[not.blank]=Please enter your e-mail address. Person.email[email]=Please enter a valid e-mail address. Person.email[length]=Please enter no more than {2} characters. In fact, the documentation claims that is possible to configure a default message for a particular rule (e.g. @Email) like this: ``` email=email address is invalid ``` This default message should be used if a bean-specific message for the rule cannot be found. However, my experience is that this simply does not work. An alternative mechanism for avoiding duplicate messages is to pass the key of the error message to the rule annotation. For example, assume I have defined the following default error message for the @Email rule ``` badEmail=Email address is invalid ``` This message should be used if I annotate the relevant property like this: ``` @Email(errorCode="badEmail") private String email; ``` However I tried this, out and again, it just doesn't seem to work. Has anyone found a way to avoid duplicating error messages when using this validation framework?
I took a quick look at the [BeanValidator API](https://springmodules.dev.java.net/source/browse/%2Acheckout%2A/springmodules/www/docs/javadocs/0.8/org/springmodules/validation/bean/BeanValidator.html), and it looks like you might want to try the *errorCodeConverter* property. You would need to implement your own [ErrorCodeConverter](https://springmodules.dev.java.net/source/browse/%2Acheckout%2A/springmodules/www/docs/javadocs/0.8/org/springmodules/validation/bean/converter/ErrorCodeConverter.html), or use one of the provided implementations? ``` .... <bean id="validator" class="org.springmodules.validation.bean.BeanValidator" p:configurationLoader-ref="configurationLoader" p:errorCodeConverter-ref="errorCodeConverter" /> <bean id="errorCodeConverter" class="contact.MyErrorCodeConverter" /> .... ``` *Note: configurationLoader is another bean defined in the config XML used in the tutorial* Example converter: ``` package contact; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springmodules.validation.bean.converter.ErrorCodeConverter; public class MyErrorCodeConverter implements ErrorCodeConverter { private Log log = LogFactory.getLog(MyErrorCodeConverter.class); @Override public String convertPropertyErrorCode(String errorCode, Class clazz, String property) { log.error(String.format("Property %s %s %s", errorCode, clazz.getClass().getName(), property)); return errorCode; // <------ use the errorCode only } @Override public String convertGlobalErrorCode(String errorCode, Class clazz) { log.error(String.format("Global %s %s", errorCode, clazz.getClass().getName())); return errorCode; } } ``` Now the properties should work: ``` MyEmailErrorCode=Bad email class Foo { @Email(errorCode="MyEmailErrorCode") String email } ```
149,573
<p>Using jQuery, how do you check if there is an option selected in a select menu, and if not, assign one of the options as selected.</p> <p>(The select is generated with a maze of PHP functions in an app I just inherited, so this is a quick fix while I get my head around those :)</p>
[ { "answer_id": 149592, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 2, "selected": false, "text": "<p>Look at the <a href=\"http://www.w3schools.com/htmldom/prop_select_selectedindex.asp\" rel=\"nofollow noreferrer\">selec...
2008/09/29
[ "https://Stackoverflow.com/questions/149573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4196/" ]
Using jQuery, how do you check if there is an option selected in a select menu, and if not, assign one of the options as selected. (The select is generated with a maze of PHP functions in an app I just inherited, so this is a quick fix while I get my head around those :)
While I'm not sure about exactly what you want to accomplish, this bit of code worked for me. ``` <select id="mySelect" multiple="multiple"> <option value="1">First</option> <option value="2">Second</option> <option value="3">Third</option> <option value="4">Fourth</option> </select> <script type="text/javascript"> $(document).ready(function() { if (!$("#mySelect option:selected").length) { $("#mySelect option[value='3']").attr('selected', 'selected'); } }); </script> ```
149,600
<p>Do you know any good tools for nicely formatting messy php code? Preferably a script for Aptana/Eclipse, but a standalone tool will do too.</p>
[ { "answer_id": 149612, "author": "Ian P", "author_id": 10853, "author_profile": "https://Stackoverflow.com/users/10853", "pm_score": 3, "selected": false, "text": "<p>If you use Zend Development Environment, you can use the Indent Code feature (Ctrl+Shift+F).</p>\n" }, { "answer_...
2008/09/29
[ "https://Stackoverflow.com/questions/149600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/556/" ]
Do you know any good tools for nicely formatting messy php code? Preferably a script for Aptana/Eclipse, but a standalone tool will do too.
[PHP Code Beautifier](http://www.waterproof.fr/products/phpCodeBeautifier/) is a useful free tool that should do what you're after, although their [download page](http://www.waterproof.fr/products/phpCodeBeautifier/download.php) does require an account to be created. > > The tool has been declined into 3 versions: > > > * A GUI version which allow to process file visually. > * A command line version which allow to be batched or integrated with other tools (CVS, SubVersion, IDE ...). > * As an integrated tool of PHPEdit. > > > Basically, it'll turn: ``` if($code == BAD){$action = REWRITE;}else{$action = KEEP;} for($i=0; $i<10;$i++){while($j>0){$j++;doCall($i+$j);if($k){$k/=10;}}} ``` into ``` if ($code == BAD) { $action = REWRITE; } else { $action = KEEP; } for($i = 0; $i < 10;$i++) { while ($j > 0) { $j++; doCall($i + $j); if ($k) { $k /= 10; } } } ```
149,609
<p>Does the using catch the exception or throw it? i.e. </p> <pre><code>using (StreamReader rdr = File.OpenText("file.txt")) { //do stuff } </code></pre> <p>If the streamreader throws an exception is it caught by using or thrown so the calling function can handle it?</p>
[ { "answer_id": 149623, "author": "hometoast", "author_id": 2009, "author_profile": "https://Stackoverflow.com/users/2009", "pm_score": 2, "selected": false, "text": "<p>If you don't specifically catch an exception it's thrown up the stack until something does</p>\n" }, { "answer_...
2008/09/29
[ "https://Stackoverflow.com/questions/149609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21299/" ]
Does the using catch the exception or throw it? i.e. ``` using (StreamReader rdr = File.OpenText("file.txt")) { //do stuff } ``` If the streamreader throws an exception is it caught by using or thrown so the calling function can handle it?
using statements do not eat exceptions. All "Using" does is scope your object to the using block, and automatically calls Dispose() on the object when it leaves the block. There is a gotcha though, if a thread is forcefully aborted by an outside source, it is possible that Dispose will never be called.
149,617
<p>Let's assume that I have some packets with a 16-bit checksum at the end. I would like to guess which checksum algorithm is used.</p> <p>For a start, from dump data I can see that one byte change in the packet's payload totally changes the checksum, so I can assume that it isn't some kind of simple XOR or sum.</p> <p>Then I tried <a href="http://svn.rot13.org/index.cgi/RFID/view/guess-crc.pl" rel="noreferrer">several variations of CRC16</a>, but without much luck.</p> <p>This question might be more biased towards cryptography, but I'm really interested in any easy to understand statistical tools to find out which CRC this might be. I might even turn to <a href="http://lcamtuf.coredump.cx/newtcp/" rel="noreferrer">drawing different CRC algorithms</a> if everything else fails.</p> <p>Backgroud story: I have serial RFID protocol with some kind of checksum. I can replay messages without problem, and interpret results (without checksum check), but I can't send modified packets because device drops them on the floor. </p> <p>Using existing software, I can change payload of RFID chip. However, unique serial number is immutable, so I don't have ability to check every possible combination. Allthough I could generate dumps of values incrementing by one, but not enough to make exhaustive search applicable to this problem.</p> <p><a href="http://www.bljak.org/~dpavlin/rfid-serial-dump.tar.gz" rel="noreferrer">dump files with data</a> are available if question itself isn't enough :-)</p> <p><strong>Need reference documentation?</strong> <a href="http://www.geocities.com/SiliconValley/Pines/8659/crc.htm" rel="noreferrer">A PAINLESS GUIDE TO CRC ERROR DETECTION ALGORITHMS</a> is great reference which I found after asking question here.</p> <p>In the end, after very helpful hint in accepted answer than it's CCITT, I <a href="http://www.zorc.breitbandkatze.de/crc.html" rel="noreferrer">used this CRC calculator</a>, and xored generated checksum with known checksum to get 0xffff which led me to conclusion that final xor is 0xffff instread of CCITT's 0x0000.</p>
[ { "answer_id": 149663, "author": "Martin Cote", "author_id": 9936, "author_profile": "https://Stackoverflow.com/users/9936", "pm_score": 0, "selected": false, "text": "<p>You would have to try every possible checksum algorithm and see which one generates the same result. However, there ...
2008/09/29
[ "https://Stackoverflow.com/questions/149617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1081/" ]
Let's assume that I have some packets with a 16-bit checksum at the end. I would like to guess which checksum algorithm is used. For a start, from dump data I can see that one byte change in the packet's payload totally changes the checksum, so I can assume that it isn't some kind of simple XOR or sum. Then I tried [several variations of CRC16](http://svn.rot13.org/index.cgi/RFID/view/guess-crc.pl), but without much luck. This question might be more biased towards cryptography, but I'm really interested in any easy to understand statistical tools to find out which CRC this might be. I might even turn to [drawing different CRC algorithms](http://lcamtuf.coredump.cx/newtcp/) if everything else fails. Backgroud story: I have serial RFID protocol with some kind of checksum. I can replay messages without problem, and interpret results (without checksum check), but I can't send modified packets because device drops them on the floor. Using existing software, I can change payload of RFID chip. However, unique serial number is immutable, so I don't have ability to check every possible combination. Allthough I could generate dumps of values incrementing by one, but not enough to make exhaustive search applicable to this problem. [dump files with data](http://www.bljak.org/~dpavlin/rfid-serial-dump.tar.gz) are available if question itself isn't enough :-) **Need reference documentation?** [A PAINLESS GUIDE TO CRC ERROR DETECTION ALGORITHMS](http://www.geocities.com/SiliconValley/Pines/8659/crc.htm) is great reference which I found after asking question here. In the end, after very helpful hint in accepted answer than it's CCITT, I [used this CRC calculator](http://www.zorc.breitbandkatze.de/crc.html), and xored generated checksum with known checksum to get 0xffff which led me to conclusion that final xor is 0xffff instread of CCITT's 0x0000.
There are a number of variables to consider for a CRC: ``` Polynomial No of bits (16 or 32) Normal (LSB first) or Reverse (MSB first) Initial value How the final value is manipulated (e.g. subtracted from 0xffff), or is a constant value ``` Typical CRCs: ``` LRC: Polynomial=0x81; 8 bits; Normal; Initial=0; Final=as calculated CRC16: Polynomial=0xa001; 16 bits; Normal; Initial=0; Final=as calculated CCITT: Polynomial=0x1021; 16 bits; reverse; Initial=0xffff; Final=0x1d0f Xmodem: Polynomial=0x1021; 16 bits; reverse; Initial=0; Final=0x1d0f CRC32: Polynomial=0xebd88320; 32 bits; Normal; Initial=0xffffffff; Final=inverted value ZIP32: Polynomial=0x04c11db7; 32 bits; Normal; Initial=0xffffffff; Final=as calculated ``` The first thing to do is to get some samples by changing say the last byte. This will assist you to figure out the number of bytes in the CRC. Is this a "homemade" algorithm. In this case it may take some time. Otherwise try the standard algorithms. Try changing either the msb or the lsb of the last byte, and see how this changes the CRC. This will give an indication of the direction. To make it more difficult, there are implementations that manipulate the CRC so that it will not affect the communications medium (protocol). From your comment about RFID, it implies that the CRC is communications related. Usually CRC16 is used for communications, though CCITT is also used on some systems. On the other hand, if this is UHF RFID tagging, then there are a few CRC schemes - a 5 bit one and some 16 bit ones. These are documented in the ISO standards and the IPX data sheets. ``` IPX: Polynomial=0x8005; 16 bits; Reverse; Initial=0xffff; Final=as calculated ISO 18000-6B: Polynomial=0x1021; 16 bits; Reverse; Initial=0xffff; Final=as calculated ISO 18000-6C: Polynomial=0x1021; 16 bits; Reverse; Initial=0xffff; Final=as calculated Data must be padded with zeroes to make a multiple of 8 bits ISO CRC5: Polynomial=custom; 5 bits; Reverse; Initial=0x9; Final=shifted left by 3 bits Data must be padded with zeroes to make a multiple of 8 bits EPC class 1: Polynomial=custom 0x1021; 16 bits; Reverse; Initial=0xffff; Final=post processing of 16 zero bits ``` **Here is your answer!!!!** **Having worked through your logs, the CRC is the CCITT one. The first byte 0xd6 is excluded from the CRC.**
149,627
<p>Is there a clean way of cloning a record in SQL that has an index(auto increment). I want to clone all the fields except the index. I currently have to enumerate every field, and use that in an insert select, and I would rather not explicitly list all of the fields, as they may change over time.</p>
[ { "answer_id": 149650, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 2, "selected": true, "text": "<p>Not unless you want to get into dynamic SQL. Since you wrote \"clean\", I'll assume not.</p>\n\n<p><strong>Edit:</s...
2008/09/29
[ "https://Stackoverflow.com/questions/149627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17712/" ]
Is there a clean way of cloning a record in SQL that has an index(auto increment). I want to clone all the fields except the index. I currently have to enumerate every field, and use that in an insert select, and I would rather not explicitly list all of the fields, as they may change over time.
Not unless you want to get into dynamic SQL. Since you wrote "clean", I'll assume not. **Edit:** Since he asked for a dynamic SQL example, I'll take a stab at it. I'm not connected to any databases at the moment, so this is off the top of my head and will almost certainly need revision. But hopefully it captures the spirit of things: ``` -- Get list of columns in table SELECT INTO #t EXEC sp_columns @table_name = N'TargetTable' -- Create a comma-delimited string excluding the identity column DECLARE @cols varchar(MAX) SELECT @cols = COALESCE(@cols+',' ,'') + COLUMN_NAME FROM #t WHERE COLUMN_NAME <> 'id' -- Construct dynamic SQL statement DECLARE @sql varchar(MAX) SET @sql = 'INSERT INTO TargetTable (' + @cols + ') ' + 'SELECT ' + @cols + ' FROM TargetTable WHERE SomeCondition' PRINT @sql -- for debugging EXEC(@sql) ```
149,639
<p>I've got a 'task list' database that uses the adjacency list model (see below) so each 'task' can have unlimited sub-tasks. The table has an 'TaskOrder' column so everything renders in the correct order on a treeview.</p> <p>Is there an SQL statement (MS-SQL 2005) that will select all the child nodes for a specified parent and update the TaskOder column when a sibling is deleted?</p> <pre> Task Table ---------- TaskId ParentTaskId TaskOrder TaskName --etc-- </pre> <p>Any ideas? Thanks.</p>
[ { "answer_id": 149695, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 2, "selected": false, "text": "<p>If you're only using TaskOrder for sorting, it would certainly be simpler to simply leave the holes in TaskOrder,...
2008/09/29
[ "https://Stackoverflow.com/questions/149639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14072/" ]
I've got a 'task list' database that uses the adjacency list model (see below) so each 'task' can have unlimited sub-tasks. The table has an 'TaskOrder' column so everything renders in the correct order on a treeview. Is there an SQL statement (MS-SQL 2005) that will select all the child nodes for a specified parent and update the TaskOder column when a sibling is deleted? ``` Task Table ---------- TaskId ParentTaskId TaskOrder TaskName --etc-- ``` Any ideas? Thanks.
Couple of different ways... Since the TaskOrder is scoped by parent id, it's not terribly difficult to gather it. In SQL Server, I'd put a trigger on delete that decrements all the ones 'higher' than the one you deleted, thereby closing the gap (pseudocode follows): ``` CREATE TRIGGER ON yourtable FOR DELETE AS UPDATE Task SET TaskOrder = TaskOrder - 1 WHERE ParentTaskId = deleted.ParentTaskId AND TaskOrder > deleted.TaskOrder ``` If you don't want a trigger, you can capture the parentID and TaskOrder in a query first, delete the row, then execute that same update statement but with literals rather than the trigger. Or if you want to minimize server round-trips, you could move the to-be-deleted task all the way to the bottom, then move the others up, then do the delete, but that seems overly complicated.
149,646
<p>In the Apple documentation for <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSRunLoop_Class/Reference/Reference.html#//apple_ref/occ/instm/NSRunLoop/run" rel="noreferrer">NSRunLoop</a> there is sample code demonstrating suspending execution while waiting for a flag to be set by something else.</p> <pre><code>BOOL shouldKeepRunning = YES; // global NSRunLoop *theRL = [NSRunLoop currentRunLoop]; while (shouldKeepRunning &amp;&amp; [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]); </code></pre> <p>I have been using this and it works but in investigating a performance issue I tracked it down to this piece of code. I use almost exactly the same piece of code (just the name of the flag is different :) and if I put a <code>NSLog</code> on the line after the flag is being set (in another method) and then a line after the <code>while()</code> there is a seemingly random wait between the two log statements of several seconds.</p> <p>The delay does not seem to be different on slower or faster machines but does vary from run to run being at least a couple of seconds and up to 10 seconds.</p> <p>I have worked around this issue with the following code but it does not seem right that the original code doesn't work.</p> <pre><code>NSDate *loopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1]; while (webViewIsLoading &amp;&amp; [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate:loopUntil]) loopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1]; </code></pre> <p>using this code, the log statements when setting the flag and after the while loop are now consistently less than 0.1 seconds apart.</p> <p>Anyone any ideas why the original code exhibits this behaviour?</p>
[ { "answer_id": 150302, "author": "schwa", "author_id": 23113, "author_profile": "https://Stackoverflow.com/users/23113", "pm_score": 6, "selected": true, "text": "<p>Runloops can be a bit of a magic box where stuff just happens.</p>\n\n<p>Basically you're telling the runloop to go proces...
2008/09/29
[ "https://Stackoverflow.com/questions/149646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4496/" ]
In the Apple documentation for [NSRunLoop](http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSRunLoop_Class/Reference/Reference.html#//apple_ref/occ/instm/NSRunLoop/run) there is sample code demonstrating suspending execution while waiting for a flag to be set by something else. ``` BOOL shouldKeepRunning = YES; // global NSRunLoop *theRL = [NSRunLoop currentRunLoop]; while (shouldKeepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]); ``` I have been using this and it works but in investigating a performance issue I tracked it down to this piece of code. I use almost exactly the same piece of code (just the name of the flag is different :) and if I put a `NSLog` on the line after the flag is being set (in another method) and then a line after the `while()` there is a seemingly random wait between the two log statements of several seconds. The delay does not seem to be different on slower or faster machines but does vary from run to run being at least a couple of seconds and up to 10 seconds. I have worked around this issue with the following code but it does not seem right that the original code doesn't work. ``` NSDate *loopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1]; while (webViewIsLoading && [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate:loopUntil]) loopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1]; ``` using this code, the log statements when setting the flag and after the while loop are now consistently less than 0.1 seconds apart. Anyone any ideas why the original code exhibits this behaviour?
Runloops can be a bit of a magic box where stuff just happens. Basically you're telling the runloop to go process some events and then return. OR return if it doesn't process any events before the timeout is hit. With 0.1 second timeout, you're htting the timeout more often than not. The runloop fires, doesn't process any events and returns in 0.1 of second. Occasionally it'll get a chance to process an event. With your distantFuture timeout, the runloop will wait foreever until it processes an event. So when it returns to you, it has just processed an event of some kind. A short timeout value will consume considerably more CPU than the infinite timeout but there are good reasons for using a short timeout, for example if you want to terminate the process/thread the runloop is running in. You'll probably want the runloop to notice that a flag has changed and that it needs to bail out ASAP. You might want to play around with runloop observers so you can see exactly what the runloop is doing. See [this Apple doc](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html#//apple_ref/doc/uid/10000057i-CH16-SW22) for more information.
149,690
<p>I am trying to extract a certain part of a column that is between delimiters.</p> <p>e.g. find foo in the following</p> <p>test 'esf :foo: bar</p> <p>So in the above I'd want to return foo, but all the regexp functions only return true|false, is there a way to do this in MySQL</p>
[ { "answer_id": 149703, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 2, "selected": false, "text": "<p>A combination of <a href=\"http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_locate\" rel=\"nofollow ...
2008/09/29
[ "https://Stackoverflow.com/questions/149690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to extract a certain part of a column that is between delimiters. e.g. find foo in the following test 'esf :foo: bar So in the above I'd want to return foo, but all the regexp functions only return true|false, is there a way to do this in MySQL
Here ya go, bud: ``` SELECT SUBSTR(column, LOCATE(':',column)+1, (CHAR_LENGTH(column) - LOCATE(':',REVERSE(column)) - LOCATE(':',column))) FROM table ``` Yea, no clue why you're doing this, but this will do the trick. By performing a LOCATE, we can find the first ':'. To find the last ':', there's no reverse LOCATE, so we have to do it manually by performing a LOCATE(':', REVERSE(column)). With the index of the first ':', the number of chars from the last ':' to the end of the string, and the CHAR\_LENGTH (*don't use LENGTH() for this*), we can use a little math to discover the length of the string between the two instances of ':'. This way we can peform a SUBSTR and dynamically pluck out the characters between the two ':'. Again, it's gross, but to each his own.
149,772
<p>Basically the question is how to get from this:</p> <pre> foo_id foo_name 1 A 1 B 2 C </pre> <p>to this:</p> <pre> foo_id foo_name 1 A B 2 C </pre>
[ { "answer_id": 149799, "author": "Scott Noyes", "author_id": 23539, "author_profile": "https://Stackoverflow.com/users/23539", "pm_score": 10, "selected": true, "text": "<pre><code>SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id;\n</code></pre>\n<p><a href=\"https://de...
2008/09/29
[ "https://Stackoverflow.com/questions/149772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9403/" ]
Basically the question is how to get from this: ``` foo_id foo_name 1 A 1 B 2 C ``` to this: ``` foo_id foo_name 1 A B 2 C ```
``` SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id; ``` <https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat> From the link above, `GROUP_CONCAT`: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.
149,784
<p><a href="https://stackoverflow.com/questions/57168/how-to-copy-a-row-from-one-sql-server-table-to-another">This question</a> comes close to what I need, but my scenario is slightly different. The source table and destination table are the same and the primary key is a uniqueidentifier (guid). When I try this:</p> <pre><code>insert into MyTable select * from MyTable where uniqueId = @Id; </code></pre> <p>I obviously get a primary key constraint violation, since I'm attempting to copy over the primary key. Actually, I don't want to copy over the primary key at all. Rather, I want to create a new one. Additionally, I would like to selectively copy over certain fields, and leave the others null. To make matters more complex, I need to take the primary key of the original record, and insert it into another field in the copy (PreviousId field).</p> <p>I'm sure there is an easy solution to this, I just don't know enough TSQL to know what it is.</p>
[ { "answer_id": 149792, "author": "AaronSieb", "author_id": 16911, "author_profile": "https://Stackoverflow.com/users/16911", "pm_score": 9, "selected": true, "text": "<p>Try this:\n<pre><code>\ninsert into MyTable(field1, field2, id_backup)\n select field1, field2, uniqueId from MyTab...
2008/09/29
[ "https://Stackoverflow.com/questions/149784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5469/" ]
[This question](https://stackoverflow.com/questions/57168/how-to-copy-a-row-from-one-sql-server-table-to-another) comes close to what I need, but my scenario is slightly different. The source table and destination table are the same and the primary key is a uniqueidentifier (guid). When I try this: ``` insert into MyTable select * from MyTable where uniqueId = @Id; ``` I obviously get a primary key constraint violation, since I'm attempting to copy over the primary key. Actually, I don't want to copy over the primary key at all. Rather, I want to create a new one. Additionally, I would like to selectively copy over certain fields, and leave the others null. To make matters more complex, I need to take the primary key of the original record, and insert it into another field in the copy (PreviousId field). I'm sure there is an easy solution to this, I just don't know enough TSQL to know what it is.
Try this: ``` insert into MyTable(field1, field2, id_backup) select field1, field2, uniqueId from MyTable where uniqueId = @Id; ``` Any fields not specified should receive their default value (which is usually NULL when not defined).
149,796
<p>Often I want to add a value to a table or update the value if its key already exists. This can be accomplished in several ways, assuming a primary or unique key is set on the 'user_id' and 'pref_key' columns in the example:</p> <p><strong>1. Blind insert, update if receiving a duplicate key error:</strong></p> <pre><code>// Try to insert as a new value INSERT INTO my_prefs (user_id, pref_key, pref_value) VALUES (1234, 'show_help', 'true'); // If a duplicate-key error occurs run an update query UPDATE my_prefs SET pref_value = 'true' WHERE user_id=1234 AND pref_key='show_help'; </code></pre> <p><strong>2. Check for existence, then select or update:</strong></p> <pre><code>// Check for existence SELECT COUNT(*) FROM my_prefs WHERE user_id=1234 AND pref_key='show_help'; // If count is zero, insert INSERT INTO my_prefs (user_id, pref_key, pref_value) VALUES (1234, 'show_help', 'true'); // If count is one, update UPDATE my_prefs SET pref_value = 'true' WHERE user_id=1234 AND pref_key='show_help'; </code></pre> <p>The first way seems to be preferable as it will require only one query for new inserts and two for an update, where as the second way will always require two queries. Is there anything I'm missing though that would make it a bad idea to blindly insert?</p>
[ { "answer_id": 149812, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 0, "selected": false, "text": "<p>The first way is the preferred way as far as I know.</p>\n" }, { "answer_id": 149819, "author": "Dave Verwer",...
2008/09/29
[ "https://Stackoverflow.com/questions/149796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15872/" ]
Often I want to add a value to a table or update the value if its key already exists. This can be accomplished in several ways, assuming a primary or unique key is set on the 'user\_id' and 'pref\_key' columns in the example: **1. Blind insert, update if receiving a duplicate key error:** ``` // Try to insert as a new value INSERT INTO my_prefs (user_id, pref_key, pref_value) VALUES (1234, 'show_help', 'true'); // If a duplicate-key error occurs run an update query UPDATE my_prefs SET pref_value = 'true' WHERE user_id=1234 AND pref_key='show_help'; ``` **2. Check for existence, then select or update:** ``` // Check for existence SELECT COUNT(*) FROM my_prefs WHERE user_id=1234 AND pref_key='show_help'; // If count is zero, insert INSERT INTO my_prefs (user_id, pref_key, pref_value) VALUES (1234, 'show_help', 'true'); // If count is one, update UPDATE my_prefs SET pref_value = 'true' WHERE user_id=1234 AND pref_key='show_help'; ``` The first way seems to be preferable as it will require only one query for new inserts and two for an update, where as the second way will always require two queries. Is there anything I'm missing though that would make it a bad idea to blindly insert?
Will there be concurrent INSERTs to these rows? DELETEs? "ON DUPLICATE" sounds great (the behavior is just what you want) provided that you're not concerned about portability to non-MySQL databases. The "blind insert" seems reasonable and robust provided that rows are never deleted. (If the INSERT case fails because the row exists, the UPDATE afterward should succeed because the row still exists. But this assumption is false if rows are deleted - you'd need retry logic then.) On other databases without "ON DUPLICATE", you might consider an optimization if you find latency to be bad: you could avoid a database round trip in the already-exists case by putting this logic in a stored procedure. The "check for existence" is tricky to get right if there are concurrent INSERTs. Rows could be added between your SELECT and your UPDATE. Transactions won't even really help - I think even at isolation level "serializable", you'll see "could not serialize access due to concurrent update" errors occasionally (or whatever the MySQL equivalent error message is). You'll need retry logic, so I'd say the person above who suggests using this method to avoid "exception-based programming" is wrong, as is the person who suggests doing the UPDATE first for the same reason.
149,800
<p>I'm making a small quiz-application in Flash (and ActionScript 3). Decided to use the RadioButton-component for radiobuttons, but I'm having some problems getting the word-wrapping to work.</p> <p>The code for creating the button can be found below.</p> <pre><code>_button = new RadioButton(); _button.setStyle("textFormat", _format); _button.label = _config.toString(); _button.width = Number(_defaults.@alen); _button.textField.width = Number(_defaults.@alen); _button.textField.multiline = true; _button.textField.wordWrap = true; _button.value = _config.@value; _button.group = _group; _button.x = _config.@x; _button.y = _config.@y; </code></pre> <p>_config is a piece of XML, and _defaults is a piece of XML containing size-information and font-setup</p> <p>When I set _button.textField.wordWrap to true, the text gets split into multiple lines, but it's not split at _defaults.@alen, which I want, but looks like it happens pretty much after each word.</p> <p>Also, it sometimes splits it into several lines, but doesn't display it all until the mouse hovers over it.</p>
[ { "answer_id": 149926, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 3, "selected": true, "text": "<p>Two possibilities: width should be in pixels, not in characters. In addition, don't forget that the button itself uses up s...
2008/09/29
[ "https://Stackoverflow.com/questions/149800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm making a small quiz-application in Flash (and ActionScript 3). Decided to use the RadioButton-component for radiobuttons, but I'm having some problems getting the word-wrapping to work. The code for creating the button can be found below. ``` _button = new RadioButton(); _button.setStyle("textFormat", _format); _button.label = _config.toString(); _button.width = Number(_defaults.@alen); _button.textField.width = Number(_defaults.@alen); _button.textField.multiline = true; _button.textField.wordWrap = true; _button.value = _config.@value; _button.group = _group; _button.x = _config.@x; _button.y = _config.@y; ``` \_config is a piece of XML, and \_defaults is a piece of XML containing size-information and font-setup When I set \_button.textField.wordWrap to true, the text gets split into multiple lines, but it's not split at \_defaults.@alen, which I want, but looks like it happens pretty much after each word. Also, it sometimes splits it into several lines, but doesn't display it all until the mouse hovers over it.
Two possibilities: width should be in pixels, not in characters. In addition, don't forget that the button itself uses up some of the width. If you can't get it to work, instead of banging your head on it, might want to just create the label separately, either a simple TextField, or using a Label component. Slightly more code, but might be worth it to spend an extra 10 minutes writing code versus two hours getting the component to work how you want.
149,808
<p>I have several stored procedures in my database that are used to load data from a datamart that is housed in a separate database. These procedures are, generally, in the form:</p> <pre><code> CREATE PROCEDURE load_stuff WITH EXECUTE AS OWNER AS INSERT INTO my_db.dbo.report_table ( column_a ) SELECT column_b FROM data_mart.dbo.source_table WHERE foo = 'bar'; </code></pre> <p>These run fine when I execute the query in SQL Server Management Studio. When I try to execute them using EXEC load_stuff, the procedure fails with a security warning:</p> <p><em>The server principal "the_user" is not able to access the database "data_mart" under the current security context.</em></p> <p>The OWNER of the sproc is dbo, which is the_user (for the sake of our example). The OWNER of both databases is also the_user and the_user is mapped to dbo (which is what SQL Server should do).</p> <p>Why would I be seeing this error in SQL Server? Is this because the user in question is being aliased as dbo and I should use a different user account for my cross-database data access?</p> <p><strong>Edit</strong> I understand that this is because SQL Server disables cross database ownership chaining by default, which is good. However, I'm not sure of the best practice in this situation. If anyone has any input on the best practice for this scenario, it would be greatly appreciated.</p> <p><strong>Edit 2</strong> The eventual solution was to set TRUSTWORTHY ON on both of the databases. This allows for limited ownership chaining between the two databases without resorting to full database ownership chaining.</p>
[ { "answer_id": 149984, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 2, "selected": false, "text": "<p>Why not remove EXECUTE AS OWNER?</p>\n\n<p>Usually, my user executing the SP would have appropriate rights in both da...
2008/09/29
[ "https://Stackoverflow.com/questions/149808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11780/" ]
I have several stored procedures in my database that are used to load data from a datamart that is housed in a separate database. These procedures are, generally, in the form: ``` CREATE PROCEDURE load_stuff WITH EXECUTE AS OWNER AS INSERT INTO my_db.dbo.report_table ( column_a ) SELECT column_b FROM data_mart.dbo.source_table WHERE foo = 'bar'; ``` These run fine when I execute the query in SQL Server Management Studio. When I try to execute them using EXEC load\_stuff, the procedure fails with a security warning: *The server principal "the\_user" is not able to access the database "data\_mart" under the current security context.* The OWNER of the sproc is dbo, which is the\_user (for the sake of our example). The OWNER of both databases is also the\_user and the\_user is mapped to dbo (which is what SQL Server should do). Why would I be seeing this error in SQL Server? Is this because the user in question is being aliased as dbo and I should use a different user account for my cross-database data access? **Edit** I understand that this is because SQL Server disables cross database ownership chaining by default, which is good. However, I'm not sure of the best practice in this situation. If anyone has any input on the best practice for this scenario, it would be greatly appreciated. **Edit 2** The eventual solution was to set TRUSTWORTHY ON on both of the databases. This allows for limited ownership chaining between the two databases without resorting to full database ownership chaining.
Why not remove EXECUTE AS OWNER? Usually, my user executing the SP would have appropriate rights in both databases, and I don't have to do that at all.
149,821
<p>I have the following function that is pulling data from a database. The ajax call is working correctly. How can I send the tab delimited data in my success function to the user? Setting the contect type to "application/vnd.ms-excel" didn't work. The alert on success shows the correctly formatted data.</p> <pre><code> function SendToExcel() { $.ajax({ type: "GET", url: "/Search.aspx", contentType: "application/vnd.ms-excel", dataType: "text", data: "{id: '" + "asdf" + "'}", success: function(data) { alert(data); }, error: function (jqXHR, textStatus, errorThrown) { alert(jqXHR.responseText); }}); } </code></pre> <p>I don't want to display the data in the browser--I want to send it to Excel.</p> <p><strong>EDIT:</strong> I found a way to do what I wanted. Instead of redirecting the users to a new page that would prompt them to save/open an Excel file, I opened the page inside a hidden iframe. That way, the users click a button, and they are prompted to save/open an Excel file. No page redirection. Is it Ajax? No, but it solves the real problem I had.</p> <p>Here's the function I'm calling on the button click:</p> <pre><code> function SendToExcel() { var dataString = 'type=excel' + '&amp;Number=' + $('#txtNumber').val() + '&amp;Reference=' + $('#txtReference').val() $("#sltCTPick option").each(function (i) { dataString = dataString + '&amp;Columns=' + this.value; }); top.iExcelHelper.location.href = "/Reports/JobSearchResults.aspx?" + dataString;; } </code></pre>
[ { "answer_id": 149859, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 5, "selected": true, "text": "<p>AJAX is... the wrong choice. Redirect the user to a server resource that will send the data down with the proper MIME type, an...
2008/09/29
[ "https://Stackoverflow.com/questions/149821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681/" ]
I have the following function that is pulling data from a database. The ajax call is working correctly. How can I send the tab delimited data in my success function to the user? Setting the contect type to "application/vnd.ms-excel" didn't work. The alert on success shows the correctly formatted data. ``` function SendToExcel() { $.ajax({ type: "GET", url: "/Search.aspx", contentType: "application/vnd.ms-excel", dataType: "text", data: "{id: '" + "asdf" + "'}", success: function(data) { alert(data); }, error: function (jqXHR, textStatus, errorThrown) { alert(jqXHR.responseText); }}); } ``` I don't want to display the data in the browser--I want to send it to Excel. **EDIT:** I found a way to do what I wanted. Instead of redirecting the users to a new page that would prompt them to save/open an Excel file, I opened the page inside a hidden iframe. That way, the users click a button, and they are prompted to save/open an Excel file. No page redirection. Is it Ajax? No, but it solves the real problem I had. Here's the function I'm calling on the button click: ``` function SendToExcel() { var dataString = 'type=excel' + '&Number=' + $('#txtNumber').val() + '&Reference=' + $('#txtReference').val() $("#sltCTPick option").each(function (i) { dataString = dataString + '&Columns=' + this.value; }); top.iExcelHelper.location.href = "/Reports/JobSearchResults.aspx?" + dataString;; } ```
AJAX is... the wrong choice. Redirect the user to a server resource that will send the data down with the proper MIME type, and let the browser figure out what to do with it.
149,823
<p>When I dynamically create a Datagrid and add in a new buttoncolumn how do I access the buttoncolumn_click event? </p> <p>Thanks.</p>
[ { "answer_id": 150068, "author": "Brendan Enrick", "author_id": 22381, "author_profile": "https://Stackoverflow.com/users/22381", "pm_score": 0, "selected": false, "text": "<p>This article on the MSDN site clearly explains how to go about <a href=\"http://msdn.microsoft.com/en-us/library...
2008/09/29
[ "https://Stackoverflow.com/questions/149823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20748/" ]
When I dynamically create a Datagrid and add in a new buttoncolumn how do I access the buttoncolumn\_click event? Thanks.
``` protected void Page_Load(object sender, EventArgs e) { DataGrid dg = new DataGrid(); dg.GridLines = GridLines.Both; dg.Columns.Add(new ButtonColumn { CommandName = "add", HeaderText = "Event Details", Text = "Details", ButtonType = ButtonColumnType.PushButton }); dg.DataSource = getDataTable(); dg.DataBind(); dg.ItemCommand += new DataGridCommandEventHandler(dg_ItemCommand); pnlMain.Controls.Add(dg); } protected void dg_ItemCommand(object source, DataGridCommandEventArgs e) { if (e.CommandName == "add") { throw new Exception("add it!"); } } protected DataTable getDataTable() { // returns your data table } ```
149,825
<p>I ran across the following code in <a href="http://www.quietlyscheming.com/blog/" rel="nofollow noreferrer">Ely Greenfield's</a> SuperImage from his Book component - I understand loader.load() but what does the rest of do?</p> <pre><code>loader.load((newSource is URLRequest)? newSource:new URLRequest(newSource)); </code></pre> <p>It looks like some kind of crazy inline if statement but still, I'm a little preplexed. And if it is an if statement - is this way better than a regular if statement?</p>
[ { "answer_id": 149847, "author": "Matt", "author_id": 20630, "author_profile": "https://Stackoverflow.com/users/20630", "pm_score": 0, "selected": false, "text": "<p>this is using the <a href=\"http://en.wikipedia.org/wiki/%3F:\" rel=\"nofollow noreferrer\">ternary ?: operator</a>. the ...
2008/09/29
[ "https://Stackoverflow.com/questions/149825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3435/" ]
I ran across the following code in [Ely Greenfield's](http://www.quietlyscheming.com/blog/) SuperImage from his Book component - I understand loader.load() but what does the rest of do? ``` loader.load((newSource is URLRequest)? newSource:new URLRequest(newSource)); ``` It looks like some kind of crazy inline if statement but still, I'm a little preplexed. And if it is an if statement - is this way better than a regular if statement?
? is called the 'ternary operator' and it's basic use is: ``` (expression) ? (evaluate to this if expression is true) : (evaluate to this otherwise); ``` In this case, if newSource is a URLRequest, loader.load will be passed newSource directly, otherwise it will be passed a new URLRequest built from newSource. The ternary operator is frequently used as a more concise form of if statement as it allows ifs to be inlined. The corresponding code in this case would be: ``` if (newSource is URLRequest) loader.load(newSource); else loader.load(new URLRequest(newSource)); ```
149,827
<p>I want to be able to run a text editor from my app, as given by the user in the TEXT_EDITOR environment variable. Now, assuming there is nothing in that variable, I want to default to the TextEdit program that ships with OSX. Is it kosher to hardcode /Applications/TextEdit.app/Contents/MacOS/TextEdit into my app, or is there a better way to call the program?</p> <p>Edit: For the record, I am limited to running a specific application path, in C. I'm not opening a path to a text file.</p> <p>Edit 2: Seriously people, I'm not opening a file here. I'm asking about an application path for a reason.</p>
[ { "answer_id": 149846, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 0, "selected": false, "text": "<p>I believe that Mac OS X provides a default application mechanism, so that .txt will open in TextEdit.app or Emacs or GVi...
2008/09/29
[ "https://Stackoverflow.com/questions/149827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3830/" ]
I want to be able to run a text editor from my app, as given by the user in the TEXT\_EDITOR environment variable. Now, assuming there is nothing in that variable, I want to default to the TextEdit program that ships with OSX. Is it kosher to hardcode /Applications/TextEdit.app/Contents/MacOS/TextEdit into my app, or is there a better way to call the program? Edit: For the record, I am limited to running a specific application path, in C. I'm not opening a path to a text file. Edit 2: Seriously people, I'm not opening a file here. I'm asking about an application path for a reason.
In your second edit it makes it sound like you just want to get the path to TextEdit, this can be done easily by using NSWorkspace method absolutePathForAppBundleWithIdentifier: ``` NSString *path = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:@"com.apple.TextEdit"]; ```
149,844
<p>I'm running my site through the W3C's validator trying to get it to validate as XHTML 1.0 Strict and I've gotten down to a particularly sticky (at least in my experience) validation error. I'm including certain badges from various services in the site that provide their own API and code for inclusion on an external site. These badges use javascript (for the most part) to fill an element that you insert in the markup which requires a child. This means that in the end, perfectly valid markup is generated, but to the validator, all it sees is an incomplete parent-child tag which it then throws an error on.</p> <p>As a caveat, I understand that I could complain to the services that their badges don't validate. Sans this, I assume that someone has validated their code while including badges like this, and that's what I'm interested in. Answers such as, 'Complain to Flickr about their badge' aren't going to help me much.</p> <p>An additional caveat: I would prefer that as much as possible the markup remains semantic. I.E. Adding an empty li tag or tr-td pair to make it validate would be an <em>undesirable</em> solution, even though it may be necessary. If that's the only way it can be made to validate, oh well, but please lean answers towards semantic markup.</p> <p>As an example: </p> <pre><code>&lt;div id="twitter_div"&gt; &lt;h2&gt;&lt;a href="http://twitter.com/stopsineman"&gt;@Twitter&lt;/a&gt;&lt;/h2&gt; &lt;ul id="twitter_update_list"&gt; &lt;script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://twitter.com/statuses/user_timeline/stopsineman.json?callback=twitterCallback2&amp;amp;count=1"&gt;&lt;/script&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>Notice the ul tags wrapping the javascript. This eventually gets filled in with lis via the script, but to the validator it only sees the unpopulated ul.</p> <p>Thanks in advance!</p>
[ { "answer_id": 150071, "author": "Rudi", "author_id": 22830, "author_profile": "https://Stackoverflow.com/users/22830", "pm_score": 2, "selected": false, "text": "<p>Perhaps you could use javascript to write the initial badge HTML? You'd probably only want the badge code to be inserted i...
2008/09/29
[ "https://Stackoverflow.com/questions/149844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16562/" ]
I'm running my site through the W3C's validator trying to get it to validate as XHTML 1.0 Strict and I've gotten down to a particularly sticky (at least in my experience) validation error. I'm including certain badges from various services in the site that provide their own API and code for inclusion on an external site. These badges use javascript (for the most part) to fill an element that you insert in the markup which requires a child. This means that in the end, perfectly valid markup is generated, but to the validator, all it sees is an incomplete parent-child tag which it then throws an error on. As a caveat, I understand that I could complain to the services that their badges don't validate. Sans this, I assume that someone has validated their code while including badges like this, and that's what I'm interested in. Answers such as, 'Complain to Flickr about their badge' aren't going to help me much. An additional caveat: I would prefer that as much as possible the markup remains semantic. I.E. Adding an empty li tag or tr-td pair to make it validate would be an *undesirable* solution, even though it may be necessary. If that's the only way it can be made to validate, oh well, but please lean answers towards semantic markup. As an example: ``` <div id="twitter_div"> <h2><a href="http://twitter.com/stopsineman">@Twitter</a></h2> <ul id="twitter_update_list"> <script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script> <script type="text/javascript" src="http://twitter.com/statuses/user_timeline/stopsineman.json?callback=twitterCallback2&amp;count=1"></script> </ul> </div> ``` Notice the ul tags wrapping the javascript. This eventually gets filled in with lis via the script, but to the validator it only sees the unpopulated ul. Thanks in advance!
The following fragment is valid XHTML and does the job: ``` <div id="twitter_div"> <h2 class="twitter-title"><a href="http://twitter.com/stopsineman" title="Tim's Twitter Page.">Twitter Updates</a></h2> <div id="myDiv" /> </div> <script type="text/javascript"> var placeHolderNode = document.getElementById("myDiv"); var parentNode = placeHolderNode.parentNode; var insertedNode = document.createElement("ul"); insertedNode .setAttribute("id", "twitter_update_list"); parentNode.insertBefore( insertedNode, placeHolderNode); parentNode.remove(placeHolderNode); </script> <script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script> <script type="text/javascript" src="http://twitter.com/statuses/user_timeline/stopsineman.json?callback=twitterCallback2&amp;count=5"></script> ```
149,848
<p>What is a strong way to protect against sql injection for a classic asp app?</p> <p>FYI I am using it with an access DB. (I didnt write the app)</p>
[ { "answer_id": 149854, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 6, "selected": true, "text": "<p>Stored Procedures and/or prepared statements:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/1973/what-is-the...
2008/09/29
[ "https://Stackoverflow.com/questions/149848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23528/" ]
What is a strong way to protect against sql injection for a classic asp app? FYI I am using it with an access DB. (I didnt write the app)
Stored Procedures and/or prepared statements: <https://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks> [Can I protect against SQL Injection by escaping single-quote and surrounding user input with single-quotes?](https://stackoverflow.com/questions/139199/can-i-protect-against-sql-injection-by-escaping-single-quote-and-surrounding-us) [Catching SQL Injection and other Malicious Web Requests](https://stackoverflow.com/questions/1284/catching-sql-injection-and-other-malicious-web-requests) With Access DB, you can still do it, but if you're already worried about SQL Injection, I think you need to get off Access anyway. Here's a link to the technique in Access: <http://www.asp101.com/samples/storedqueries.asp> Note that what typically protects from injection is not the stored procedure itself, but that fact that it is parameterized and not dynamic. Remember that even SPs which build dynamic code can be vulnerable to injection if they use parameters in certain ways to build the dynamic code. Overall, I prefer SPs because they form an interface layer which the applications get to the database, so the apps aren't even allowed to execute arbitrary code in the first place. In addition, the execution point of the stored procedure can be vulnerable if you don't use command and parameters, e.g. this is still vulnerable because it's dynamically built and can be an injection target: ``` Conn.Execute("EXEC usp_ImOnlySafeIfYouCallMeRight '" + param1 + "', '" + param2 + "'") ; ``` Remember that your database needs to defend its own perimeter, and if various logins have rights to `INSERT/UPDATE/DELETE` in tables, any code in those applications (or compromised applications) can be a potential problem. If the logins only have rights to execute stored procedures, this forms a funnel through which you can much more easily ensure correct behavior. (Similar to OO concepts where objects are responsible for their interfaces and don't expose all their inner workings.)
149,860
<p>I have a <code>popen()</code> function which executes <code>tail -f sometextfile</code>. Aslong as there is data in the filestream obviously I can get the data through <code>fgets()</code>. Now, if no new data comes from tail, <code>fgets()</code> hangs. I tried <code>ferror()</code> and <code>feof()</code> to no avail. How can I make sure <code>fgets()</code> doesn't try to read data when nothing new is in the file stream? </p> <p>One of the suggestion was <code>select()</code>. Since this is for Windows Platform select doesn't seem to work as anonymous pipes do not seem to work for it (see <a href="https://stackoverflow.com/questions/152807/what-is-wrong-with-this-popen-select-example" title="this post">this post</a>).</p>
[ { "answer_id": 149875, "author": "Kasprzol", "author_id": 5957, "author_profile": "https://Stackoverflow.com/users/5957", "pm_score": 0, "selected": false, "text": "<p>I you would use POSIX functions for IO instead of those of C library, you could use <a href=\"http://linux.die.net/man/2...
2008/09/29
[ "https://Stackoverflow.com/questions/149860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10010/" ]
I have a `popen()` function which executes `tail -f sometextfile`. Aslong as there is data in the filestream obviously I can get the data through `fgets()`. Now, if no new data comes from tail, `fgets()` hangs. I tried `ferror()` and `feof()` to no avail. How can I make sure `fgets()` doesn't try to read data when nothing new is in the file stream? One of the suggestion was `select()`. Since this is for Windows Platform select doesn't seem to work as anonymous pipes do not seem to work for it (see [this post](https://stackoverflow.com/questions/152807/what-is-wrong-with-this-popen-select-example "this post")).
In Linux (or any Unix-y OS), you can mark the underlying file descriptor used by popen() to be non-blocking. ``` #include <fcntl.h> FILE *proc = popen("tail -f /tmp/test.txt", "r"); int fd = fileno(proc); int flags; flags = fcntl(fd, F_GETFL, 0); flags |= O_NONBLOCK; fcntl(fd, F_SETFL, flags); ``` If there is no input available, fgets will return NULL with errno set to EWOULDBLOCK.
149,871
<p>I'm building a data warehouse that includes delivery information for restaurants. The data is stored in SQL Server 2005 and is then put into a SQL Server Analysis Services 2005 cube.</p> <p>The Deliveries information consists of the following tables:</p> <p><strong>FactDeliveres</strong></p> <ul> <li>BranchKey</li> <li>DeliveryDateKey</li> <li>ProductKey</li> <li>InvoiceNumber (DD: degenerate dimension)</li> <li>Quantity</li> <li>UnitCosT</li> <li>Linecost</li> </ul> <p><strong>Note:</strong> </p> <ul> <li>The granularity of FactDeliveres is each line on the invoice</li> <li>The Product dimension include supplier information</li> </ul> <p><strong>And the problem:</strong> there is no primary key for the fact table. The primary key should be something that uniquely identifies each delivery plus the ProductKey. But I have no way to uniquely identify a delivery.</p> <p>In the source OLTP database there is a DeliveryID that is unique for every delivery, but that is an internal ID that meaningless to users. The InvoiceNumber is the suppliers' invoices number -- this is typed in manually and so we get duplicates.</p> <p>In the cube, I created a dimension based only on the InvoiceNumber field in FactDeliveres. That does mean that when you group by InvoiceNumber, you might get 2 deliveries combined only because they (mistakenly) have the same InvoiceNumber.</p> <p>I feel that I need to include the DeliveryID (to be called DeliveryKey), but I'm not sure how. </p> <p><strong>So, do I:</strong> </p> <ol> <li>Use that as the underlying key for the InvoiceNumber dimension?</li> <li>Create a DimDelivery that grows every time there is a new delivery? That could mean that some attributes come out of FactDeliveries and go into DimDelivery, like DeliveryDate,Supplier, InvoiceNumber.</li> </ol> <p>After all that, I could just ask you: how do I create a Deliveries cube when I have the following information in my source database</p> <p><strong>DeliveryHeaders</strong></p> <ul> <li>DeliveryID (PK)</li> <li>DeliveryDate</li> <li>SupplierID (FK)</li> <li>InvoiceNumber (typed in manually)</li> </ul> <p><strong>DeliveryDetails</strong></p> <ul> <li>DeliveryID (PK)</li> <li>ProductID (PK)</li> <li>Quantity</li> <li>UnitCosT</li> </ul>
[ { "answer_id": 149951, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 2, "selected": false, "text": "<p>I would have Quantity, UnitCode, InvoiceNumber, DeliveryID all in the fact table. Both InvoiceNumber and DeliveryID ...
2008/09/29
[ "https://Stackoverflow.com/questions/149871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16279/" ]
I'm building a data warehouse that includes delivery information for restaurants. The data is stored in SQL Server 2005 and is then put into a SQL Server Analysis Services 2005 cube. The Deliveries information consists of the following tables: **FactDeliveres** * BranchKey * DeliveryDateKey * ProductKey * InvoiceNumber (DD: degenerate dimension) * Quantity * UnitCosT * Linecost **Note:** * The granularity of FactDeliveres is each line on the invoice * The Product dimension include supplier information **And the problem:** there is no primary key for the fact table. The primary key should be something that uniquely identifies each delivery plus the ProductKey. But I have no way to uniquely identify a delivery. In the source OLTP database there is a DeliveryID that is unique for every delivery, but that is an internal ID that meaningless to users. The InvoiceNumber is the suppliers' invoices number -- this is typed in manually and so we get duplicates. In the cube, I created a dimension based only on the InvoiceNumber field in FactDeliveres. That does mean that when you group by InvoiceNumber, you might get 2 deliveries combined only because they (mistakenly) have the same InvoiceNumber. I feel that I need to include the DeliveryID (to be called DeliveryKey), but I'm not sure how. **So, do I:** 1. Use that as the underlying key for the InvoiceNumber dimension? 2. Create a DimDelivery that grows every time there is a new delivery? That could mean that some attributes come out of FactDeliveries and go into DimDelivery, like DeliveryDate,Supplier, InvoiceNumber. After all that, I could just ask you: how do I create a Deliveries cube when I have the following information in my source database **DeliveryHeaders** * DeliveryID (PK) * DeliveryDate * SupplierID (FK) * InvoiceNumber (typed in manually) **DeliveryDetails** * DeliveryID (PK) * ProductID (PK) * Quantity * UnitCosT
I would have Quantity, UnitCode, InvoiceNumber, DeliveryID all in the fact table. Both InvoiceNumber and DeliveryID are degenerate dimensions, because they will change with every fact (or very few facts). It is possible that you could put them in their own dimension if you have a large number of items on each order. The model below may not be 100% correct if you have multiple deliveries on an invoice, but it will be close. Check out Kimball, he might have an example of a star schema for this business scenario. ``` Fact table: OrderDateID (not in your model, but probably should be, date dimension in a role) DeliveryDateID (date dimension in a role) SupplierID (supplier dimension surrogate key) InvoiceID (invoice dimension surrogate key) ProductID (product dimension surrogate key) Quantity (fact) UnitCost (fact) InvoiceNumber (optional) DeliveryID (optional) ``` with the usual date dimension table and the following dimensions: ``` Supplier Dim: SupplierID (surrogate) SupplierCode and data Invoice Dim: InvoiceID (surrogate) InvoiceNumber (optional) DeliveryID (optional) Product Dim: ProductID (surrogate) ProductCode and Data ``` Always remember, your (star schema) data warehouse is not going to be structured at all like your OLTP data - it's all about the facts and what dimensions describe them.
149,909
<p>I would like to specify a constraint which is another type with a generic argument.</p> <pre><code>class KeyFrame&lt;T&gt; { public float Time; public T Value; } // I want any kind of Keyframe to be accepted class Timeline&lt;T&gt; where T : Keyframe&lt;*&gt; { } </code></pre> <p>But this cannot be done in c# as of yet, (and I really doubt it will ever be). Is there any elegant solution to this rather than having to specify the type of the keyframe argument?:</p> <pre><code>class Timeline&lt;TKeyframe, TKeyframeValue&gt; where TKeyframe : Keyframe&lt;TKeyframeValue&gt;, { } </code></pre>
[ { "answer_id": 149954, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 2, "selected": false, "text": "<p>As TimeLine is most likely an aggregation of KeyFrames, wouldn't something like:</p>\n\n<pre><code>class TimeLine&lt;T...
2008/09/29
[ "https://Stackoverflow.com/questions/149909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7839/" ]
I would like to specify a constraint which is another type with a generic argument. ``` class KeyFrame<T> { public float Time; public T Value; } // I want any kind of Keyframe to be accepted class Timeline<T> where T : Keyframe<*> { } ``` But this cannot be done in c# as of yet, (and I really doubt it will ever be). Is there any elegant solution to this rather than having to specify the type of the keyframe argument?: ``` class Timeline<TKeyframe, TKeyframeValue> where TKeyframe : Keyframe<TKeyframeValue>, { } ```
Read about this from [Eric Lippert's blog](http://blogs.msdn.com/ericlippert/archive/2008/05/19/a-generic-constraint-question.aspx) Basically, you have to find a way to refer to the type you want without specifying the secondary type parameter. In his post, he shows this example as a possible solution: ``` public abstract class FooBase { private FooBase() {} // Not inheritable by anyone else public class Foo<U> : FooBase {...generic stuff ...} ... nongeneric stuff ... } public class Bar<T> where T: FooBase { ... } ... new Bar<FooBase.Foo<string>>() ``` Hope that helps, Troy
149,939
<p>I would like to do something like <code>&lt;test:di id="someService"</code>/`><br> &lt;% someService.methodCall(); %></p> <p>where <code>&lt;test:di</code><br> gets and instantiates a service bean and creates a scripting variable for use. similar to how jsp:usebean works for example <code>&lt;jsp:useBean id="someDate" class="java.util.Date"</code>/><br> &lt;%<br> someDate.getYear();</p> <pre><code>%&gt; </code></pre> <p>how do i make my own objects available as a scritping variable?</p>
[ { "answer_id": 149989, "author": "zmf", "author_id": 13285, "author_profile": "https://Stackoverflow.com/users/13285", "pm_score": 1, "selected": false, "text": "<p>I think you're trying to write your own tag library.</p>\n\n<p>Check out the tutorial at:\n<a href=\"http://www.ironflare.c...
2008/09/29
[ "https://Stackoverflow.com/questions/149939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20641/" ]
I would like to do something like `<test:di id="someService"`/`> <% someService.methodCall(); %> where `<test:di` gets and instantiates a service bean and creates a scripting variable for use. similar to how jsp:usebean works for example `<jsp:useBean id="someDate" class="java.util.Date"`/> <% someDate.getYear(); ``` %> ``` how do i make my own objects available as a scritping variable?
The way this is done in a Tag Library is by using a Tag Extra Info (TEI) class. You can find an [example here](http://www.stardeveloper.com/articles/display.html?article=2001081601&page=2).
149,956
<p>Does anyone know of a method to determine when a file copy completes in VBScript? I'm using the following to copy:</p> <pre><code>set sa = CreateObject("Shell.Application") set zip = sa.NameSpace(saveFile) set Fol = sa.NameSpace(folderToZip) zip.copyHere (Fol.items) </code></pre>
[ { "answer_id": 149979, "author": "Matt Dillard", "author_id": 863, "author_profile": "https://Stackoverflow.com/users/863", "pm_score": 2, "selected": false, "text": "<p>You may have better luck using the Copy method on a <a href=\"http://msdn.microsoft.com/en-us/library/6973t06a(VS.85)....
2008/09/29
[ "https://Stackoverflow.com/questions/149956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14092/" ]
Does anyone know of a method to determine when a file copy completes in VBScript? I'm using the following to copy: ``` set sa = CreateObject("Shell.Application") set zip = sa.NameSpace(saveFile) set Fol = sa.NameSpace(folderToZip) zip.copyHere (Fol.items) ```
``` Do Until zip.Items.Count = Fol.Items.Count WScript.Sleep 300 Loop ``` When the loop finishes your copy is finished. But if you only want to copy and not zip, FSO or WMI is better. If you are zipping and want them in a file you have to create the zip-file yourself, with the right header first. Else you only get compressed files/folders IIRC. Something like this: ``` Set FSO = CreateObject( "Scripting.FileSystemObject" ) Set File = FSO.OpenTextFile( saveFile, 2, True ) File.Write "PK" & Chr(5) & Chr(6) & String( 18, Chr(0) ) File.Close Set File = Nothing Set FSO = Nothing ``` The 2 in OpenTextFile is ForWriting.
149,995
<p>I have a C++ program representing a TCP header as a struct:</p> <pre><code>#include "stdafx.h" /* TCP HEADER 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Source Port | Destination Port | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Sequence Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Acknowledgment Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Data | |U|A|P|R|S|F| | | Offset| Reserved |R|C|S|S|Y|I| Window | | | |G|K|H|T|N|N| | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Checksum | Urgent Pointer | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Options | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | data | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ typedef struct { // RFC793 WORD wSourcePort; WORD wDestPort; DWORD dwSequence; DWORD dwAcknowledgment; unsigned int byReserved1:4; unsigned int byDataOffset:4; unsigned int fFIN:1; unsigned int fSYN:1; unsigned int fRST:1; unsigned int fPSH:1; unsigned int fACK:1; unsigned int fURG:1; unsigned int byReserved2:2; unsigned short wWindow; WORD wChecksum; WORD wUrgentPointer; } TCP_HEADER, *PTCP_HEADER; int _tmain(int argc, _TCHAR* argv[]) { printf("TCP header length: %d\n", sizeof(TCP_HEADER)); return 0; } </code></pre> <p>If I run this program I get the size of this header as 24 bytes, which is not the size I was expecting. If I change the type of the field "wWindow" to "unsigned int wWindow:16", which has the same number of bits as an unsigned short, the program tells me the size of the struct is now 20 bytes, the correct size. Why is this?</p> <p>I am using Microsoft Visual Studio 2005 with SP1 on a 32-bit x86 machine.</p>
[ { "answer_id": 150001, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 3, "selected": false, "text": "<p>Because the compiler is packing your bitfield into a 32-bit int, not a 16-bit entity.</p>\n\n<p>In general you sho...
2008/09/29
[ "https://Stackoverflow.com/questions/149995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a C++ program representing a TCP header as a struct: ``` #include "stdafx.h" /* TCP HEADER 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Source Port | Destination Port | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Sequence Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Acknowledgment Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Data | |U|A|P|R|S|F| | | Offset| Reserved |R|C|S|S|Y|I| Window | | | |G|K|H|T|N|N| | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Checksum | Urgent Pointer | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Options | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | data | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ typedef struct { // RFC793 WORD wSourcePort; WORD wDestPort; DWORD dwSequence; DWORD dwAcknowledgment; unsigned int byReserved1:4; unsigned int byDataOffset:4; unsigned int fFIN:1; unsigned int fSYN:1; unsigned int fRST:1; unsigned int fPSH:1; unsigned int fACK:1; unsigned int fURG:1; unsigned int byReserved2:2; unsigned short wWindow; WORD wChecksum; WORD wUrgentPointer; } TCP_HEADER, *PTCP_HEADER; int _tmain(int argc, _TCHAR* argv[]) { printf("TCP header length: %d\n", sizeof(TCP_HEADER)); return 0; } ``` If I run this program I get the size of this header as 24 bytes, which is not the size I was expecting. If I change the type of the field "wWindow" to "unsigned int wWindow:16", which has the same number of bits as an unsigned short, the program tells me the size of the struct is now 20 bytes, the correct size. Why is this? I am using Microsoft Visual Studio 2005 with SP1 on a 32-bit x86 machine.
See this question: [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](https://stackoverflow.com/questions/119123/why-does-the-sizeof-operator-return-a-size-larger-for-a-structure-than-the-tota) . I believe that compiler takes a hint to disable padding when you use the "unsigned int wWindow:16" syntax. Also, note that a short is not guaranteed to be 16 bits. The guarantee is that: 16 bits <= size of a short <= size of an int.
150,010
<p>I am creating a "department picker" form that is going to serve as a modal popup form with many of my "primary" forms of a Winforms application. Ideally the user is going to click on an icon next to a text box that will pop up the form, they will select the department they need, and when they click OK, the dialog will close and I will have the value selected for me to update the textbox with.</p> <p>I've already done the route with passing the owner of the dialog box into the dialog form and having the OK button click event do the proper update, but this forces me to do a DirectCast to the form type and I can then only reuse the picker on the current form.</p> <p>I have been able to use a ByRef variable in the constructor and successfully update a value, but it works only in the constructor. If I attempt to assign the ByRef value to some internal variable in the Department Picker class, I lose the reference aspect of it. This is my basic code attached to my form: </p> <pre><code>Public Class DeptPicker Private m_TargetResult As String Public Sub New(ByRef TargetResult As String) InitializeComponent() ' This works just fine, my "parent" form has the reference value properly updated. TargetResult = "Booyah!" ' Once I leave the constructor, m_TargetResult is a simple string value that won't update the parent m_TargetResult = TargetResult End Sub Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click DialogResult = Windows.Forms.DialogResult.OK ' I get no love here. m_TargetResult is just a string and doesn't push the value back to the referenced variable I want. m_TargetResult = "That department I selected." Me.Close() End Sub Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click DialogResult = Windows.Forms.DialogResult.Cancel Me.Close() End Sub End Class </code></pre> <p>Can somebody tell me what I'm missing here or a different approach to make this happen?</p> <p><em>Note: Code sample is in VB.NET, but I'll take any C# answers too. 8^D</em></p>
[ { "answer_id": 150021, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 3, "selected": true, "text": "<p>In such cases, I usually either</p>\n\n<ul>\n<li>Write a ShowDialog function that does what I want (e.g. return the ...
2008/09/29
[ "https://Stackoverflow.com/questions/150010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71/" ]
I am creating a "department picker" form that is going to serve as a modal popup form with many of my "primary" forms of a Winforms application. Ideally the user is going to click on an icon next to a text box that will pop up the form, they will select the department they need, and when they click OK, the dialog will close and I will have the value selected for me to update the textbox with. I've already done the route with passing the owner of the dialog box into the dialog form and having the OK button click event do the proper update, but this forces me to do a DirectCast to the form type and I can then only reuse the picker on the current form. I have been able to use a ByRef variable in the constructor and successfully update a value, but it works only in the constructor. If I attempt to assign the ByRef value to some internal variable in the Department Picker class, I lose the reference aspect of it. This is my basic code attached to my form: ``` Public Class DeptPicker Private m_TargetResult As String Public Sub New(ByRef TargetResult As String) InitializeComponent() ' This works just fine, my "parent" form has the reference value properly updated. TargetResult = "Booyah!" ' Once I leave the constructor, m_TargetResult is a simple string value that won't update the parent m_TargetResult = TargetResult End Sub Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click DialogResult = Windows.Forms.DialogResult.OK ' I get no love here. m_TargetResult is just a string and doesn't push the value back to the referenced variable I want. m_TargetResult = "That department I selected." Me.Close() End Sub Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click DialogResult = Windows.Forms.DialogResult.Cancel Me.Close() End Sub End Class ``` Can somebody tell me what I'm missing here or a different approach to make this happen? *Note: Code sample is in VB.NET, but I'll take any C# answers too. 8^D*
In such cases, I usually either * Write a ShowDialog function that does what I want (e.g. return the value) or * Just let the result be a property in the dialog. This is how the common file dialogs do it in the BCL. The caller must then read the property to get the result. That's fine in my opinion. You can also combine these methods, by making the result value a property in the dialog and creating a ShowDialog method that returns that property value, either as ByRef as you want or as a return value, depending on your needs. I'll add this as a usage instruction, for example (sorry, no VB over here, and you said C# is welcome): ``` using (var dlg = new DeptPicker()) { if (dlg.ShowDialog() == DialogResult.OK) { myTextBoxOrWhatEver.Text = dlg.TargetResult; } } ``` In the dialog itself, just do this: ``` void okButton_Click(object sender, EventArgs e) { TargetResult = whatever; // can also do this when the selection changes DialogResult = DialogResult.OK; Close(); } ``` I didn't use the new ShowDialog implementation in this sample though.
150,011
<p>My clients application exports and imports quite a few variables of type real through a text file using writeln and readln. I've tried to increase the width of the fields written so the code looks like: </p> <pre><code>writeln(file, exportRealvalue:30); //using excess width of field .... readln(file, importRealvalue); </code></pre> <p>When I export and then import and export again and compare the files I get a difference in the last two digits, e.g (might be off on the actual number of digits here but you get it): </p> <pre><code>-1.23456789012E-0002 -1.23456789034E-0002 </code></pre> <p>This actually makes a difference in the app so the client wants to know what I can do about it. Now I'm not sure it's only the write/read that does it but I thought I'd throw a quick question out there before I dive into the hey stack again. Do I need to go binary on this?</p> <p>This is not an app dealing with currency or something, I just write and read the values to/from file. I know floating points are a bit strange sometimes and I thought one of the routines (writeln/readln) may have some funny business going on.</p>
[ { "answer_id": 150180, "author": "Jon Trauntvein", "author_id": 19674, "author_profile": "https://Stackoverflow.com/users/19674", "pm_score": 0, "selected": false, "text": "<p>When using floating point types, you should be aware of the precision limitations on the specified types. A 4 b...
2008/09/29
[ "https://Stackoverflow.com/questions/150011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9077/" ]
My clients application exports and imports quite a few variables of type real through a text file using writeln and readln. I've tried to increase the width of the fields written so the code looks like: ``` writeln(file, exportRealvalue:30); //using excess width of field .... readln(file, importRealvalue); ``` When I export and then import and export again and compare the files I get a difference in the last two digits, e.g (might be off on the actual number of digits here but you get it): ``` -1.23456789012E-0002 -1.23456789034E-0002 ``` This actually makes a difference in the app so the client wants to know what I can do about it. Now I'm not sure it's only the write/read that does it but I thought I'd throw a quick question out there before I dive into the hey stack again. Do I need to go binary on this? This is not an app dealing with currency or something, I just write and read the values to/from file. I know floating points are a bit strange sometimes and I thought one of the routines (writeln/readln) may have some funny business going on.
If you want to specify the precision of a real with a WriteLn, use the following: ``` WriteLn(RealVar:12:3); ``` It outputs the value Realvar with at least 12 positions and a precision of 3.
150,017
<p>I have a query that I'm executing from a .NET application to a SQL Server database and it seems to take quite a while to complete (5+ Minutes). I created a test app in c# to try to see what was talking so long (the query should return quickly). </p> <p>As I was reconstructing the query by adding in elements to see which portion was taking so long, I ended up reconstructing the query practically verbatim where the only difference was the spaces in the original query and a capitalization difference. This difference returned a result in about 100 milliseconds.</p> <p>Has anybody seen this before? I'm wondering if there are services turned off in our server (since a coworker has the same problem) or on our computers.</p> <p>Thanks in advance for any help with this.</p> <p>Code Sample Below (The Difference in in the first line of the query at the end (fk_source vs. fk _Source):</p> <pre><code>//Original OleDbCommand comm = new OleDbCommand("select min(ctc.serial_no) as MIN_INTERVAL from countstypecode ctc, source s, countstype ct, counts c where ct.value_id=c.value_id and s.c_id=ct.fk_source and " + "ct.timeinterval=ctc.typename and ct.timeinterval in ('15min','1h','1day') and c.time_stamp &gt;= CONVERT(datetime,'01-01-2008',105) and c.time_stamp &lt; " + "CONVERT(datetime,'01-01-2009',105) and s.c_id = '27038dbb19ed93db011a315297df3b7a'", dbConn); //Rebuilt OleDbCommand comm = new OleDbCommand("select min(ctc.serial_no) as MIN_INTERVAL from countstypecode ctc, source s, countstype ct, counts c where ct.value_id=c.value_id and s.c_id=ct.fk_Source and " + "ct.timeinterval=ctc.typename and ct.timeinterval in ('15min','1h','1day') and c.time_stamp &gt;= CONVERT(datetime,'01-01-2008',105) and c.time_stamp &lt; " + "CONVERT(datetime,'01-01-2009',105) and s.c_id='27038dbb19ed93db011a315297df3b7a'", dbConn); </code></pre>
[ { "answer_id": 150029, "author": "Russ Cam", "author_id": 1831, "author_profile": "https://Stackoverflow.com/users/1831", "pm_score": 1, "selected": false, "text": "<p>Since you are using SQL Server 2005, have you tried with a SqlCommand object instead of the OleDbCommand object?</p>\n" ...
2008/09/29
[ "https://Stackoverflow.com/questions/150017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23553/" ]
I have a query that I'm executing from a .NET application to a SQL Server database and it seems to take quite a while to complete (5+ Minutes). I created a test app in c# to try to see what was talking so long (the query should return quickly). As I was reconstructing the query by adding in elements to see which portion was taking so long, I ended up reconstructing the query practically verbatim where the only difference was the spaces in the original query and a capitalization difference. This difference returned a result in about 100 milliseconds. Has anybody seen this before? I'm wondering if there are services turned off in our server (since a coworker has the same problem) or on our computers. Thanks in advance for any help with this. Code Sample Below (The Difference in in the first line of the query at the end (fk\_source vs. fk \_Source): ``` //Original OleDbCommand comm = new OleDbCommand("select min(ctc.serial_no) as MIN_INTERVAL from countstypecode ctc, source s, countstype ct, counts c where ct.value_id=c.value_id and s.c_id=ct.fk_source and " + "ct.timeinterval=ctc.typename and ct.timeinterval in ('15min','1h','1day') and c.time_stamp >= CONVERT(datetime,'01-01-2008',105) and c.time_stamp < " + "CONVERT(datetime,'01-01-2009',105) and s.c_id = '27038dbb19ed93db011a315297df3b7a'", dbConn); //Rebuilt OleDbCommand comm = new OleDbCommand("select min(ctc.serial_no) as MIN_INTERVAL from countstypecode ctc, source s, countstype ct, counts c where ct.value_id=c.value_id and s.c_id=ct.fk_Source and " + "ct.timeinterval=ctc.typename and ct.timeinterval in ('15min','1h','1day') and c.time_stamp >= CONVERT(datetime,'01-01-2008',105) and c.time_stamp < " + "CONVERT(datetime,'01-01-2009',105) and s.c_id='27038dbb19ed93db011a315297df3b7a'", dbConn); ```
I suspect that this is a procedure cache issue. One benefit of stored procedures is that the plan is stored for you, which speeds things up. Unfortunately, it's possible to get a bad plan in the cache (even when using dynamic queries). Just for fun, I checked my procedure cache, ran an adhoc query, checked again, then I ran the same query with different capitlization and I was surprised to see the procedure count higher. Try this.... Connect to SQL Server Management Studio. ``` DBCC MemoryStatus Select Columns... From TABLES.... Where.... dbcc MemoryStatus Select Columns... From tables.... Where.... dbcc MemoryStatus ``` I think you'll find that the TotalProcs changes when the statement changes (even when the only change is case sensitive). Updating your statistics may help. That is a rather slow running process, so you may want to run that during a slow period.
150,032
<p>We have a Cash flow report which is basically in this structure:</p> <pre><code>Date |Credit|Debit|balance| 09/29| 20 | 10 | 10 | 09/30| 0 | 10 | 0 | </code></pre> <p>The main problem is the balance, and as we are using a DataSet for the Data, it's kinda hard to calculate the balance on the DataSet, because we always need the balance from the previous day.</p> <p>Also this data comes from several tables and it's been hard to maintain this procedure, because the database metadata is changing frequently.</p> <p>Anyone could give me some possible different solutions? for the problem?</p> <p>This report is being displayed on a DataGrid.</p>
[ { "answer_id": 150064, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 0, "selected": false, "text": "<p>On the code side of things, you've got two relatively easy options, but they both involve iterating through the ...
2008/09/29
[ "https://Stackoverflow.com/questions/150032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/727/" ]
We have a Cash flow report which is basically in this structure: ``` Date |Credit|Debit|balance| 09/29| 20 | 10 | 10 | 09/30| 0 | 10 | 0 | ``` The main problem is the balance, and as we are using a DataSet for the Data, it's kinda hard to calculate the balance on the DataSet, because we always need the balance from the previous day. Also this data comes from several tables and it's been hard to maintain this procedure, because the database metadata is changing frequently. Anyone could give me some possible different solutions? for the problem? This report is being displayed on a DataGrid.
This may be too big a change or off the mark for you, but a cash flow report indicates to me that you are probably maintaining, either formally or informally, a general ledger arrangement of some sort. If you are, then maybe I am naive about this but I think you should maintain your general ledger detail as a single table that has a bare minimum number of columns like ID, date, account, source and amount. All of the data that comes from different tables suggests that there several different kinds of events that are affecting your cash. To me, representing these different kinds of events in their own tables (like accounts receivable or accounts payable or inventory or whatever) makes sense, but the trick is to not have any monetary columns in those other tables. Instead, have them refer to the row in the general ledger detail where that data is recorded. If you enforce this, then the cash flow would always work the same regardless of changes to the other tables. The balance forward issue still has to be addressed and you have to take into account the number of transactions involved and the responsiveness required of the system but at least you could make a decision about how to handle it one time and not have to make changes as the other parts of your system evolve.
150,033
<p>What is the easiest way to match non-ASCII characters in a regex? I would like to match all words individually in an input string, but the language may not be English, so I will need to match things like ü, ö, ß, and ñ. Also, this is in Javascript/jQuery, so any solution will need to apply to that. </p>
[ { "answer_id": 150062, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 2, "selected": false, "text": "<p>All Unicode-enabled Regex flavours should have a special character class like \\w that match any Unicode letter. Ta...
2008/09/29
[ "https://Stackoverflow.com/questions/150033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85/" ]
What is the easiest way to match non-ASCII characters in a regex? I would like to match all words individually in an input string, but the language may not be English, so I will need to match things like ü, ö, ß, and ñ. Also, this is in Javascript/jQuery, so any solution will need to apply to that.
This should do it: ``` [^\x00-\x7F]+ ``` It matches any character which is not contained in the [ASCII character set](http://en.wikipedia.org/wiki/American_Standard_Code_for_Information_Interchange) (0-127, i.e. 0x0 to 0x7F). You can do the same thing with Unicode: ``` [^\u0000-\u007F]+ ``` For unicode you can look at this 2 resources: * [Code charts](http://www.unicode.org/charts/) list of Unicode ranges * [This tool](http://kourge.net/projects/regexp-unicode-block) to create a regex filtered by Unicode block.
150,038
<p>I have a middle tier containing several related objects and a data tier that is using a DataSet with several DataTables and relationships.</p> <p>I want to call a Save method on one of my objects (a parent object) and have its private variable data transformed into a DataRow and added to a DataTable. Some of the private variable data are actually other objects (child object) that each need to have their own Save method called and their own variable data persisted.</p> <p>How do I "lace" this together? What parts of a DataSet should be instantiated in the ParentObject and what needs to be passed to the ChildObjects so they can add themselves to the dataset?</p> <p>Also, how do I wire the relationships together for 2 tables?</p> <p>The examples I have seen for an Order OrderDetail relationship create the OrderRow and the OrderDetailRow then call OrderDetailRow.SetParentRow(OrderDetail)</p> <p>I do not think this will work for me since my Order and OrderDetail (using their examples naming) are in separate classes and the examples have it all happening in a Big Honking Method.</p> <p>Thank you, Keith</p>
[ { "answer_id": 151255, "author": "Keith Sirmons", "author_id": 1048, "author_profile": "https://Stackoverflow.com/users/1048", "pm_score": 0, "selected": false, "text": "<p>So, What I am doing right now is passing a reference to the DataSet and a reference to the DataRow of the parent in...
2008/09/29
[ "https://Stackoverflow.com/questions/150038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1048/" ]
I have a middle tier containing several related objects and a data tier that is using a DataSet with several DataTables and relationships. I want to call a Save method on one of my objects (a parent object) and have its private variable data transformed into a DataRow and added to a DataTable. Some of the private variable data are actually other objects (child object) that each need to have their own Save method called and their own variable data persisted. How do I "lace" this together? What parts of a DataSet should be instantiated in the ParentObject and what needs to be passed to the ChildObjects so they can add themselves to the dataset? Also, how do I wire the relationships together for 2 tables? The examples I have seen for an Order OrderDetail relationship create the OrderRow and the OrderDetailRow then call OrderDetailRow.SetParentRow(OrderDetail) I do not think this will work for me since my Order and OrderDetail (using their examples naming) are in separate classes and the examples have it all happening in a Big Honking Method. Thank you, Keith
I will not start another debate whether datasets are good or evil. If you continue to use them, here are something to consider: * You need to keep the original dataset and update that, in order to get correct inserts and updates. * You want your parents to know their children, but not the other way. Banish the ParentTable. * An Order and its OrderDetails is an aggregate (from Domain Driven Design) and should be considered as a whole. A call to order.Save() should save everything. Well, that's the theory. How can we do that? One way is to create the following artifacts: * Order * OrderDetail * OrderRepository * OrderMap The OrderMap is where you manage the Order to Dataset relationships. Internally, it could use a Hashtable or a Dictionary. The OrderRepository is where you get your Orders from. The repository will get the dataset with all relations from somewhere, build the Order with all its OrderDetails, and store the Order/Dataset relationship in the OrderMap. The OrderMap must be kept alive as long as the Order is alive. The Order contains all OrderDetails. Pass the order to the repository and let it save it. The repository will get the dataset from the map, update the Order-table from the order and iterate all order-details to update the OrderDetail-table. Retrieve and save: ``` var order = repository.GetOrder(id); repository.Save(order); ``` Inside OrderRepository.GetOrder(): ``` var ds = db.GetOrderAndDetailsBy(id); var order = new Order(); UpdateOrder(ds, order); UpdateOrderDetails(ds, order); // creates and updates OrderDetail, add it to order. map.Register(ds, order); ``` Inside OrderRepository.Save(): ``` var ds = map.GetDataSetFor(order); UpdateFromOrder(ds, order); foreach(var detail in order.Details) UpdateFromDetail(ds.OrderDetail, detail); ``` Some final notes: * You can implement the map as a singelton. * Let the map use weak references. Then any order should be garbage-collected when it should, and memory will be freed. * You need some way to associate an OrderDetail with its table-row * If you have the slightest possibility to upgrade to .NET 3.5, do it. Linq to Sql or Linq to Entity will remove some of your pain. * All of this is created out of thin air. I hope it's not too inaccurate.
150,042
<p>I have tried this...</p> <pre><code>Dim myMatches As String() = System.Text.RegularExpressions.Regex.Split(postRow.Item("Post"), "\b\#\b") </code></pre> <p>But it is splitting all words, I want an array of words that start with#</p> <p>Thanks!</p>
[ { "answer_id": 150086, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 1, "selected": false, "text": "<p>Since you want to include the words in the split you should use something like</p>\n\n<pre><code>\"\\b#\\w+\\b\"\n</code...
2008/09/29
[ "https://Stackoverflow.com/questions/150042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6514/" ]
I have tried this... ``` Dim myMatches As String() = System.Text.RegularExpressions.Regex.Split(postRow.Item("Post"), "\b\#\b") ``` But it is splitting all words, I want an array of words that start with# Thanks!
This seems to work... c# ``` Regex MyRegex = new Regex("\\#\\w+"); MatchCollection ms = MyRegex.Matches(InputText); ``` or vb.net ``` Dim MyRegex as Regex = new Regex("\#\w+") Dim ms as MatchCollection = MyRegex.Matches(InputText) ``` Given input text of... "asdfas asdf #asdf asd fas df asd fas #df asd f asdf" ...this will yield.... "#asdf" and "#df" I'll grant you that this does not get you a string Array but the MatchCollection is enumerable and so might be good enough. --- Additionally, I'll add that I got this through the use of [Expresso](http://www.ultrapico.com/Expresso.htm). which appears to be free. It was very helpful in producing the c# which I am very poor at. (Ie it did the escaping for me.) (If anyone thinks I should remove this pseudo-advert then please comment, but I thought it might be helpful :) Good times )
150,044
<p>I'm new to ASP.NET and want to have an asp:content control for the page title, but I want that value to be used for the tag and for a page header. When I tried to do this with two tags with the same id, it complained that I couldn't have two tags with the same id. Is there a way to achieve this with contentplaceholders, and if not what would be the easiest way to use a single parameter to the masterpage twice in one page?</p>
[ { "answer_id": 150072, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": true, "text": "<p>Title is actually an attribute on content pages, so you do something like:</p>\n\n<pre><code>&lt;%@ Page Language=\"...
2008/09/29
[ "https://Stackoverflow.com/questions/150044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6222/" ]
I'm new to ASP.NET and want to have an asp:content control for the page title, but I want that value to be used for the tag and for a page header. When I tried to do this with two tags with the same id, it complained that I couldn't have two tags with the same id. Is there a way to achieve this with contentplaceholders, and if not what would be the easiest way to use a single parameter to the masterpage twice in one page?
Title is actually an attribute on content pages, so you do something like: ``` <%@ Page Language="C#" MasterPageFile="~/default.master" Title="My Content Title" %> ``` on the content page. To get that into a header, on the master page just render the page title: ``` <h1><%= this.Page.Title %></h3> ```
150,047
<p>Does anyone know how to get the name of the TARGET (/t) called from the MSBuild command line? There are a few types of targets that can be called and I want to use that property in a notification to users.</p> <p>Example:</p> <pre><code>msbuild Project.proj /t:ApplicationDeployment /p:Environment=DEV </code></pre> <p>I want access to the target words <code>ApplicationDeployment</code> in my .Proj file. </p> <p>Is there a property I can access? Any clue how to do this?</p> <p><strong>EDIT:</strong> I do not want to have to also pass in a property to get this.</p> <p><strong>UPDATE:</strong> This is based on <strong>deployment scripts</strong> using MSBuild scripts. My build server is not used for deploying code, only for building. The build server itself has build notifications that can be opted into.</p>
[ { "answer_id": 150271, "author": "Tim Booker", "author_id": 10046, "author_profile": "https://Stackoverflow.com/users/10046", "pm_score": 4, "selected": false, "text": "<p>I'm not sure how to do exactly what you ask, but could you pass that string using the /p option?</p>\n\n<pre><code>m...
2008/09/29
[ "https://Stackoverflow.com/questions/150047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18475/" ]
Does anyone know how to get the name of the TARGET (/t) called from the MSBuild command line? There are a few types of targets that can be called and I want to use that property in a notification to users. Example: ``` msbuild Project.proj /t:ApplicationDeployment /p:Environment=DEV ``` I want access to the target words `ApplicationDeployment` in my .Proj file. Is there a property I can access? Any clue how to do this? **EDIT:** I do not want to have to also pass in a property to get this. **UPDATE:** This is based on **deployment scripts** using MSBuild scripts. My build server is not used for deploying code, only for building. The build server itself has build notifications that can be opted into.
I found the answer! ``` <Target Name="ApplicationDeployment" > <CreateProperty Value="$(MSBuildProjectName) - $(Environment) - Application Deployment Complete"> <Output TaskParameter="Value" PropertyName="DeploymentCompleteNotifySubject" /> </CreateProperty> ``` I would like to give partial credit to apathetic. Not sure how to do that.
150,053
<p>How can I limit my post-build events to running only for one type of build?</p> <p>I'm using the events to copy DLL files to a local IIS virtual directory, but I don't want this happening on the build server in release mode.</p>
[ { "answer_id": 150070, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 3, "selected": false, "text": "<p>You can pass the configuration name to the post-build script and check it in there to see if it should run.</p>\n\n<p>...
2008/09/29
[ "https://Stackoverflow.com/questions/150053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3615/" ]
How can I limit my post-build events to running only for one type of build? I'm using the events to copy DLL files to a local IIS virtual directory, but I don't want this happening on the build server in release mode.
Pre- and Post-Build Events run as a batch script. You can do a conditional statement on `$(ConfigurationName)`. For instance ``` if $(ConfigurationName) == Debug xcopy something somewhere ```
150,076
<p>I created a Rails application normally. Then created the scaffold for an event class. Then tried the following code. When run it complains about a InvalidAuthenticityToken when the destroy method is executed. How do I authenticate to avoid this response?</p> <pre><code>require 'rubygems' require 'activeresource' class Event &lt; ActiveResource::Base self.site = "http://localhost:3000" end e = Event.create( :name =&gt; "Shortest Event Ever!", :starts_at =&gt; 1.second.ago, :capacity =&gt; 25, :price =&gt; 10.00) e.destroy </code></pre>
[ { "answer_id": 150109, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 3, "selected": false, "text": "<p>By default, all innodb databases in a given mysql server installation use the same physical pool of data files, so con...
2008/09/29
[ "https://Stackoverflow.com/questions/150076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/219658/" ]
I created a Rails application normally. Then created the scaffold for an event class. Then tried the following code. When run it complains about a InvalidAuthenticityToken when the destroy method is executed. How do I authenticate to avoid this response? ``` require 'rubygems' require 'activeresource' class Event < ActiveResource::Base self.site = "http://localhost:3000" end e = Event.create( :name => "Shortest Event Ever!", :starts_at => 1.second.ago, :capacity => 25, :price => 10.00) e.destroy ```
So I'm not sure [Matt Rogish's answer](https://stackoverflow.com/a/150763) is going to help 100%. The problem is that MySQL\* has a mutex (mutually exclusive lock) around opening and closing tables, so that basically means that if a table is in the process of being closed/deleted, *no* other tables can be opened. This is described by a colleague of mine here: <http://www.mysqlperformanceblog.com/2009/06/16/slow-drop-table/> One excellent impact reduction strategy is to use a filesystem like XFS. The workaround is ugly. You essentially have to nibble away at all the data in the tables before dropping them (see comment #11 on the link above).
150,084
<p>I have a collection of data stored in XDocuments and DataTables, and I'd like to address both as a single unified data space with XPath queries. So, for example, "/Root/Tables/Orders/FirstName" would fetch the value of the Firstname column in every row of the DataTable named "Orders". </p> <p>Is there a way to do this without copying all of the records in the DataTable into the XDocument?</p> <p>I'm using .Net 3.5</p>
[ { "answer_id": 150117, "author": "dacracot", "author_id": 13930, "author_profile": "https://Stackoverflow.com/users/13930", "pm_score": 0, "selected": false, "text": "<p>Are you looking for something similar to what I asked regarding <a href=\"https://stackoverflow.com/questions/142010/c...
2008/09/29
[ "https://Stackoverflow.com/questions/150084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5548/" ]
I have a collection of data stored in XDocuments and DataTables, and I'd like to address both as a single unified data space with XPath queries. So, for example, "/Root/Tables/Orders/FirstName" would fetch the value of the Firstname column in every row of the DataTable named "Orders". Is there a way to do this without copying all of the records in the DataTable into the XDocument? I'm using .Net 3.5
I eventually figured out the answer to this myself. I discovered a class in System.Xml.LINQ called XStreamingElement that can create an XML structure on-the-fly from a LINQ expression. Here's an example of casting a DataTable into an XML-space. ``` Dictionary<string,DataTable> Tables = new Dictionary<string,DataTable>(); // ... populate dictionary of tables ... XElement TableRoot = new XStreamingElement("Tables", from t in Tables select new XStreamingElement(t.Key, from DataRow r in t.Value.Rows select new XStreamingElement("row", from DataColumn c in t.Value.Columns select new XElement(c.ColumnName, r[c]))))) ``` The result is an XElement (TableRoot) with a structure similar to the following, assuming the dictionary contains one table called "Orders" with two rows. ``` <Tables> <Orders> <row> <sku>12345</sku> <quantity>2</quantity> <price>5.95</price> </row> <row> <sku>54321</sku> <quantity>3</quantity> <price>2.95</price> </row> </Orders> </Tables> ``` That can be merged with a larger XElement/XDocument based hierarchy and queried with XPath.
150,095
<p>I need to substitute the value of a string into my regular expression in Ruby. Is there an easy way to do this? For example:</p> <pre><code>foo = "0.0.0.0" goo = "here is some other stuff 0.0.0.0" if goo =~ /value of foo here dynamically/ puts "success!" end </code></pre>
[ { "answer_id": 150108, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 2, "selected": false, "text": "<p>Use Regexp.new:</p>\n\n<pre><code>if goo =~ Regexp.new(foo) # Evaluates to /0.0.0.0/\n</code></pre>\n" }, { "an...
2008/09/29
[ "https://Stackoverflow.com/questions/150095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422/" ]
I need to substitute the value of a string into my regular expression in Ruby. Is there an easy way to do this? For example: ``` foo = "0.0.0.0" goo = "here is some other stuff 0.0.0.0" if goo =~ /value of foo here dynamically/ puts "success!" end ```
Same as string insertion. ``` if goo =~ /#{Regexp.quote(foo)}/ #... ```
150,113
<p>An older application using System.Web.Mail is throwing an exception on emails coming from <em>hr@domain.com</em>. Other addresses appear to be working correctly. We changed our mail server to Exchange 2007 when the errors started, so I assume that is where the problem is. Does anyone know what is happening?</p> <p>Here is the exception and stack trace:</p> <blockquote> <p>System.Web.HttpException: Could not access 'CDO.Message' object. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException (0x80040212): The transport lost its connection to the server.<br/> <br/> --- End of inner exception stack trace ---<br/> at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters)<br/> at System.RuntimeType.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters)<br/> at System.Web.Mail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args)<br/> --- End of inner exception stack trace ---<br/> at System.Web.Mail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args)<br/> at System.Web.Mail.CdoSysHelper.Send(MailMessage message)<br/> at System.Web.Mail.SmtpMail.Send(MailMessage message)<br/> at ProcessEmail.Main()<br/></p> </blockquote>
[ { "answer_id": 150108, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 2, "selected": false, "text": "<p>Use Regexp.new:</p>\n\n<pre><code>if goo =~ Regexp.new(foo) # Evaluates to /0.0.0.0/\n</code></pre>\n" }, { "an...
2008/09/29
[ "https://Stackoverflow.com/questions/150113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17287/" ]
An older application using System.Web.Mail is throwing an exception on emails coming from *hr@domain.com*. Other addresses appear to be working correctly. We changed our mail server to Exchange 2007 when the errors started, so I assume that is where the problem is. Does anyone know what is happening? Here is the exception and stack trace: > > System.Web.HttpException: Could not access 'CDO.Message' object. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException (0x80040212): The transport lost its connection to the server. > > > > --- End of inner exception stack trace --- > > at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters) > > at System.RuntimeType.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) > > at System.Web.Mail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args) > > --- End of inner exception stack trace --- > > at System.Web.Mail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args) > > at System.Web.Mail.CdoSysHelper.Send(MailMessage message) > > at System.Web.Mail.SmtpMail.Send(MailMessage message) > > at ProcessEmail.Main() > > > >
Same as string insertion. ``` if goo =~ /#{Regexp.quote(foo)}/ #... ```
150,114
<p>I know plenty about the different ways of handling parsing text for information. For parsing integers for example, what kind of performance can be expected. I am wondering if anyone knows of any good stats on this. I am looking for some real numbers from someone who has tested this.</p> <p>Which of these offers the best performance in which situations?</p> <pre><code>Parse(...) // Crash if the case is extremely rare .0001% If (SomethingIsValid) // Check the value before parsing Parse(...) TryParse(...) // Using TryParse try { Parse(...) } catch { // Catch any thrown exceptions } </code></pre>
[ { "answer_id": 150123, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 7, "selected": true, "text": "<p>Always use <strong>T.TryParse(string str, out T value)</strong>. Throwing exceptions is expensive and should be avoided i...
2008/09/29
[ "https://Stackoverflow.com/questions/150114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22381/" ]
I know plenty about the different ways of handling parsing text for information. For parsing integers for example, what kind of performance can be expected. I am wondering if anyone knows of any good stats on this. I am looking for some real numbers from someone who has tested this. Which of these offers the best performance in which situations? ``` Parse(...) // Crash if the case is extremely rare .0001% If (SomethingIsValid) // Check the value before parsing Parse(...) TryParse(...) // Using TryParse try { Parse(...) } catch { // Catch any thrown exceptions } ```
Always use **T.TryParse(string str, out T value)**. Throwing exceptions is expensive and should be avoided if you can handle the situation *a priori*. Using a try-catch block to "save" on performance (because your invalid data rate is low) is an abuse of exception handling at the expense of maintainability and good coding practices. Follow sound software engineering development practices, write your test cases, run your application, THEN benchmark and optimize. > > "We should forget about small efficiencies, say about 97% of the time: **premature optimization is the root of all evil**. Yet we should not pass up our opportunities in that critical 3%" -Donald Knuth > > > Therefore you assign, arbitrarily like in carbon credits, that the performance of try-catch is *worse* and that the performance of TryParse is *better*. Only after we've run our application and determined that we have some sort of slowdown w.r.t. string parsing would we even consider using anything other than TryParse. *(edit: since it appears the questioner wanted timing data to go with good advice, here is the timing data requested)* Times for various failure rates on 10,000 inputs from the user (for the unbelievers): ``` Failure Rate Try-Catch TryParse Slowdown 0% 00:00:00.0131758 00:00:00.0120421 0.1 10% 00:00:00.1540251 00:00:00.0087699 16.6 20% 00:00:00.2833266 00:00:00.0105229 25.9 30% 00:00:00.4462866 00:00:00.0091487 47.8 40% 00:00:00.6951060 00:00:00.0108980 62.8 50% 00:00:00.7567745 00:00:00.0087065 85.9 60% 00:00:00.7090449 00:00:00.0083365 84.1 70% 00:00:00.8179365 00:00:00.0088809 91.1 80% 00:00:00.9468898 00:00:00.0088562 105.9 90% 00:00:01.0411393 00:00:00.0081040 127.5 100% 00:00:01.1488157 00:00:00.0078877 144.6 /// <param name="errorRate">Rate of errors in user input</param> /// <returns>Total time taken</returns> public static TimeSpan TimeTryCatch(double errorRate, int seed, int count) { Stopwatch stopwatch = new Stopwatch(); Random random = new Random(seed); string bad_prefix = @"X"; stopwatch.Start(); for(int ii = 0; ii < count; ++ii) { string input = random.Next().ToString(); if (random.NextDouble() < errorRate) { input = bad_prefix + input; } int value = 0; try { value = Int32.Parse(input); } catch(FormatException) { value = -1; // we would do something here with a logger perhaps } } stopwatch.Stop(); return stopwatch.Elapsed; } /// <param name="errorRate">Rate of errors in user input</param> /// <returns>Total time taken</returns> public static TimeSpan TimeTryParse(double errorRate, int seed, int count) { Stopwatch stopwatch = new Stopwatch(); Random random = new Random(seed); string bad_prefix = @"X"; stopwatch.Start(); for(int ii = 0; ii < count; ++ii) { string input = random.Next().ToString(); if (random.NextDouble() < errorRate) { input = bad_prefix + input; } int value = 0; if (!Int32.TryParse(input, out value)) { value = -1; // we would do something here with a logger perhaps } } stopwatch.Stop(); return stopwatch.Elapsed; } public static void TimeStringParse() { double errorRate = 0.1; // 10% of the time our users mess up int count = 10000; // 10000 entries by a user TimeSpan trycatch = TimeTryCatch(errorRate, 1, count); TimeSpan tryparse = TimeTryParse(errorRate, 1, count); Console.WriteLine("trycatch: {0}", trycatch); Console.WriteLine("tryparse: {0}", tryparse); } ```
150,146
<p>In my just-completed project, I was working getting distributed transactions working.</p> <p>We implemented this using JBoss's Arjuna Transaction Manager, and Spring's declarative transaction boundaries.</p> <p>Our request sequence looked like:</p> <pre><code>browser -&gt; secured servlet -&gt; 'wafer-thin' SLSB -&gt; spring TX-aware proxy -&gt; request-handler POJO </code></pre> <p>What this meant is that we had a WAR to serve our secured servlet and an EAR to serve our SLSB.</p> <p>Our SLSB had a static initialiser block to bootstrap our Spring application context.</p> <p>I don't like the mix of technologies, but I do like the separation of presentation and business tiers, which could reside on different physical locations.</p> <p>I would be interested to know what others propose to separate tiers when using Spring?</p>
[ { "answer_id": 150526, "author": "Michael Brown", "author_id": 14359, "author_profile": "https://Stackoverflow.com/users/14359", "pm_score": 1, "selected": false, "text": "<p>Jeremiah Morrill has recently released a <a href=\"http://www.codeplex.com/WPFMediaKit\" rel=\"nofollow noreferre...
2008/09/29
[ "https://Stackoverflow.com/questions/150146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3295/" ]
In my just-completed project, I was working getting distributed transactions working. We implemented this using JBoss's Arjuna Transaction Manager, and Spring's declarative transaction boundaries. Our request sequence looked like: ``` browser -> secured servlet -> 'wafer-thin' SLSB -> spring TX-aware proxy -> request-handler POJO ``` What this meant is that we had a WAR to serve our secured servlet and an EAR to serve our SLSB. Our SLSB had a static initialiser block to bootstrap our Spring application context. I don't like the mix of technologies, but I do like the separation of presentation and business tiers, which could reside on different physical locations. I would be interested to know what others propose to separate tiers when using Spring?
Jeremiah Morrill has recently released a [specialized WPF library](http://www.codeplex.com/WPFMediaKit) that supports displaying HD Media (among other features)
150,150
<p>I have a defined MenuItem that I would like to share between two different menus on one page. The menu contains functionallity that is the same between both menus and I do not want two copies of it. Is there anyway to define a MenuItem in the Page.Resources and reference it in the ContextMenu XAML below?</p> <pre><code>&lt;Page.Resources&gt; &lt;MenuItem x:Key="123"/&gt; &lt;/Page.Resources&gt; &lt;ContextMenu&gt; &lt;MenuItem&gt;Something hardcoded&lt;/MenuItem&gt; &lt;!-- include shared menu here --&gt; &lt;/ContextMenu&gt; </code></pre>
[ { "answer_id": 150203, "author": "Phobis", "author_id": 19854, "author_profile": "https://Stackoverflow.com/users/19854", "pm_score": 1, "selected": false, "text": "<p>Because you want to mix-and-match... I would make a custom control that inherits from ContextMenu that has a \"SharedMen...
2008/09/29
[ "https://Stackoverflow.com/questions/150150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1514/" ]
I have a defined MenuItem that I would like to share between two different menus on one page. The menu contains functionallity that is the same between both menus and I do not want two copies of it. Is there anyway to define a MenuItem in the Page.Resources and reference it in the ContextMenu XAML below? ``` <Page.Resources> <MenuItem x:Key="123"/> </Page.Resources> <ContextMenu> <MenuItem>Something hardcoded</MenuItem> <!-- include shared menu here --> </ContextMenu> ```
I've done this by setting x:Shared="False" on the menu item itself. Resources are shared between each place that uses them by default (meaning one instance across all uses), so turning that off means that a new "copy" of the resource is made each time. So: ``` <MenuItem x:Key="myMenuItem" x:Shared="False" /> ``` You'll still get a "copy" of it, but you only need to define it in one place. See if that helps. You use it like this within your menu definition: ``` <StaticResource ResourceKey="myMenuItem" /> ```
150,161
<p>I have searched but apparently my google foo is weak. What I need is a way to prompt for user input in the console and have the request time out after a period of time and continue executing the script if no input comes in. As near as I can tell, Read-Host does not provide this functionality. Neither does $host.UI.PromptForChoice() nor does $host.UI.RawUI.ReadKey(). Thanks in advance for any pointers.</p> <p>EDIT: Much thanks to Lars Truijens for finding the answer. I have taken the code that he pointed out and encapsulated it into a function. Note that the way that I have implemented it means there could be up to one second of delay between when the user hits a key and when script execution continues.</p> <pre><code>function Pause-Host { param( $Delay = 1 ) $counter = 0; While(!$host.UI.RawUI.KeyAvailable -and ($counter++ -lt $Delay)) { [Threading.Thread]::Sleep(1000) } } </code></pre>
[ { "answer_id": 150326, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 5, "selected": true, "text": "<p>Found something <a href=\"http://huddledmasses.org/powershell-xmpp-jabber-snapin/\" rel=\"noreferrer\">here</a>:</p>...
2008/09/29
[ "https://Stackoverflow.com/questions/150161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1358/" ]
I have searched but apparently my google foo is weak. What I need is a way to prompt for user input in the console and have the request time out after a period of time and continue executing the script if no input comes in. As near as I can tell, Read-Host does not provide this functionality. Neither does $host.UI.PromptForChoice() nor does $host.UI.RawUI.ReadKey(). Thanks in advance for any pointers. EDIT: Much thanks to Lars Truijens for finding the answer. I have taken the code that he pointed out and encapsulated it into a function. Note that the way that I have implemented it means there could be up to one second of delay between when the user hits a key and when script execution continues. ``` function Pause-Host { param( $Delay = 1 ) $counter = 0; While(!$host.UI.RawUI.KeyAvailable -and ($counter++ -lt $Delay)) { [Threading.Thread]::Sleep(1000) } } ```
Found something [here](http://huddledmasses.org/powershell-xmpp-jabber-snapin/): ``` $counter = 0 while(!$Host.UI.RawUI.KeyAvailable -and ($counter++ -lt 600)) { [Threading.Thread]::Sleep( 1000 ) } ```
150,167
<p>How do I list and export a private key from a keystore?</p>
[ { "answer_id": 150181, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 6, "selected": true, "text": "<p>A portion of code originally from Example Depot for listing all of the aliases in a key store:</p>\n\n<pre><code> // Lo...
2008/09/29
[ "https://Stackoverflow.com/questions/150167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ]
How do I list and export a private key from a keystore?
A portion of code originally from Example Depot for listing all of the aliases in a key store: ``` // Load input stream into keystore keystore.load(is, password.toCharArray()); // List the aliases Enumeration aliases = keystore.aliases(); for (; aliases.hasMoreElements(); ) { String alias = (String)aliases.nextElement(); // Does alias refer to a private key? boolean b = keystore.isKeyEntry(alias); // Does alias refer to a trusted certificate? b = keystore.isCertificateEntry(alias); } ``` The exporting of private keys came up on the [Sun forums](http://forums.sun.com/thread.jspa?threadID=154587&start=15&tstart=0) a couple of months ago, and [u:turingcompleter](http://forums.sun.com/profile.jspa?userID=505275) came up with a DumpPrivateKey class to stitch into your app. ``` import java.io.FileInputStream; import java.security.Key; import java.security.KeyStore; import sun.misc.BASE64Encoder; public class DumpPrivateKey { /** * Provides the missing functionality of keytool * that Apache needs for SSLCertificateKeyFile. * * @param args <ul> * <li> [0] Keystore filename. * <li> [1] Keystore password. * <li> [2] alias * </ul> */ static public void main(String[] args) throws Exception { if(args.length < 3) { throw new IllegalArgumentException("expected args: Keystore filename, Keystore password, alias, <key password: default same tha n keystore"); } final String keystoreName = args[0]; final String keystorePassword = args[1]; final String alias = args[2]; final String keyPassword = getKeyPassword(args,keystorePassword); KeyStore ks = KeyStore.getInstance("jks"); ks.load(new FileInputStream(keystoreName), keystorePassword.toCharArray()); Key key = ks.getKey(alias, keyPassword.toCharArray()); String b64 = new BASE64Encoder().encode(key.getEncoded()); System.out.println("-----BEGIN PRIVATE KEY-----"); System.out.println(b64); System.out.println("-----END PRIVATE KEY-----"); } private static String getKeyPassword(final String[] args, final String keystorePassword) { String keyPassword = keystorePassword; // default case if(args.length == 4) { keyPassword = args[3]; } return keyPassword; } } ``` Note: this use Sun package, [which is a "bad thing"](http://java.sun.com/products/jdk/faq/faq-sun-packages.html). If you can download [apache commons code](http://commons.apache.org/codec/index.html), here is a version which will compile without warning: ``` javac -classpath .:commons-codec-1.4/commons-codec-1.4.jar DumpPrivateKey.java ``` and will give the same result: ``` import java.io.FileInputStream; import java.security.Key; import java.security.KeyStore; //import sun.misc.BASE64Encoder; import org.apache.commons.codec.binary.Base64; public class DumpPrivateKey { /** * Provides the missing functionality of keytool * that Apache needs for SSLCertificateKeyFile. * * @param args <ul> * <li> [0] Keystore filename. * <li> [1] Keystore password. * <li> [2] alias * </ul> */ static public void main(String[] args) throws Exception { if(args.length < 3) { throw new IllegalArgumentException("expected args: Keystore filename, Keystore password, alias, <key password: default same tha n keystore"); } final String keystoreName = args[0]; final String keystorePassword = args[1]; final String alias = args[2]; final String keyPassword = getKeyPassword(args,keystorePassword); KeyStore ks = KeyStore.getInstance("jks"); ks.load(new FileInputStream(keystoreName), keystorePassword.toCharArray()); Key key = ks.getKey(alias, keyPassword.toCharArray()); //String b64 = new BASE64Encoder().encode(key.getEncoded()); String b64 = new String(Base64.encodeBase64(key.getEncoded(),true)); System.out.println("-----BEGIN PRIVATE KEY-----"); System.out.println(b64); System.out.println("-----END PRIVATE KEY-----"); } private static String getKeyPassword(final String[] args, final String keystorePassword) { String keyPassword = keystorePassword; // default case if(args.length == 4) { keyPassword = args[3]; } return keyPassword; } } ``` You can use it like so: ``` java -classpath .:commons-codec-1.4/commons-codec-1.4.jar DumpPrivateKey $HOME/.keystore changeit tomcat ```
150,177
<p>I was helping out some colleagues of mine with an SQL problem. Mainly they wanted to move all the rows from table A to table B (both tables having the same columns (names and types)). Although this was done in Oracle 11g I don't think it really matters.</p> <p>Their initial naive implementation was something like </p> <pre><code>BEGIN INSERT INTO B SELECT * FROM A DELETE FROM A COMMIT; END </code></pre> <p>Their concern was if there were INSERTs made to table A during copying from A to B and the "DELETE FROM A" (or TRUNCATE for what was worth) would cause data loss (having the newer inserted rows in A deleted).</p> <p>Ofcourse I quickly recommended storing the IDs of the copied rows in a temporary table and then deleting just the rows in A that matched the IDS in the temporary table.</p> <p>However for curiosity's sake we put up a little test by adding a wait command (don't remember the PL/SQL syntax) between INSERT and DELETE. THen from a different connection we would insert rows <em>DURING THE WAIT</em>.</p> <p>We observed that was a data loss by doing so. I reproduced the whole context in SQL Server and wrapped it all in a transaction but still the fresh new data was lost too in SQL Server. This made me think there is a systematic error/flaw in the initial approach.</p> <p>However I can't tell if it was the fact that the TRANSACTION was not (somehow?) isolated from the fresh new INSERTs or the fact that the INSERTs came during the WAIT command.</p> <p>In the end it was implemented using the temporary table suggested by me but we couldn't get the answer to "Why the data loss". Do you know why?</p>
[ { "answer_id": 150187, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 1, "selected": false, "text": "<p>i don't know if this is relevant, but in SQL Server the syntax is</p>\n\n<pre><code>begin tran\n....\ncommit\n</co...
2008/09/29
[ "https://Stackoverflow.com/questions/150177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1796/" ]
I was helping out some colleagues of mine with an SQL problem. Mainly they wanted to move all the rows from table A to table B (both tables having the same columns (names and types)). Although this was done in Oracle 11g I don't think it really matters. Their initial naive implementation was something like ``` BEGIN INSERT INTO B SELECT * FROM A DELETE FROM A COMMIT; END ``` Their concern was if there were INSERTs made to table A during copying from A to B and the "DELETE FROM A" (or TRUNCATE for what was worth) would cause data loss (having the newer inserted rows in A deleted). Ofcourse I quickly recommended storing the IDs of the copied rows in a temporary table and then deleting just the rows in A that matched the IDS in the temporary table. However for curiosity's sake we put up a little test by adding a wait command (don't remember the PL/SQL syntax) between INSERT and DELETE. THen from a different connection we would insert rows *DURING THE WAIT*. We observed that was a data loss by doing so. I reproduced the whole context in SQL Server and wrapped it all in a transaction but still the fresh new data was lost too in SQL Server. This made me think there is a systematic error/flaw in the initial approach. However I can't tell if it was the fact that the TRANSACTION was not (somehow?) isolated from the fresh new INSERTs or the fact that the INSERTs came during the WAIT command. In the end it was implemented using the temporary table suggested by me but we couldn't get the answer to "Why the data loss". Do you know why?
Depending on your isolation level, selecting all the rows from a table does not prevent new inserts, it will just lock the rows you read. In SQL Server, if you use the Serializable isolation level then it will prevent new rows if they would have been including in your select query. <http://msdn.microsoft.com/en-us/library/ms173763.aspx> - SERIALIZABLE Specifies the following: * Statements cannot read data that has been modified but not yet committed by other transactions. * No other transactions can modify data that has been read by the current transaction until the current transaction completes. * **Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.**
150,186
<p>I'm trying to build a new .NET C++ project from scratch. I am planning to mix managed and unmanaged code in this project.</p> <p>this forum thread <a href="http://www.daniweb.com/forums/thread29742.html" rel="nofollow noreferrer">IDataObject : ambiguous symbol error</a> answers a problem I've seen multiple times.</p> <p>Post #4 states "Move all 'using namespace XXXX' from .h to .cpp"</p> <p>this looks like a good idea but now in my header files I need to reference parameters from the .NET Framework like</p> <pre><code>void loadConfigurations(String^ pPathname); </code></pre> <p>How am I supposed to move using statements in the .cpp file and use the according namespaces in the .h file?</p>
[ { "answer_id": 150236, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 0, "selected": false, "text": "<p>I don't know much about .NET, so my answer only applies to the unmanaged c++ part of your question. Personally, this...
2008/09/29
[ "https://Stackoverflow.com/questions/150186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6367/" ]
I'm trying to build a new .NET C++ project from scratch. I am planning to mix managed and unmanaged code in this project. this forum thread [IDataObject : ambiguous symbol error](http://www.daniweb.com/forums/thread29742.html) answers a problem I've seen multiple times. Post #4 states "Move all 'using namespace XXXX' from .h to .cpp" this looks like a good idea but now in my header files I need to reference parameters from the .NET Framework like ``` void loadConfigurations(String^ pPathname); ``` How am I supposed to move using statements in the .cpp file and use the according namespaces in the .h file?
It's a good idea to always use fully qualified names in header files. Because the `using` statement affects all following code regardless of `#include`, putting a `using` statement in a header file affects everybody that might include that header. So you would change your function declaration in your header file to: ``` void loadConfigurations(SomeNamespace::String^ pPathname); ``` where SomeNamespace is the name of the namespace you were `using` previously.
150,208
<p>Is there a free third-party or .NET class that will convert HTML to RTF (for use in a rich-text enabled Windows Forms control)?</p> <p>The "free" requirement comes from the fact that I'm only working on a prototype and can just load the BrowserControl and just render HTML if need be (even if it is slow) and that Developer Express is going to be releasing their own such control soon-ish.</p> <p>I don't want to learn to write RTF by hand, and I already know HTML, so I figure this is the quickest way to get some demonstrable code out the door quickly.</p>
[ { "answer_id": 152182, "author": "GvS", "author_id": 11492, "author_profile": "https://Stackoverflow.com/users/11492", "pm_score": 1, "selected": false, "text": "<p>Maybe what you need is <a href=\"http://www.codeplex.com/WinformHtmlTextbox\" rel=\"nofollow noreferrer\">a control to edit...
2008/09/29
[ "https://Stackoverflow.com/questions/150208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/549/" ]
Is there a free third-party or .NET class that will convert HTML to RTF (for use in a rich-text enabled Windows Forms control)? The "free" requirement comes from the fact that I'm only working on a prototype and can just load the BrowserControl and just render HTML if need be (even if it is slow) and that Developer Express is going to be releasing their own such control soon-ish. I don't want to learn to write RTF by hand, and I already know HTML, so I figure this is the quickest way to get some demonstrable code out the door quickly.
Actually there is a simple and **free** solution: use your browser, ok this is the trick I used: ``` var webBrowser = new WebBrowser(); webBrowser.CreateControl(); // only if needed webBrowser.DocumentText = *yourhtmlstring*; while (_webBrowser.DocumentText != *yourhtmlstring*) Application.DoEvents(); webBrowser.Document.ExecCommand("SelectAll", false, null); webBrowser.Document.ExecCommand("Copy", false, null); *yourRichTextControl*.Paste(); ``` This could be slower than other methods but at least it's free and works!
150,213
<p>I'm trying to chart the number of registrations per day in our registration system. I have an Attendee table in sql server that has a smalldatetime field A_DT, which is the date and time the person registered.</p> <p>I started with this:</p> <pre><code>var dailyCountList = (from a in showDC.Attendee let justDate = new DateTime(a.A_DT.Year, a.A_DT.Month, a.A_DT.Day) group a by justDate into DateGroup orderby DateGroup.Key select new RegistrationCount { EventDateTime = DateGroup.Key, Count = DateGroup.Count() }).ToList(); </code></pre> <p>That works great, but it won't include the dates where there were no registrations, because there are no attendee records for those dates. I want every date to be included, and when there is no data for a given date, the count should just be zero.</p> <p>So this is my current working solution, but I KNOW THAT IT IS TERRIBLE. I added the following to the code above:</p> <pre><code>// Create a new list of data ranging from the beginning to the end of the first list, specifying 0 counts for missing data points (days with no registrations) var allDates = new List&lt;RegistrationCount&gt;(); for (DateTime date = (from dcl in dailyCountList select dcl).First().EventDateTime; date &lt;= (from dcl in dailyCountList select dcl).Last().EventDateTime; date = date.AddDays(1)) { DateTime thisDate = date; // lexical closure issue - see: http://www.managed-world.com/2008/06/13/LambdasKnowYourClosures.aspx allDates.Add(new RegistrationCount { EventDateTime = date, Count = (from dclInner in dailyCountList where dclInner.EventDateTime == thisDate select dclInner).DefaultIfEmpty(new RegistrationCount { EventDateTime = date, Count = 0 }).Single().Count }); } </code></pre> <p>So I created ANOTHER list, and loop through a sequence of dates I generate based on the first and last registrations in the query, and for each item in the sequence of dates, I QUERY the results of my first QUERY for the information regarding the given date, and supply a default if nothing comes back. So I end up doing a subquery here and I want to avoid this.</p> <p>Can anyone thing of an elegant solution? Or at least one that is less embarrassing?</p>
[ { "answer_id": 150334, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": true, "text": "<p>O(n) with 2 enumerations. It's very good to pull the items into memory before trying this. Database has enough to do witho...
2008/09/29
[ "https://Stackoverflow.com/questions/150213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13700/" ]
I'm trying to chart the number of registrations per day in our registration system. I have an Attendee table in sql server that has a smalldatetime field A\_DT, which is the date and time the person registered. I started with this: ``` var dailyCountList = (from a in showDC.Attendee let justDate = new DateTime(a.A_DT.Year, a.A_DT.Month, a.A_DT.Day) group a by justDate into DateGroup orderby DateGroup.Key select new RegistrationCount { EventDateTime = DateGroup.Key, Count = DateGroup.Count() }).ToList(); ``` That works great, but it won't include the dates where there were no registrations, because there are no attendee records for those dates. I want every date to be included, and when there is no data for a given date, the count should just be zero. So this is my current working solution, but I KNOW THAT IT IS TERRIBLE. I added the following to the code above: ``` // Create a new list of data ranging from the beginning to the end of the first list, specifying 0 counts for missing data points (days with no registrations) var allDates = new List<RegistrationCount>(); for (DateTime date = (from dcl in dailyCountList select dcl).First().EventDateTime; date <= (from dcl in dailyCountList select dcl).Last().EventDateTime; date = date.AddDays(1)) { DateTime thisDate = date; // lexical closure issue - see: http://www.managed-world.com/2008/06/13/LambdasKnowYourClosures.aspx allDates.Add(new RegistrationCount { EventDateTime = date, Count = (from dclInner in dailyCountList where dclInner.EventDateTime == thisDate select dclInner).DefaultIfEmpty(new RegistrationCount { EventDateTime = date, Count = 0 }).Single().Count }); } ``` So I created ANOTHER list, and loop through a sequence of dates I generate based on the first and last registrations in the query, and for each item in the sequence of dates, I QUERY the results of my first QUERY for the information regarding the given date, and supply a default if nothing comes back. So I end up doing a subquery here and I want to avoid this. Can anyone thing of an elegant solution? Or at least one that is less embarrassing?
O(n) with 2 enumerations. It's very good to pull the items into memory before trying this. Database has enough to do without thinking about this stuff. ``` if (!dailyCountList.Any()) return; //make a dictionary to provide O(1) lookups for later Dictionary<DateTime, RegistrationCount> lookup = dailyCountList.ToDictionary(r => r.EventDateTime); DateTime minDate = dailyCountList[0].EventDateTime; DateTime maxDate = dailyCountList[dailyCountList.Count - 1].EventDateTime; int DayCount = 1 + (int) (maxDate - minDate).TotalDays; // I have the days now. IEnumerable<DateTime> allDates = Enumerable .Range(0, DayCount) .Select(x => minDate.AddDays(x)); //project the days into RegistrationCounts, making up the missing ones. List<RegistrationCount> result = allDates .Select(d => lookup.ContainsKey(d) ? lookup[d] : new RegistrationCount(){EventDateTime = d, Count = 0}) .ToList(); ```
150,223
<p>Looking for a way to programatically, or otherwise, add a new instance of SQL 2005 Express Edition to a system that already has an instance installed. Traditionally, you run Micrsoft's installer like I am in the command line below and it does the trick. Executing the command in my installer is not the issue, it's more a matter of dragging around the 40 MBs of MS-SQL installer that I don't need if they have SQL Express already installed. This is what my installer currently executes:</p> <pre><code>SQLEXPR32.EXE /qb ADDLOCAL=ALL INSTANCENAME=&lt;instancename&gt; SECURITYMODE=SQL SAPWD=&lt;password&gt; SQLAUTOSTART=1 DISABLENETWORKPROTOCOLS=0 </code></pre> <p>I don't need assistance with launching this command, rather the appropriate way to add a new instance of SQL 2005 Express without actually running the full installer again. </p> <p>I'd go into great detail about why I want to do this but I'd simply bore everyone. Suffice to say, having this ability to create a new instance without the time it takes to reinstall SQL Express etc. would greatly assist me for the deployment of my application and it's installer. If makes any difference to anyone, I'm using a combination of NSIS and Advanced Installer for this installation project.</p>
[ { "answer_id": 150247, "author": "Scott Isaacs", "author_id": 1664, "author_profile": "https://Stackoverflow.com/users/1664", "pm_score": 0, "selected": false, "text": "<p>I do not know how to do it with an API, but if no one gives a better solution, you can always use Process.Start() to...
2008/09/29
[ "https://Stackoverflow.com/questions/150223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5678/" ]
Looking for a way to programatically, or otherwise, add a new instance of SQL 2005 Express Edition to a system that already has an instance installed. Traditionally, you run Micrsoft's installer like I am in the command line below and it does the trick. Executing the command in my installer is not the issue, it's more a matter of dragging around the 40 MBs of MS-SQL installer that I don't need if they have SQL Express already installed. This is what my installer currently executes: ``` SQLEXPR32.EXE /qb ADDLOCAL=ALL INSTANCENAME=<instancename> SECURITYMODE=SQL SAPWD=<password> SQLAUTOSTART=1 DISABLENETWORKPROTOCOLS=0 ``` I don't need assistance with launching this command, rather the appropriate way to add a new instance of SQL 2005 Express without actually running the full installer again. I'd go into great detail about why I want to do this but I'd simply bore everyone. Suffice to say, having this ability to create a new instance without the time it takes to reinstall SQL Express etc. would greatly assist me for the deployment of my application and it's installer. If makes any difference to anyone, I'm using a combination of NSIS and Advanced Installer for this installation project.
After months/years of looking into this it appears it can't be done. Oh well, I guess I just reinstall each time I want a new instance. I guess it's because each instance is it's own service.
150,250
<p>I was recently tasked with debugging a strange problem within an e-commerce application. After an application upgrade the site started to hang from time to time and I was sent in to debug. After checking the event log I found that the SQL-server wrote ~200 000 events in a couple of minutes with the message saying that a constraint had failed. After much debugging and some tracing I found the culprit. I've removed some unnecessary code and cleaned it up a bit but essentially this is it</p> <pre><code>WHILE EXISTS (SELECT * FROM ShoppingCartItem WHERE ShoppingCartItem.PurchID = @PurchID) BEGIN SELECT TOP 1 @TmpGFSID = ShoppingCartItem.GFSID, @TmpQuantity = ShoppingCartItem.Quantity, @TmpShoppingCartItemID = ShoppingCartItem.ShoppingCartItemID, FROM ShoppingCartItem INNER JOIN GoodsForSale on ShoppingCartItem.GFSID = GoodsForSale.GFSID WHERE ShoppingCartItem.PurchID = @PurchID EXEC @ErrorCode = spGoodsForSale_ReverseReservations @TmpGFSID, @TmpQuantity IF @ErrorCode &lt;&gt; 0 BEGIN Goto Cleanup END DELETE FROM ShoppingCartItem WHERE ShoppingCartItem.ShoppingCartItemID = @TmpShoppingCartItemID -- @@ROWCOUNT is 1 after this END </code></pre> <p>Facts:</p> <ol> <li>There's only one or two records matching the first select-clause</li> <li>RowCount from the DELETE statement indicates that it has been removed</li> <li>The WHILE-clause will loop forever</li> </ol> <p>The procedure has been rewritten to select the rows that should be deleted into a temporary in-memory table instead so the immediate problem is solved but this really sparked my curiosity.</p> <p>Why does it loop forever?</p> <p><strong>Clarification</strong>: The delete doesn't fail (@@rowcount is 1 after the delete stmt when debugged) <strong>Clarification 2</strong>: It shouldn't matter whether or not the SELECT TOP ... clause is ordered by any specific field since the record with the returned id will be deleted so in the next loop it should get another record.</p> <p><strong>Update</strong>: After checking the subversion logs I found the culprit commit that made this stored procedure to go haywire. The only real difference that I can find is that there previously was no join in the SELECT TOP 1 statement i.e. without that join it worked without any transaction statements surrounding the delete. It appears to be the introduction of the join that made SQL server more picky.</p> <p><strong>Update clarification</strong>: <a href="https://stackoverflow.com/questions/150250/while-clause-in-t-sql-that-loops-forever#150400">brien</a> pointed out that there's no need for the join but we actually do use some fields from the GoodsForSale table but I've removed them to keep the code simply so that we can concentrate on the problem at hand</p>
[ { "answer_id": 150267, "author": "Alex Fort", "author_id": 12624, "author_profile": "https://Stackoverflow.com/users/12624", "pm_score": 0, "selected": false, "text": "<p>Obviously, something is not being deleted or modified where it should. If the condition is still the same on the next...
2008/09/29
[ "https://Stackoverflow.com/questions/150250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2114/" ]
I was recently tasked with debugging a strange problem within an e-commerce application. After an application upgrade the site started to hang from time to time and I was sent in to debug. After checking the event log I found that the SQL-server wrote ~200 000 events in a couple of minutes with the message saying that a constraint had failed. After much debugging and some tracing I found the culprit. I've removed some unnecessary code and cleaned it up a bit but essentially this is it ``` WHILE EXISTS (SELECT * FROM ShoppingCartItem WHERE ShoppingCartItem.PurchID = @PurchID) BEGIN SELECT TOP 1 @TmpGFSID = ShoppingCartItem.GFSID, @TmpQuantity = ShoppingCartItem.Quantity, @TmpShoppingCartItemID = ShoppingCartItem.ShoppingCartItemID, FROM ShoppingCartItem INNER JOIN GoodsForSale on ShoppingCartItem.GFSID = GoodsForSale.GFSID WHERE ShoppingCartItem.PurchID = @PurchID EXEC @ErrorCode = spGoodsForSale_ReverseReservations @TmpGFSID, @TmpQuantity IF @ErrorCode <> 0 BEGIN Goto Cleanup END DELETE FROM ShoppingCartItem WHERE ShoppingCartItem.ShoppingCartItemID = @TmpShoppingCartItemID -- @@ROWCOUNT is 1 after this END ``` Facts: 1. There's only one or two records matching the first select-clause 2. RowCount from the DELETE statement indicates that it has been removed 3. The WHILE-clause will loop forever The procedure has been rewritten to select the rows that should be deleted into a temporary in-memory table instead so the immediate problem is solved but this really sparked my curiosity. Why does it loop forever? **Clarification**: The delete doesn't fail (@@rowcount is 1 after the delete stmt when debugged) **Clarification 2**: It shouldn't matter whether or not the SELECT TOP ... clause is ordered by any specific field since the record with the returned id will be deleted so in the next loop it should get another record. **Update**: After checking the subversion logs I found the culprit commit that made this stored procedure to go haywire. The only real difference that I can find is that there previously was no join in the SELECT TOP 1 statement i.e. without that join it worked without any transaction statements surrounding the delete. It appears to be the introduction of the join that made SQL server more picky. **Update clarification**: [brien](https://stackoverflow.com/questions/150250/while-clause-in-t-sql-that-loops-forever#150400) pointed out that there's no need for the join but we actually do use some fields from the GoodsForSale table but I've removed them to keep the code simply so that we can concentrate on the problem at hand
Are you operating in explicit or implicit [transaction mode](http://doc.ddart.net/mssql/sql70/ta-tz_8.htm)? Since you're in explicit mode, I think you need to surround the DELETE operation with BEGIN TRANSACTION and COMMIT TRANSACTION statements. ``` WHILE EXISTS (SELECT * FROM ShoppingCartItem WHERE ShoppingCartItem.PurchID = @PurchID) BEGIN SELECT TOP 1 @TmpGFSID = ShoppingCartItem.GFSID, @TmpQuantity = ShoppingCartItem.Quantity, @TmpShoppingCartItemID = ShoppingCartItem.ShoppingCartItemID, FROM ShoppingCartItem INNER JOIN GoodsForSale on ShoppingCartItem.GFSID = GoodsForSale.GFSID WHERE ShoppingCartItem.PurchID = @PurchID EXEC @ErrorCode = spGoodsForSale_ReverseReservations @TmpGFSID, @TmpQuantity IF @ErrorCode <> 0 BEGIN Goto Cleanup END BEGIN TRANSACTION delete DELETE FROM ShoppingCartItem WHERE ShoppingCartItem.ShoppingCartItemID = @TmpShoppingCartItemID -- @@ROWCOUNT is 1 after this COMMIT TRANSACTION delete END ``` **Clarification:** The reason you'd need to use transactions is that the delete doesn't actually happen in the database until you do a COMMIT operation. This is generally used when you have multiple write operations in an atomic transaction. Basically, you only want the changes to happen to the DB if all of the operations are successful. In your case, there's only 1 operation, but since you're in explicit transaction mode, you need to tell SQL Server to **really** make the changes.
150,329
<p>I recently migrated a website to a new CMS (Umbraco). A lot of the links have changed, but they can be easily corrected by searching for patters in the url, so I would like to write something that will redirect to the correct page if the old one is not found. That part isn't a problem. </p> <p>How can I obtain the requested URL after the browser is redirected to my custom 404 page. I tried using:</p> <pre><code>request.ServerVariables("HTTP_REFERER") 'sorry i corrected the typo from system to server. </code></pre> <p>But that didn't work.</p> <p>Any Ideas?</p> <p>The site is on IIS 6.0. We did consider using 301 redirects, but we don't have any way of knowing what pages people have bookmarked and there are a few hundred pages, so no one is keen on spending the time to create the 301's.</p>
[ { "answer_id": 150336, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 0, "selected": false, "text": "<p>Update, you actually want to pick up:</p>\n\n<p>VB.NET:</p>\n\n<pre><code>Request.QueryString(\"aspxerrorpath\")\n</code></pre>...
2008/09/29
[ "https://Stackoverflow.com/questions/150329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20483/" ]
I recently migrated a website to a new CMS (Umbraco). A lot of the links have changed, but they can be easily corrected by searching for patters in the url, so I would like to write something that will redirect to the correct page if the old one is not found. That part isn't a problem. How can I obtain the requested URL after the browser is redirected to my custom 404 page. I tried using: ``` request.ServerVariables("HTTP_REFERER") 'sorry i corrected the typo from system to server. ``` But that didn't work. Any Ideas? The site is on IIS 6.0. We did consider using 301 redirects, but we don't have any way of knowing what pages people have bookmarked and there are a few hundred pages, so no one is keen on spending the time to create the 301's.
I do basically the same thing you ask in a custom 404 error handling page. On IIS 6 the original URL is in the query string. The code below shows how to grab the original URL and then forward the user. In my case I switched from old ASP to new ASP.NET, so all the .asp pages had to be forwarded to .aspx pages. Also, some URLs changed so I look for keywords in the old URL and forward. ``` //did the error go to a .ASP page? If so, append x (for .aspx) and //issue a 301 permanently moved //when we get an error, the querystring will be "404;<complete original URL>" string targetPage = Request.RawUrl.Substring(Request.FilePath.Length); if((null == targetPage) || (targetPage.Length == 0)) targetPage = "[home page]"; else { //find the original URL if(targetPage[0] == '?') { if(-1 != targetPage.IndexOf("?aspxerrorpath=")) targetPage = targetPage.Substring(15); // ?aspxerrorpath= else targetPage = targetPage.Substring(5); // ?404; } else { if(-1 != targetPage.IndexOf("errorpath=")) targetPage = targetPage.Substring(14); // aspxerrorpath= else targetPage = targetPage.Substring(4); // 404; } } string upperTarget = targetPage.ToUpper(); if((-1 == upperTarget.IndexOf(".ASPX")) && (-1 != upperTarget.IndexOf(".ASP"))) { //this is a request for an .ASP page - permanently redirect to .aspx targetPage = upperTarget.Replace(".ASP", ".ASPX"); //issue 301 redirect Response.Status = "301 Moved Permanently"; Response.AddHeader("Location",targetPage); Response.End(); } if(-1 != upperTarget.IndexOf("ORDER")) { //going to old order page -- forward to new page Response.Redirect(WebRoot + "/order.aspx"); Response.End(); } ```
150,332
<p>If I have variable of type <code>IEnumerable&lt;List&lt;string&gt;&gt;</code> is there a LINQ statement or lambda expression I can apply to it which will combine the lists returning an <code>IEnumerable&lt;string&gt;</code>? </p>
[ { "answer_id": 150343, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": true, "text": "<p>SelectMany - i.e.</p>\n\n<pre><code> IEnumerable&lt;List&lt;string&gt;&gt; someList = ...;\n IEnumera...
2008/09/29
[ "https://Stackoverflow.com/questions/150332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If I have variable of type `IEnumerable<List<string>>` is there a LINQ statement or lambda expression I can apply to it which will combine the lists returning an `IEnumerable<string>`?
SelectMany - i.e. ``` IEnumerable<List<string>> someList = ...; IEnumerable<string> all = someList.SelectMany(x => x); ``` For each item in someList, this then uses the lambda "x => x" to get an IEnumerable<T> for the inner items. In this case, each "x" is a List<T>, which is already IEnumerable<T>. These are then returned as a contiguous block. Essentially, SelectMany is something like (simplified): ``` static IEnumerable<TResult> SelectMany<TSource, TResult>( this IEnumerable<TSource> source, Func<TSource, IEnumerable<TResult>> selector) { foreach(TSource item in source) { foreach(TResult result in selector(item)) { yield return result; } } } ``` Although that is simplified somewhat.
150,333
<p>We need to remotely create an Exchange 2007 distribution list from Asp.Net.</p> <p>Near as I can tell, the only way to create a distribution list in the GAL is via the exchange management tools. Without installing this on our web server, is there any way to create a distribution list remotely? There are some third party components that allow you to create personal distribution lists, but these only live in a users Contacts folder and are not available to all users within the company.</p> <p>Ideally there would be some kind of web services call to exchange or an API we could work with. The Exchange SDK provides the ability to managing Exchange data (e.g. emails, contacts, calendars etc.). There doesn't appear to be an Exchange management API.</p> <p>It looks like the distribution lists are stored in AD as group objects with a special Exchange attributes, but there doesn't seem to be any documentation on how they are supposed to work. </p> <p>Edit: We could reverse engineer what Exchange is doing with AD, but my concern is that with the next service pack of Exchange this will all break. </p> <p>Is there an API that I can use to manage the distribution lists in Active Directory without going through Exchange? </p>
[ { "answer_id": 150343, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": true, "text": "<p>SelectMany - i.e.</p>\n\n<pre><code> IEnumerable&lt;List&lt;string&gt;&gt; someList = ...;\n IEnumera...
2008/09/29
[ "https://Stackoverflow.com/questions/150333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23583/" ]
We need to remotely create an Exchange 2007 distribution list from Asp.Net. Near as I can tell, the only way to create a distribution list in the GAL is via the exchange management tools. Without installing this on our web server, is there any way to create a distribution list remotely? There are some third party components that allow you to create personal distribution lists, but these only live in a users Contacts folder and are not available to all users within the company. Ideally there would be some kind of web services call to exchange or an API we could work with. The Exchange SDK provides the ability to managing Exchange data (e.g. emails, contacts, calendars etc.). There doesn't appear to be an Exchange management API. It looks like the distribution lists are stored in AD as group objects with a special Exchange attributes, but there doesn't seem to be any documentation on how they are supposed to work. Edit: We could reverse engineer what Exchange is doing with AD, but my concern is that with the next service pack of Exchange this will all break. Is there an API that I can use to manage the distribution lists in Active Directory without going through Exchange?
SelectMany - i.e. ``` IEnumerable<List<string>> someList = ...; IEnumerable<string> all = someList.SelectMany(x => x); ``` For each item in someList, this then uses the lambda "x => x" to get an IEnumerable<T> for the inner items. In this case, each "x" is a List<T>, which is already IEnumerable<T>. These are then returned as a contiguous block. Essentially, SelectMany is something like (simplified): ``` static IEnumerable<TResult> SelectMany<TSource, TResult>( this IEnumerable<TSource> source, Func<TSource, IEnumerable<TResult>> selector) { foreach(TSource item in source) { foreach(TResult result in selector(item)) { yield return result; } } } ``` Although that is simplified somewhat.
150,341
<p>How do people approach mocking out TcpClient (or things like TcpClient)?</p> <p>I have a service that takes in a TcpClient. Should I wrap that in something else more mockable? How should I approach this?</p>
[ { "answer_id": 150480, "author": "Doron Yaacoby", "author_id": 3389, "author_profile": "https://Stackoverflow.com/users/3389", "pm_score": 6, "selected": true, "text": "<p>When coming to mock classes that are not test friendly (i.e. sealed/not implementing any interface/methods are not v...
2008/09/29
[ "https://Stackoverflow.com/questions/150341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3285/" ]
How do people approach mocking out TcpClient (or things like TcpClient)? I have a service that takes in a TcpClient. Should I wrap that in something else more mockable? How should I approach this?
When coming to mock classes that are not test friendly (i.e. sealed/not implementing any interface/methods are not virtual), you would probably want to use the [Adapter](http://en.wikipedia.org/wiki/Adapter_pattern) design pattern. In this pattern you add a wrapping class that implements an interface. You should then mock the interface, and make sure all your code uses that interface instead of the unfriendly concrete class. It would look something like this: ``` public interface ITcpClient { Stream GetStream(); // Anything you need here } public class TcpClientAdapter: ITcpClient { private TcpClient wrappedClient; public TcpClientAdapter(TcpClient client) { wrappedClient = client; } public Stream GetStream() { return wrappedClient.GetStream(); } } ```
150,355
<p>Is there a way to determine how many cores a machine has from C/C++ in a platform-independent way? If no such thing exists, what about determining it per-platform (Windows/*nix/Mac)?</p>
[ { "answer_id": 150369, "author": "Chris Ballance", "author_id": 1551, "author_profile": "https://Stackoverflow.com/users/1551", "pm_score": 2, "selected": false, "text": "<p>Windows Server 2003 and later lets you leverage the GetLogicalProcessorInformation function</p>\n\n<p><a href=\"ht...
2008/09/29
[ "https://Stackoverflow.com/questions/150355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5066/" ]
Is there a way to determine how many cores a machine has from C/C++ in a platform-independent way? If no such thing exists, what about determining it per-platform (Windows/\*nix/Mac)?
C++11 ===== ``` #include <thread> //may return 0 when not able to detect const auto processor_count = std::thread::hardware_concurrency(); ``` Reference: [std::thread::hardware\_concurrency](http://en.cppreference.com/w/cpp/thread/thread/hardware_concurrency) --- In C++ prior to C++11, there's no portable way. Instead, you'll need to use one or more of the following methods (guarded by appropriate `#ifdef` lines): * ### Win32 ``` SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); int numCPU = sysinfo.dwNumberOfProcessors; ``` * ### Linux, Solaris, AIX and Mac OS X >=10.4 (i.e. Tiger onwards) ``` int numCPU = sysconf(_SC_NPROCESSORS_ONLN); ``` * ### FreeBSD, MacOS X, NetBSD, OpenBSD, etc. ``` int mib[4]; int numCPU; std::size_t len = sizeof(numCPU); /* set the mib for hw.ncpu */ mib[0] = CTL_HW; mib[1] = HW_AVAILCPU; // alternatively, try HW_NCPU; /* get the number of CPUs from the system */ sysctl(mib, 2, &numCPU, &len, NULL, 0); if (numCPU < 1) { mib[1] = HW_NCPU; sysctl(mib, 2, &numCPU, &len, NULL, 0); if (numCPU < 1) numCPU = 1; } ``` * ### HPUX ``` int numCPU = mpctl(MPC_GETNUMSPUS, NULL, NULL); ``` * ### IRIX ``` int numCPU = sysconf(_SC_NPROC_ONLN); ``` * ### Objective-C (Mac OS X >=10.5 or iOS) ``` NSUInteger a = [[NSProcessInfo processInfo] processorCount]; NSUInteger b = [[NSProcessInfo processInfo] activeProcessorCount]; ```
150,375
<p>What do you insert into Python source code to have it break into pdb (when execution gets to that spot)? </p>
[ { "answer_id": 150376, "author": "Daryl Spitzer", "author_id": 4766, "author_profile": "https://Stackoverflow.com/users/4766", "pm_score": 6, "selected": true, "text": "<pre><code>import pdb; pdb.set_trace()\n</code></pre>\n\n<p>See <a href=\"http://jjinux.blogspot.com/2007/08/python-cod...
2008/09/29
[ "https://Stackoverflow.com/questions/150375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ]
What do you insert into Python source code to have it break into pdb (when execution gets to that spot)?
``` import pdb; pdb.set_trace() ``` See [Python: Coding in the Debugger for Beginners](http://jjinux.blogspot.com/2007/08/python-coding-in-debugger-for-beginners.html) for this and more helpful hints.
150,446
<p>I want to react when somebody shakes the iPhone. I don't particularly care how they shake it, just that it was waved vigorously about for a split second. Does anyone know how to detect this?</p>
[ { "answer_id": 150449, "author": "camflan", "author_id": 22445, "author_profile": "https://Stackoverflow.com/users/22445", "pm_score": 3, "selected": false, "text": "<p>Check out the GLPaint example.</p>\n\n<p><a href=\"http://developer.apple.com/library/ios/#samplecode/GLPaint/Introduct...
2008/09/29
[ "https://Stackoverflow.com/questions/150446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7944/" ]
I want to react when somebody shakes the iPhone. I don't particularly care how they shake it, just that it was waved vigorously about for a split second. Does anyone know how to detect this?
In 3.0, there's now an easier way - hook into the new motion events. The main trick is that you need to have some UIView (not UIViewController) that you want as firstResponder to receive the shake event messages. Here's the code that you can use in any UIView to get shake events: ``` @implementation ShakingView - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event { if ( event.subtype == UIEventSubtypeMotionShake ) { // Put in code here to handle shake } if ( [super respondsToSelector:@selector(motionEnded:withEvent:)] ) [super motionEnded:motion withEvent:event]; } - (BOOL)canBecomeFirstResponder { return YES; } @end ``` You can easily transform any UIView (even system views) into a view that can get the shake event simply by subclassing the view with only these methods (and then selecting this new type instead of the base type in IB, or using it when allocating a view). In the view controller, you want to set this view to become first responder: ``` - (void) viewWillAppear:(BOOL)animated { [shakeView becomeFirstResponder]; [super viewWillAppear:animated]; } - (void) viewWillDisappear:(BOOL)animated { [shakeView resignFirstResponder]; [super viewWillDisappear:animated]; } ``` Don't forget that if you have other views that become first responder from user actions (like a search bar or text entry field) you'll also need to restore the shaking view first responder status when the other view resigns! This method works even if you set applicationSupportsShakeToEdit to NO.
150,454
<p>In light of Michael Carman's comment, I have decided to rewrite the question. Note that 11 comments appear before this edit, and give credence to Michael's observation that I did not write the question in a way that made it clear what I was asking. <hr/> <em>Question:</em> What is the standard--or <em>cleanest</em> way--to fake the special status that <code>$a</code> and <code>$b</code> have in regard to strict by simply importing a module? </p> <p>First of all some setup. The following works: </p> <pre><code>#!/bin/perl use strict; print "\$a=$a\n"; print "\$b=$b\n"; </code></pre> <p>If I add one more line: </p> <pre><code>print "\$c=$c\n"; </code></pre> <p>I get an error at compile time, which means that none of my <em>dazzling</em> print code gets to run. </p> <p>If I comment out <code>use strict;</code> it runs fine. Outside of strictures, <code>$a</code> and <code>$b</code> are mainly special in that <code>sort</code> passes the two values to be compared with those names. </p> <pre><code>my @reverse_order = sort { $b &lt;=&gt; $a } @unsorted; </code></pre> <p>Thus the main <em>functional</em> difference about <code>$a</code> and <code>$b</code>--even though Perl "knows their names"--is that you'd better know this when you sort, or use some of the functions in <a href="http://search.cpan.org/module?List::Util" rel="nofollow noreferrer">List::Util</a>. </p> <p>It's only when you use strict, that <code>$a</code> and <code>$b</code> become special variables in a whole new way. They are the only variables that strict will pass over without complaining that they are not declared.</p> <p><em>:</em> Now, I like strict, but it strikes me that if TIMTOWTDI (There is more than one way to do it) is Rule #1 in Perl, this is not very TIMTOWDI. It says that <code>$a</code> and <code>$b</code> are special and that's it. If you want to use variables you don't have to declare <code>$a</code> and <code>$b</code> are your guys. If you want to have three variables by adding <code>$c</code>, suddenly there's a whole other way to do it.</p> <p>Nevermind that in manipulating hashes <code>$k</code> and <code>$v</code> might make more sense:</p> <pre><code>my %starts_upper_1_to_25 = skim { $k =~ m/^\p{IsUpper}/ &amp;&amp; ( 1 &lt;= $v &amp;&amp; $v &lt;= 25 ) } %my_hash ;` </code></pre> <p>Now, I use and I like strict. But I just want <code>$k</code> and <code>$v</code> to be visible to <code>skim</code> for the most compact syntax. And I'd like it to be visible simply by </p> <pre><code>use Hash::Helper qw&lt;skim&gt;; </code></pre> <p>I'm not asking this question to know how to black-magic it. My "answer" below, should let you know that I know enough Perl to be dangerous. I'm asking if there is a way to make strict accept other variables, or what is the <em>cleanest</em> solution. The answer could well be no. If that's the case, it simply does not seem very TIMTOWTDI. </p>
[ { "answer_id": 150483, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 1, "selected": false, "text": "<p><code>$a</code> and <code>$b</code> are just global variables. You can achieve similar effects by simply declaring <code...
2008/09/29
[ "https://Stackoverflow.com/questions/150454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11289/" ]
In light of Michael Carman's comment, I have decided to rewrite the question. Note that 11 comments appear before this edit, and give credence to Michael's observation that I did not write the question in a way that made it clear what I was asking. --- *Question:* What is the standard--or *cleanest* way--to fake the special status that `$a` and `$b` have in regard to strict by simply importing a module? First of all some setup. The following works: ``` #!/bin/perl use strict; print "\$a=$a\n"; print "\$b=$b\n"; ``` If I add one more line: ``` print "\$c=$c\n"; ``` I get an error at compile time, which means that none of my *dazzling* print code gets to run. If I comment out `use strict;` it runs fine. Outside of strictures, `$a` and `$b` are mainly special in that `sort` passes the two values to be compared with those names. ``` my @reverse_order = sort { $b <=> $a } @unsorted; ``` Thus the main *functional* difference about `$a` and `$b`--even though Perl "knows their names"--is that you'd better know this when you sort, or use some of the functions in [List::Util](http://search.cpan.org/module?List::Util). It's only when you use strict, that `$a` and `$b` become special variables in a whole new way. They are the only variables that strict will pass over without complaining that they are not declared. *:* Now, I like strict, but it strikes me that if TIMTOWTDI (There is more than one way to do it) is Rule #1 in Perl, this is not very TIMTOWDI. It says that `$a` and `$b` are special and that's it. If you want to use variables you don't have to declare `$a` and `$b` are your guys. If you want to have three variables by adding `$c`, suddenly there's a whole other way to do it. Nevermind that in manipulating hashes `$k` and `$v` might make more sense: ``` my %starts_upper_1_to_25 = skim { $k =~ m/^\p{IsUpper}/ && ( 1 <= $v && $v <= 25 ) } %my_hash ;` ``` Now, I use and I like strict. But I just want `$k` and `$v` to be visible to `skim` for the most compact syntax. And I'd like it to be visible simply by ``` use Hash::Helper qw<skim>; ``` I'm not asking this question to know how to black-magic it. My "answer" below, should let you know that I know enough Perl to be dangerous. I'm asking if there is a way to make strict accept other variables, or what is the *cleanest* solution. The answer could well be no. If that's the case, it simply does not seem very TIMTOWTDI.
If I'm understanding your question you want to write a module that declares variables in the user's namespace (so they don't have to) and which get localized automatically in callbacks. Is that right? You can do this by declaring globals and exporting them. (Though do note that it's generally considered bad form to export things without being asked to.) ``` package Foo; use strict; use warnings; require Exporter; our @ISA = qw(Exporter); our @EXPORT = qw(*k *v hashmap); our ($k, $v); sub hashmap(&\%) { my $code = shift; my $hash = shift; while (local ($k, $v) = each %$hash) { $code->(); } } ``` **Note:** The export is of `*k` and `*v`, not `$k` and `$v`. If you don't export the entire typeglob the `local` in `hashmap` won't work correctly from the user's package. A side effect of this is that *all* of the various forms of `k` and `v` (`%k`, `@v`, etc.) get declared and aliased. For a full explanation of this, see [Symbol Tables in perlmod](http://perldoc.perl.org/perlmod.html#Symbol-Tables). Then in your script: ``` use Foo; # exports $k and $v my %h = (a => 1, b => 2, c => 3); hashmap { print "$k => $v\n" } %h; __END__ c => 3 a => 1 b => 2 ```
150,471
<p>I have a DataGridView whose DataSource is a DataTable. This DataTable has a boolean column, which is interpreted as a checkbox in the DataGridView.</p> <pre><code>employeeSelectionTable.Columns.Add("IsSelected", typeof(bool)); ... employeeSelectionTable.RowChanged += selectionTableRowChanged; dataGridViewSelectedEmployees.DataSource = employeeSelectionTable; ... private void selectionTableRowChanged(object sender, DataRowChangeEventArgs e) { if ((bool)e.Row["IsSelected"]) { Console.Writeline("Is Selected"); } else { Console.Writeline("Is Not Selected"); } break; } </code></pre> <p>When the user single-clicks on a checkbox, it gets checked, and selectionTableRowChanged will output "Is Selected."</p> <p>Similarly, when the user checks it again, the box gets cleared, and selectionTableRowChanged outputs "Is Not Selected."</p> <p>Here's where I have the problem:</p> <p>When the user double-clicks on the checkbox, the checkbox gets checked, the RowChanged event gets called ("Is Selected"), and then the checkbox is cleared, and no corresponding RowChanged event gets called. Now the subscriber to the the RowChanged event is out of sync.</p> <p>My solution right now is to subclass DataGridView and override WndProc to eat WM_LBUTTONDBLCLICK, so any double-clicking on the control is ignored. Is there a better solution?</p>
[ { "answer_id": 150482, "author": "Ian Jacobs", "author_id": 22818, "author_profile": "https://Stackoverflow.com/users/22818", "pm_score": 1, "selected": false, "text": "<p>Is there some reason it needs to be done that low level? Can the DoubleClick Method just be an empty method that ea...
2008/09/29
[ "https://Stackoverflow.com/questions/150471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a DataGridView whose DataSource is a DataTable. This DataTable has a boolean column, which is interpreted as a checkbox in the DataGridView. ``` employeeSelectionTable.Columns.Add("IsSelected", typeof(bool)); ... employeeSelectionTable.RowChanged += selectionTableRowChanged; dataGridViewSelectedEmployees.DataSource = employeeSelectionTable; ... private void selectionTableRowChanged(object sender, DataRowChangeEventArgs e) { if ((bool)e.Row["IsSelected"]) { Console.Writeline("Is Selected"); } else { Console.Writeline("Is Not Selected"); } break; } ``` When the user single-clicks on a checkbox, it gets checked, and selectionTableRowChanged will output "Is Selected." Similarly, when the user checks it again, the box gets cleared, and selectionTableRowChanged outputs "Is Not Selected." Here's where I have the problem: When the user double-clicks on the checkbox, the checkbox gets checked, the RowChanged event gets called ("Is Selected"), and then the checkbox is cleared, and no corresponding RowChanged event gets called. Now the subscriber to the the RowChanged event is out of sync. My solution right now is to subclass DataGridView and override WndProc to eat WM\_LBUTTONDBLCLICK, so any double-clicking on the control is ignored. Is there a better solution?
The reason that making an empty DoubleClick event method would not help would be that is executed in addition to the other operations that happen when a double click occurs. If you look at the windows generated code or examples of programatically adding event handlers, you use += to assign the event handler. This means you are adding that event handler in addition to the others that already exist, you could have multiple event handlers being triggered on the save event. My instinct would have been to override the DataGridView class, then override the OnDoubleClick method and not call the base OnDoubleClick method. However, I have tested this real quick and am seeing some interesting results. I put together the following test class: ``` using System; using System.Windows.Forms; namespace TestApp { class DGV : DataGridView { private string test = ""; protected override void OnDoubleClick(EventArgs e) { MessageBox.Show(test + "OnDoubleClick"); } protected override void OnCellMouseDoubleClick(System.Windows.Forms.DataGridViewCellMouseEventArgs e) { MessageBox.Show(test + "OnCellMouseDoubleClick"); } protected override void OnCellMouseClick(System.Windows.Forms.DataGridViewCellMouseEventArgs e) { if (e.Clicks == 1) { // Had to do this with a variable as using a MessageBox // here would block us from pulling off a double click test = "1 click "; base.OnCellMouseClick(e); } else { MessageBox.Show("OnCellMouseClick"); } } } } ``` Then inserted this into a windows form, adding a checkbox column and ran the program. On a fresh run, double clicking on the checkbox causes the messagebox display to say "1 click OnDoubleClick". This means that OnCellMouseClick executed on the first part of the double click and then OnDoubleClick executed on the second click. Also, unfortunately, the removal of the call to the base methods doesn't seem to be preventing the checkbox from getting the click passed to it. I suspect that for this approach to work it may have to be taken further and override the DataGridViewCheckBoxColumn and DataGridViewCheckBoxCell that ignores the double click. Assuming this works, you would be able to stop double click on the checkbox but allow it still on your other column controls. I have posted an answer on another question that talks about creating custom DataGridView columns and cells at [here](https://stackoverflow.com/questions/121274/is-it-possible-to-bind-complex-type-properties-to-a-datagrid#128909).
150,505
<p>I am currently defining regular expressions in order to capture parameters in a URL, as described in the tutorial. How do I access parameters from the URL as part the <code>HttpRequest</code> object?</p> <p>My <code>HttpRequest.GET</code> currently returns an empty <code>QueryDict</code> object.</p> <p>I'd like to learn how to do this without a library, so I can get to know Django better.</p>
[ { "answer_id": 150518, "author": "camflan", "author_id": 22445, "author_profile": "https://Stackoverflow.com/users/22445", "pm_score": 11, "selected": true, "text": "<p>When a URL is like <code>domain/search/?q=haha</code>, you would use <code>request.GET.get('q', '')</code>.</p>\n<p><co...
2008/09/29
[ "https://Stackoverflow.com/questions/150505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1227001/" ]
I am currently defining regular expressions in order to capture parameters in a URL, as described in the tutorial. How do I access parameters from the URL as part the `HttpRequest` object? My `HttpRequest.GET` currently returns an empty `QueryDict` object. I'd like to learn how to do this without a library, so I can get to know Django better.
When a URL is like `domain/search/?q=haha`, you would use `request.GET.get('q', '')`. `q` is the parameter you want, and `''` is the default value if `q` isn't found. However, if you are instead just configuring your `URLconf`\*\*, then your captures from the `regex` are passed to the function as arguments (or named arguments). Such as: ``` (r'^user/(?P<username>\w{0,50})/$', views.profile_page,), ``` Then in your `views.py` you would have ``` def profile_page(request, username): # Rest of the method ```
150,513
<p>I have a form in HTML where our users fill in the data and then print it. The data isn't saved anywhere. These forms come from outside our company and are built as html pages to resemble the original as closely as possible and then stuffed away and forgotten in a folder on the intranet. Normally another developer does them, but I have to do a few while he's out. Looking through his code, all his forms have a bunch of server-side code to take the inputs and re-write the page with only the contents. It seems like there should be a better way.</p> <p>I want to just style the text inputs using a media selector so that when it prints you can see the text, but nothing of the box surrounding it. Any thoughts?</p>
[ { "answer_id": 150521, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;input type=\"text\" style=\"border: 0; background-color: #fff;\" /&gt;\n</code></pre>\n\n<p>Where #fff is your ...
2008/09/29
[ "https://Stackoverflow.com/questions/150513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
I have a form in HTML where our users fill in the data and then print it. The data isn't saved anywhere. These forms come from outside our company and are built as html pages to resemble the original as closely as possible and then stuffed away and forgotten in a folder on the intranet. Normally another developer does them, but I have to do a few while he's out. Looking through his code, all his forms have a bunch of server-side code to take the inputs and re-write the page with only the contents. It seems like there should be a better way. I want to just style the text inputs using a media selector so that when it prints you can see the text, but nothing of the box surrounding it. Any thoughts?
Add a separate CSS file for printing by doing something like this: ``` <link rel="stylsheet" type="text/css" media="print" href="print.css"> ``` add it to the `<head>` section of the page. In this(print.css) file include styling relevant to what you want to see when the page is printed, for example: `input{border: 0px}` should hide the border of input boxes when printing.
150,514
<p>In the database I have a field named 'body' that has an XML in it. The method I created in the model looks like this:</p> <pre><code>def self.get_personal_data_module(person_id) person_module = find_by_person_id(person_id) item_module = Hpricot(person_module.body) personal_info = Array.new personal_info = {:studies =&gt; (item_module/"studies").inner_html, :birth_place =&gt; (item_module/"birth_place").inner_html, :marrital_status =&gt; (item_module/"marrital_status").inner_html} return personal_info end </code></pre> <p>I want the function to return an object instead of an array. So I can use Module.studies instead of Model[:studies].</p>
[ { "answer_id": 150587, "author": "Atiaxi", "author_id": 2555346, "author_profile": "https://Stackoverflow.com/users/2555346", "pm_score": 3, "selected": true, "text": "<p>This is relatively simple; you're getting an Array because the code is building one. If you wanted to return an objec...
2008/09/29
[ "https://Stackoverflow.com/questions/150514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3718/" ]
In the database I have a field named 'body' that has an XML in it. The method I created in the model looks like this: ``` def self.get_personal_data_module(person_id) person_module = find_by_person_id(person_id) item_module = Hpricot(person_module.body) personal_info = Array.new personal_info = {:studies => (item_module/"studies").inner_html, :birth_place => (item_module/"birth_place").inner_html, :marrital_status => (item_module/"marrital_status").inner_html} return personal_info end ``` I want the function to return an object instead of an array. So I can use Module.studies instead of Model[:studies].
This is relatively simple; you're getting an Array because the code is building one. If you wanted to return an object, you'd do something like this: ``` class PersonalData attr_accessor :studies attr_accessor :birth_place attr_accessor :marital_status def initialize(studies,birth_place,marital_status) @studies = studies @birth_place = birth_place @marital_status = marital_status end end ``` And your translation code would look like: ``` def self.get_personal_data_module(person_id) person_module = find_by_person_id(person_id) item_module = Hpricot(person_module.body) personal_info = PersonalData.new((item_module/"studies").inner_html, (item_module/"birth_place").inner_html, (item_module/"marital_status").innner_html) return personal_info end ```
150,517
<p>This is an almost-duplicate of <a href="https://stackoverflow.com/questions/68477/send-file-using-post-from-a-python-script">Send file using POST from a Python script</a>, but I'd like to add a caveat: I need something that properly handles the encoding of fields and attached files. The solutions I've been able to find blow up when you throw unicode strings containing non-ascii characters into the mix. Also, most of the solutions don't base64-encode data to keep things 7-bit clean.</p>
[ { "answer_id": 151642, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 3, "selected": false, "text": "<p>Best thing I can think of is to encode it yourself. How about this subroutine?</p>\n\n<pre><code>from urllib2 impor...
2008/09/29
[ "https://Stackoverflow.com/questions/150517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23582/" ]
This is an almost-duplicate of [Send file using POST from a Python script](https://stackoverflow.com/questions/68477/send-file-using-post-from-a-python-script), but I'd like to add a caveat: I need something that properly handles the encoding of fields and attached files. The solutions I've been able to find blow up when you throw unicode strings containing non-ascii characters into the mix. Also, most of the solutions don't base64-encode data to keep things 7-bit clean.
Best thing I can think of is to encode it yourself. How about this subroutine? ``` from urllib2 import Request, urlopen from binascii import b2a_base64 def b64open(url, postdata): req = Request(url, b2a_base64(postdata), headers={'Content-Transfer-Encoding': 'base64'}) return urlopen(req) conn = b64open("http://www.whatever.com/script.cgi", u"Liberté Égalité Fraternité") # returns a file-like object ``` (Okay, so this code just sends POST-data. But you apparently want multipart-encoded data, as if you clicked an "Upload File" button, right? Well, it's a pretty straightforward combination of what I have here and the answers from the question you linked.)