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
80,857
<p>In the Delphi IDE, you can hold control and click on a method to jump to its definition. In VS2008, you have to right-click and select "Go To Definition".</p> <p>I use this function quite often, so I'd really like to get VS to behave like Delphi in this regard - its so much quicker to ctrl+click.</p> <p>I don't think there's a way to get this working in base VS2008 - am I wrong? Or maybe there's a plugin I could use?</p> <p><strong>Edit</strong>: Click then F12 does work - but isn't really a good solution for me.. It's still way slower than ctrl+click. I might try AutoHotkey, since I'm already running it for something else.</p> <p><strong>Edit</strong>: <a href="http://www.autohotkey.com" rel="nofollow noreferrer">AutoHotkey</a> worked for me. Here's my script:</p> <pre><code>SetTitleMatchMode RegEx #IfWinActive, .* - Microsoft Visual Studio ^LButton::Send {click}{f12} </code></pre>
[ { "answer_id": 80869, "author": "RWendi", "author_id": 15152, "author_profile": "https://Stackoverflow.com/users/15152", "pm_score": -1, "selected": false, "text": "<p>Put the mouse cursor on the method name or any identifier, and press <kbd>F12</kbd></p>\n" }, { "answer_id": 808...
2008/09/17
[ "https://Stackoverflow.com/questions/80857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369/" ]
In the Delphi IDE, you can hold control and click on a method to jump to its definition. In VS2008, you have to right-click and select "Go To Definition". I use this function quite often, so I'd really like to get VS to behave like Delphi in this regard - its so much quicker to ctrl+click. I don't think there's a way to get this working in base VS2008 - am I wrong? Or maybe there's a plugin I could use? **Edit**: Click then F12 does work - but isn't really a good solution for me.. It's still way slower than ctrl+click. I might try AutoHotkey, since I'm already running it for something else. **Edit**: [AutoHotkey](http://www.autohotkey.com) worked for me. Here's my script: ``` SetTitleMatchMode RegEx #IfWinActive, .* - Microsoft Visual Studio ^LButton::Send {click}{f12} ```
You could create an Autohotkey script that does that. When you ctrl-click a word, send a doubleclick then a F12. I don't have AHK handy so I can't try and sketch some code but it should be pretty easy; the AHK recorder should have enough features to let you create it in a point 'n' click fashion and IIRC it is smart enough to let you limit this behaviour to windows of a certain class only. When you have your script ready just run the script in the background while you code. It takes just an icon in the Notify bar.
80,859
<p>I'm writing a Rails application which will monitor data quality over some specific databases. In order to do that, I need to be able to execute direct SQL queries over these databases - which of course are not the same as the one used to drive the Rails application models. In short, this means I can't use the trick of going through the ActiveRecord base connection.</p> <p>The databases I need to connect to are not known at design time (i.e.: I can't put their details in database.yaml). Rather, I have a model 'database_details' which the user will use to enter the details of the databases over which the application will execute queries at runtime. </p> <p>So the connection to these databases really is dynamic and the details are resolved at runtime only.</p>
[ { "answer_id": 80946, "author": "Codebeef", "author_id": 12037, "author_profile": "https://Stackoverflow.com/users/12037", "pm_score": 0, "selected": false, "text": "<p>You may be able to do this through <a href=\"http://blog.whitet.net/articles/2008/01/30/rails-has_many-with-models-over...
2008/09/17
[ "https://Stackoverflow.com/questions/80859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11477/" ]
I'm writing a Rails application which will monitor data quality over some specific databases. In order to do that, I need to be able to execute direct SQL queries over these databases - which of course are not the same as the one used to drive the Rails application models. In short, this means I can't use the trick of going through the ActiveRecord base connection. The databases I need to connect to are not known at design time (i.e.: I can't put their details in database.yaml). Rather, I have a model 'database\_details' which the user will use to enter the details of the databases over which the application will execute queries at runtime. So the connection to these databases really is dynamic and the details are resolved at runtime only.
I had a situation like this where I had to connect to hundreds of different instances of an external application, and I did code similar to the following: ``` def get_custom_connection(identifier, host, port, dbname, dbuser, password) eval("Custom_#{identifier} = Class::new(ActiveRecord::Base)") eval("Custom_#{identifier}.establish_connection(:adapter=>'mysql', :host=>'#{host}', :port=>#{port}, :database=>'#{dbname}', " + ":username=>'#{dbuser}', :password=>'#{password}')") return eval("Custom_#{identifier}.connection") end ``` This has the added benefit of not changing your ActiveRecord::Base connection that your models inherit from, so you can run SQL against this connection and discard the object when you're done with it.
80,863
<p>I am seeing strange behaviour with the flash.media.Sound class in Flex 3.</p> <pre><code>var sound:Sound = new Sound(); try{ sound.load(new URLRequest("directory/file.mp3")) } catch(e:IOError){ ... } </code></pre> <p>However this isn't helping. I'm getting a stream error, and it actually sees to be in the Sound constructor.</p> <blockquote> <p>Error #2044: Unhandled IOErrorEvent:. text=Error #2032: Stream Error. at... ]</p> </blockquote> <p>I saw one example in the Flex docs where they add an event listener for IOErrorEvent, SURELY I don't have to do this, and can simply use try-catch? Can I set a null event listener?</p>
[ { "answer_id": 81447, "author": "grapefrukt", "author_id": 914, "author_profile": "https://Stackoverflow.com/users/914", "pm_score": 1, "selected": false, "text": "<p>You will need to add a listener since the URLRequest is not instantaneous. It will be <strong>very</strong> fast if you'r...
2008/09/17
[ "https://Stackoverflow.com/questions/80863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13220/" ]
I am seeing strange behaviour with the flash.media.Sound class in Flex 3. ``` var sound:Sound = new Sound(); try{ sound.load(new URLRequest("directory/file.mp3")) } catch(e:IOError){ ... } ``` However this isn't helping. I'm getting a stream error, and it actually sees to be in the Sound constructor. > > Error #2044: Unhandled IOErrorEvent:. > text=Error #2032: Stream Error. at... ] > > > I saw one example in the Flex docs where they add an event listener for IOErrorEvent, SURELY I don't have to do this, and can simply use try-catch? Can I set a null event listener?
[IOError](http://livedocs.adobe.com/flex/3/langref/flash/errors/IOError.html) = target file cannot be found (or for some other reason cannot be read). Check your file's path. Edit: I just realized this may not be your problem, you're just trying to catch the IO error? If so, you can do this: ``` var sound:Sound = new Sound(); sound.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); sound.load(new URLRequest("directory/file.mp3")); function ioErrorHandler(event:IOErrorEvent):void { trace("IO error occurred"); } ```
80,875
<p>How do you create a hardlink (as opposed to a symlink or a Mac OS alias) in OS X that points to a directory? I already know the command "ln target destination" but that only works when the target is a file. I know that Mac OS, unlike other Unix environments, does allow hardlinking to folders (this is used for Time Machine, for example) but I don't know how to do it myself.</p>
[ { "answer_id": 81000, "author": "Penfold", "author_id": 11952, "author_profile": "https://Stackoverflow.com/users/11952", "pm_score": -1, "selected": false, "text": "<p>The short answer is you can't. :) (except possibly as root, when it would be more accurate to say you shouldn't.)</p>\n...
2008/09/17
[ "https://Stackoverflow.com/questions/80875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4939/" ]
How do you create a hardlink (as opposed to a symlink or a Mac OS alias) in OS X that points to a directory? I already know the command "ln target destination" but that only works when the target is a file. I know that Mac OS, unlike other Unix environments, does allow hardlinking to folders (this is used for Time Machine, for example) but I don't know how to do it myself.
You can't do it directly in BASH then. However... I found an article here that discusses how to do it indirectly: <http://www.mactech.com/articles/mactech/Vol.23/23.11/ExploringLeopardwithDTrace/index.html> by compiling a simple little C program: ``` #include <unistd.h> #include <stdio.h> int main(int argc, char *argv[]) { if (argc != 3) return 1; int ret = link(argv[1], argv[2]); if (ret != 0) perror("link"); return ret; } ``` ...and build in Terminal.app with: ``` $ gcc -o hlink hlink.c -Wall ```
80,903
<p>My problem is that I want to have a server application (on a remote computer) to publish certain events to several client computers. The server and client communicate using .Net-Remoting so currently I am using remoted .Net-Events to get the functionality. But there is one drawback: when the server (the event publisher) comes offline and is restarted, the clients lose the connection since the remote object references become invalid.</p> <p>I am looking into Loosely Coupled Events and Transient COM Subscriptions to solve this issue. I put together a small demo application with one publisher and two subscribers. It works beautifully on one computer. </p> <p>I am using the COMAdmin-Libraries to create a transient subscription for the event subscribers. The code looks like this:</p> <pre><code>MyEventHandler handler = new MyEventHandler(); ICOMAdminCatalog catalog; ICatalogCollection transientCollection; ICatalogObject subscription; catalog = (ICOMAdminCatalog)new COMAdminCatalog(); transientCollection = (ICatalogCollection)catalog.GetCollection("TransientSubscriptions"); subscription = (ICatalogObject)transientCollection.Add(); subscription.set_Value("Name", "SubTrans"); subscription.set_Value("SubscriberInterface", handler); string eventClassString = "{B57E128F-DB28-451b-99D3-0F81DA487EDE}"; subscription.set_Value("EventCLSID", eventClassString); string sinkString = "{9A616A06-4F8D-4fbc-B47F-482C24A04F35}"; subscription.set_Value("InterfaceID", sinkString); subscription.set_Value("FilterCriteria", ""); subscription.set_Value("PublisherID", ""); transientCollection.SaveChanges(); handler.Event1 += OnEvent1; handler.Event2 += OnEvent2; </code></pre> <p>My question now is: what do I have to change in the subscription to make this work over a network? Is it even possible?</p>
[ { "answer_id": 81843, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 0, "selected": false, "text": "<p>If your server comes offline every once and a while I cannot see how you can avoid to poll it to check that it is alive...
2008/09/17
[ "https://Stackoverflow.com/questions/80903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9602/" ]
My problem is that I want to have a server application (on a remote computer) to publish certain events to several client computers. The server and client communicate using .Net-Remoting so currently I am using remoted .Net-Events to get the functionality. But there is one drawback: when the server (the event publisher) comes offline and is restarted, the clients lose the connection since the remote object references become invalid. I am looking into Loosely Coupled Events and Transient COM Subscriptions to solve this issue. I put together a small demo application with one publisher and two subscribers. It works beautifully on one computer. I am using the COMAdmin-Libraries to create a transient subscription for the event subscribers. The code looks like this: ``` MyEventHandler handler = new MyEventHandler(); ICOMAdminCatalog catalog; ICatalogCollection transientCollection; ICatalogObject subscription; catalog = (ICOMAdminCatalog)new COMAdminCatalog(); transientCollection = (ICatalogCollection)catalog.GetCollection("TransientSubscriptions"); subscription = (ICatalogObject)transientCollection.Add(); subscription.set_Value("Name", "SubTrans"); subscription.set_Value("SubscriberInterface", handler); string eventClassString = "{B57E128F-DB28-451b-99D3-0F81DA487EDE}"; subscription.set_Value("EventCLSID", eventClassString); string sinkString = "{9A616A06-4F8D-4fbc-B47F-482C24A04F35}"; subscription.set_Value("InterfaceID", sinkString); subscription.set_Value("FilterCriteria", ""); subscription.set_Value("PublisherID", ""); transientCollection.SaveChanges(); handler.Event1 += OnEvent1; handler.Event2 += OnEvent2; ``` My question now is: what do I have to change in the subscription to make this work over a network? Is it even possible?
What about MSMQ? It seems perfect for what you are trying to achieve? You can use a traditional publish/subscribe model or multicast the messages.
80,963
<p>I am trying to write some JavaScript RegEx to replace user inputed tags with real html tags, so <code>[b]</code> will become <code>&lt;b&gt;</code> and so forth. the RegEx I am using looks like so</p> <pre><code>var exptags = /\[(b|u|i|s|center|code){1}]((.){1,}?)\[\/(\1){1}]/ig; </code></pre> <p>with the following JavaScript</p> <pre><code>s.replace(exptags,"&lt;$1&gt;$2&lt;/$1&gt;"); </code></pre> <p>this works fine for single nested tags, for example:</p> <pre><code>[b]hello[/b] [u]world[/u] </code></pre> <p>but if the tags are nested inside each other it will only match the outer tags, for example </p> <pre><code>[b]foo [u]to the[/u] bar[/b] </code></pre> <p>this will only match the <code>b</code> tags. how can I fix this? should i just loop until the starting string is the same as the outcome? I have a feeling that the <code>((.){1,}?)</code> patten is wrong also?</p> <p>Thanks</p>
[ { "answer_id": 81074, "author": "Eugen Anghel", "author_id": 4017, "author_profile": "https://Stackoverflow.com/users/4017", "pm_score": 1, "selected": false, "text": "<p>AFAIK you can't express recursion with regular expressions. </p>\n\n<p>You can however do that with .NET's System.Tex...
2008/09/17
[ "https://Stackoverflow.com/questions/80963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2098/" ]
I am trying to write some JavaScript RegEx to replace user inputed tags with real html tags, so `[b]` will become `<b>` and so forth. the RegEx I am using looks like so ``` var exptags = /\[(b|u|i|s|center|code){1}]((.){1,}?)\[\/(\1){1}]/ig; ``` with the following JavaScript ``` s.replace(exptags,"<$1>$2</$1>"); ``` this works fine for single nested tags, for example: ``` [b]hello[/b] [u]world[/u] ``` but if the tags are nested inside each other it will only match the outer tags, for example ``` [b]foo [u]to the[/u] bar[/b] ``` this will only match the `b` tags. how can I fix this? should i just loop until the starting string is the same as the outcome? I have a feeling that the `((.){1,}?)` patten is wrong also? Thanks
The easiest solution would be to to replace all the tags, whether they are closed or not and let `.innerHTML` work out if they are matched or not it will much more resilient that way.. ``` var tagreg = /\[(\/?)(b|u|i|s|center|code)]/ig div.innerHTML="[b][i]helloworld[/b]".replace(tagreg, "<$1$2>") //no closing i //div.inerHTML=="<b><i>helloworld</i></b>" ```
80,993
<p>As you can see, even after the program should have died it speaks from the grave. Is there a way to "deregister" the exitfunction in case of exceptions?</p> <pre><code>import atexit def helloworld(): print("Hello World!") atexit.register(helloworld) raise Exception("Good bye cruel world!") </code></pre> <p>outputs</p> <pre><code>Traceback (most recent call last): File "test.py", line 8, in &lt;module&gt; raise Exception("Good bye cruel world!") Exception: Good bye cruel world! Hello World! </code></pre>
[ { "answer_id": 81051, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": -1, "selected": false, "text": "<p>If you call</p>\n\n<pre><code>import os\nos._exit(0)\n</code></pre>\n\n<p>the exit handlers will not be called, yours...
2008/09/17
[ "https://Stackoverflow.com/questions/80993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15274/" ]
As you can see, even after the program should have died it speaks from the grave. Is there a way to "deregister" the exitfunction in case of exceptions? ``` import atexit def helloworld(): print("Hello World!") atexit.register(helloworld) raise Exception("Good bye cruel world!") ``` outputs ``` Traceback (most recent call last): File "test.py", line 8, in <module> raise Exception("Good bye cruel world!") Exception: Good bye cruel world! Hello World! ```
I don't really know why you want to do that, but you can install an excepthook that will be called by Python whenever an uncatched exception is raised, and in it clear the array of registered function in the `atexit` module. Something like that : ``` import sys import atexit def clear_atexit_excepthook(exctype, value, traceback): atexit._exithandlers[:] = [] sys.__excepthook__(exctype, value, traceback) def helloworld(): print "Hello world!" sys.excepthook = clear_atexit_excepthook atexit.register(helloworld) raise Exception("Good bye cruel world!") ``` Beware that it may behave incorrectly if the exception is raised from an `atexit` registered function (but then the behaviour would have been strange even if this hook was not used).
81,022
<p>In the KornShell (ksh) on <b>AIX UNIX Version 5.3</b> with the editor mode set to vi using:</p> <pre><code>set -o vi </code></pre> <p>What are the key-strokes at the shell command line to autocomplete a file or directory name?</p>
[ { "answer_id": 81135, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 5, "selected": true, "text": "<p>ESC\\ works fine on AIX4.2 at least. One thing I noticed is that it only autocompletes to the unique part of the file ...
2008/09/17
[ "https://Stackoverflow.com/questions/81022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/381/" ]
In the KornShell (ksh) on **AIX UNIX Version 5.3** with the editor mode set to vi using: ``` set -o vi ``` What are the key-strokes at the shell command line to autocomplete a file or directory name?
ESC\ works fine on AIX4.2 at least. One thing I noticed is that it only autocompletes to the unique part of the file name. So if you have the files x.txt, x171go and x171stop, the following will happen: ``` Press keys: Command line is: x x <ESC>\ x 1 x1 <ESC>\ x171 g<ESC>\ x171go ```
81,052
<p>Why wouldn't I choose abstract? What are the limitations to declaring a class member virtual? Can only methods be declared virtual?</p>
[ { "answer_id": 81059, "author": "Maximilian", "author_id": 1733, "author_profile": "https://Stackoverflow.com/users/1733", "pm_score": 0, "selected": false, "text": "<p>If you want to give it an implementation in your base class you make it virtual, if you don't you make it abstract.</p>...
2008/09/17
[ "https://Stackoverflow.com/questions/81052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6651/" ]
Why wouldn't I choose abstract? What are the limitations to declaring a class member virtual? Can only methods be declared virtual?
An abstract method or property (both can be virtual or abstract) can only be declared in an abstract class and cannot have a body, i.e. you can't implement it in your abstract class. A virtual method or property must have a body, i.e. you must provide an implementation (even if the body is empty). If someone want to use your abstract class, he will have to implement a class that inherits from it and explicitly implement the abstract methods and properties but can chose to not override the virtual methods and properties. Exemple : ``` using System; using C=System.Console; namespace Foo { public class Bar { public static void Main(string[] args) { myImplementationOfTest miot = new myImplementationOfTest(); miot.myVirtualMethod(); miot.myOtherVirtualMethod(); miot.myProperty = 42; miot.myAbstractMethod(); } } public abstract class test { public abstract int myProperty { get; set; } public abstract void myAbstractMethod(); public virtual void myVirtualMethod() { C.WriteLine("foo"); } public virtual void myOtherVirtualMethod() { } } public class myImplementationOfTest : test { private int _foo; public override int myProperty { get { return _foo; } set { _foo = value; } } public override void myAbstractMethod() { C.WriteLine(myProperty); } public override void myOtherVirtualMethod() { C.WriteLine("bar"); } } } ```
81,099
<p>As the title states, I'd be interested to find a safe feature-based (that is, without using navigator.appName or navigator.appVersion) way to detect Google Chrome.</p> <p>By feature-based I mean, for example:</p> <pre><code>if(window.ActiveXObject) { // internet explorer! } </code></pre> <p><strong>Edit:</strong> As it's been pointed out, the question doesn't make much sense (obviously if you want to implement a feature, you test for it, if you want to detect for a specific browser, you check the user agent), sorry, it's 5am ;) Let me me phrase it like this: Are there any javascript objects and/or features that are unique to Chrome... </p>
[ { "answer_id": 81121, "author": "Marijn", "author_id": 12038, "author_profile": "https://Stackoverflow.com/users/12038", "pm_score": 2, "selected": false, "text": "<p>Not exactly an answer to the question... but if you are trying to detect a specific browser brand, the point of feature-c...
2008/09/17
[ "https://Stackoverflow.com/questions/81099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14981/" ]
As the title states, I'd be interested to find a safe feature-based (that is, without using navigator.appName or navigator.appVersion) way to detect Google Chrome. By feature-based I mean, for example: ``` if(window.ActiveXObject) { // internet explorer! } ``` **Edit:** As it's been pointed out, the question doesn't make much sense (obviously if you want to implement a feature, you test for it, if you want to detect for a specific browser, you check the user agent), sorry, it's 5am ;) Let me me phrase it like this: Are there any javascript objects and/or features that are unique to Chrome...
``` isChrome = function() { return Boolean(window.chrome); } ```
81,150
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/48935/how-can-i-register-a-global-hot-key-to-say-ctrlshiftletter-using-wpf-and-ne">How can I register a global hot key to say CTRL+SHIFT+(LETTER) using WPF and .NET 3.5?</a> </p> </blockquote> <p>I'd like to have multiple global hotkeys in my new app (to control the app from anywhere in windows), and all of the given sources/solutions I found on the web seem to provide with a sort of a limping solution (either solutions only for one g.hotkey, or solutions that while running create annoying mouse delays on the screen).</p> <p>Does anyone here know of a resource that can help me achive this, that I can learn from? Anything?</p> <p>Thanks ! :)</p>
[ { "answer_id": 81335, "author": "arul", "author_id": 15409, "author_profile": "https://Stackoverflow.com/users/15409", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.codeproject.com/KB/cs/CSLLKeyboardHook.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/cs/CSLL...
2008/09/17
[ "https://Stackoverflow.com/questions/81150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
> > **Possible Duplicate:** > > [How can I register a global hot key to say CTRL+SHIFT+(LETTER) using WPF and .NET 3.5?](https://stackoverflow.com/questions/48935/how-can-i-register-a-global-hot-key-to-say-ctrlshiftletter-using-wpf-and-ne) > > > I'd like to have multiple global hotkeys in my new app (to control the app from anywhere in windows), and all of the given sources/solutions I found on the web seem to provide with a sort of a limping solution (either solutions only for one g.hotkey, or solutions that while running create annoying mouse delays on the screen). Does anyone here know of a resource that can help me achive this, that I can learn from? Anything? Thanks ! :)
The nicest solution I've found is <http://bloggablea.wordpress.com/2007/05/01/global-hotkeys-with-net/> ``` Hotkey hk = new Hotkey(); hk.KeyCode = Keys.1; hk.Windows = true; hk.Pressed += delegate { Console.WriteLine("Windows+1 pressed!"); }; hk.Register(myForm); ``` Note how you can set different lambdas to different hotkeys
81,174
<p>I want to have a text box that the user can type in that shows an Ajax-populated list of my model's names, and then when the user selects one I want the HTML to save the model's ID, and use that when the form is submitted.</p> <p>I've been poking at the auto_complete plugin that got excised in Rails 2, but it seems to have no inkling that this might be useful. There's a <a href="http://railscasts.com/episodes/102-auto-complete-association" rel="nofollow noreferrer">Railscast episode</a> that covers using that plugin, but it doesn't touch on this topic. The comments <a href="http://railscasts.com/episodes/102-auto-complete-association#comment_37039" rel="nofollow noreferrer">point out that it could be an issue</a>, and <a href="http://model-ac.rubyforge.org/" rel="nofollow noreferrer">point to <code>model_auto_completer</code> as a possible solution</a>, which seems to work if the viewed items are simple strings, but the inserted text includes lots of junk spaces if (as I would like to do) you include a picture into the list items, <a href="http://model-ac.rubyforge.org/classes/ModelAutoCompleterHelper.html#M000003" rel="nofollow noreferrer">despite what the documentation says</a>.</p> <p>I could probably hack <code>model_auto_completer</code> into shape, and I may still end up doing so, but I am eager to find out if there are better options out there.</p>
[ { "answer_id": 81265, "author": "Dan Harper", "author_id": 14530, "author_profile": "https://Stackoverflow.com/users/14530", "pm_score": 1, "selected": false, "text": "<p>I rolled my own. The process is a little convoluted, but...</p>\n\n<p>I just made a text_field on the form with an o...
2008/09/17
[ "https://Stackoverflow.com/questions/81174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5657/" ]
I want to have a text box that the user can type in that shows an Ajax-populated list of my model's names, and then when the user selects one I want the HTML to save the model's ID, and use that when the form is submitted. I've been poking at the auto\_complete plugin that got excised in Rails 2, but it seems to have no inkling that this might be useful. There's a [Railscast episode](http://railscasts.com/episodes/102-auto-complete-association) that covers using that plugin, but it doesn't touch on this topic. The comments [point out that it could be an issue](http://railscasts.com/episodes/102-auto-complete-association#comment_37039), and [point to `model_auto_completer` as a possible solution](http://model-ac.rubyforge.org/), which seems to work if the viewed items are simple strings, but the inserted text includes lots of junk spaces if (as I would like to do) you include a picture into the list items, [despite what the documentation says](http://model-ac.rubyforge.org/classes/ModelAutoCompleterHelper.html#M000003). I could probably hack `model_auto_completer` into shape, and I may still end up doing so, but I am eager to find out if there are better options out there.
I've got a hackneyed fix for the junk spaces from the image. I added a `:after_update_element => "trimSelectedItem"` to the options hash of the `model_auto_completer` (that's the first hash of the three given). My `trimSelectedItem` then finds the appropriate sub-element and uses the contents of that for the element value: ``` function trimSelectedItem(element, value, hiddenField, modelID) { var span = value.down('span.display-text') console.log(span) var text = span.innerText || span.textContent console.log(text) element.value = text } ``` However, this then runs afoul of the `:allow_free_text` option, which by default changes the text back as soon as the text box loses focus if the text inside is not a "valid" item from the list. So I had to turn that off, too, by passing `:allow_free_text => true` into the options hash (again, the first hash). I'd really rather it remained on, though. So my current call to create the autocompleter is: ``` <%= model_auto_completer( "line_items_info[][name]", "", "line_items_info[][id]", "", {:url => formatted_products_path(:js), :after_update_element => "trimSelectedItem", :allow_free_text => true}, {:class => 'product-selector'}, {:method => 'GET', :param_name => 'q'}) %> ``` And the products/index.js.erb is: ``` <ul class='products'> <%- for product in @products -%> <li id="<%= dom_id(product) %>"> <%= image_tag image_product_path(product), :alt => "" %> <span class='display-text'><%=h product.name %></span> </li> <%- end -%> </ul> ```
81,180
<p>We have simple HTML form with <code>&lt;input type="file"&gt;</code>, like shown below:</p> <pre><code>&lt;form&gt; &lt;label for="attachment"&gt;Attachment:&lt;/label&gt; &lt;input type="file" name="attachment" id="attachment"&gt; &lt;input type="submit"&gt; &lt;/form&gt; </code></pre> <p>In IE7 (and probably all famous browsers, including old Firefox 2), if we submit a file like '//server1/path/to/file/filename' it works properly and gives the full path to the file and the filename.</p> <p>In Firefox 3, it returns only 'filename', because of their new 'security feature' to truncate the path, as explained in Firefox bug tracking system (<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=143220" rel="noreferrer">https://bugzilla.mozilla.org/show_bug.cgi?id=143220</a>)</p> <p>I have no clue how to overcome this 'new feature' because it causes all upload forms in my webapp to stop working on Firefox 3.</p> <p>Can anyone help to find a single solution to get the file path both on Firefox 3 and IE7?</p>
[ { "answer_id": 81227, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Simply you cannot do it with FF3.</p>\n\n<p>The other option could be using applet or other controls to select and upload fi...
2008/09/17
[ "https://Stackoverflow.com/questions/81180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/446104/" ]
We have simple HTML form with `<input type="file">`, like shown below: ``` <form> <label for="attachment">Attachment:</label> <input type="file" name="attachment" id="attachment"> <input type="submit"> </form> ``` In IE7 (and probably all famous browsers, including old Firefox 2), if we submit a file like '//server1/path/to/file/filename' it works properly and gives the full path to the file and the filename. In Firefox 3, it returns only 'filename', because of their new 'security feature' to truncate the path, as explained in Firefox bug tracking system (<https://bugzilla.mozilla.org/show_bug.cgi?id=143220>) I have no clue how to overcome this 'new feature' because it causes all upload forms in my webapp to stop working on Firefox 3. Can anyone help to find a single solution to get the file path both on Firefox 3 and IE7?
For preview in Firefox works this - attachment is object of attachment element in first example: ``` if (attachment.files) previewImage.src = attachment.files.item(0).getAsDataURL(); else previewImage.src = attachment.value; ```
81,191
<p>While answering <a href="https://stackoverflow.com/questions/68645/python-static-variable#81002">Static class variables in Python</a> </p> <p>I noticed that PythonWin PyWin32 build 209.2 interpreter seems to evaluate twice?</p> <pre><code>PythonWin 2.5 (r25:51908, Mar 9 2007, 17:40:28) [MSC v.1310 32 bit (Intel)] on win32. Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright information. &gt;&gt;&gt; class X: ... l = [] ... def __init__(self): ... self.__class__.l.append(1) ... &gt;&gt;&gt; X().l [1, 1] &gt;&gt;&gt; </code></pre> <p>while the python interpreter does the right thing</p> <pre><code>C:\&gt;python ActivePython 2.5.0.0 (ActiveState Software Inc.) based on Python 2.5 (r25:51908, Mar 9 2007, 17:40:28) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; class X: ... l = [] ... def __init__(self): ... self.__class__.l.append(1) ... &gt;&gt;&gt; X().l [1] &gt;&gt;&gt; </code></pre>
[ { "answer_id": 81274, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 3, "selected": true, "text": "<p>My guess is as follows. The PythonWin editor offers autocomplete for an object, i.e. when you type <code>myobject.</cod...
2008/09/17
[ "https://Stackoverflow.com/questions/81191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14351/" ]
While answering [Static class variables in Python](https://stackoverflow.com/questions/68645/python-static-variable#81002) I noticed that PythonWin PyWin32 build 209.2 interpreter seems to evaluate twice? ``` PythonWin 2.5 (r25:51908, Mar 9 2007, 17:40:28) [MSC v.1310 32 bit (Intel)] on win32. Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright information. >>> class X: ... l = [] ... def __init__(self): ... self.__class__.l.append(1) ... >>> X().l [1, 1] >>> ``` while the python interpreter does the right thing ``` C:\>python ActivePython 2.5.0.0 (ActiveState Software Inc.) based on Python 2.5 (r25:51908, Mar 9 2007, 17:40:28) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> class X: ... l = [] ... def __init__(self): ... self.__class__.l.append(1) ... >>> X().l [1] >>> ```
My guess is as follows. The PythonWin editor offers autocomplete for an object, i.e. when you type `myobject.` it offers a little popup of all the availble method names. So I think when you type `X().` it's creating an instance of `X` in the background and doing a `dir` or similar to find out the attributes of the object. So the constructor is only being run *once for each object* but to give you the interactivity it's creating objects silently in the background without telling you about it.
81,194
<p>We're using the Eclipse CDT 5 C++ IDE on Windows to develop a C++ application on a remote AIX host. </p> <p>Eclipse CDT has the ability to perform remote debugging using gdbserver. Unfortunately, gdbserver is not supported on AIX. </p> <p>Is anyone familiar with a way to debug remotely using Eclipse CDT without gdbserver? Perhaps using an SSH shell connection to gdb?</p>
[ { "answer_id": 90518, "author": "Nick Bastin", "author_id": 1502059, "author_profile": "https://Stackoverflow.com/users/1502059", "pm_score": 1, "selected": false, "text": "<p>I wouldn't normally take a shot in the dark on a question I can't really test the answer to, but since this one ...
2008/09/17
[ "https://Stackoverflow.com/questions/81194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15367/" ]
We're using the Eclipse CDT 5 C++ IDE on Windows to develop a C++ application on a remote AIX host. Eclipse CDT has the ability to perform remote debugging using gdbserver. Unfortunately, gdbserver is not supported on AIX. Is anyone familiar with a way to debug remotely using Eclipse CDT without gdbserver? Perhaps using an SSH shell connection to gdb?
finally I got gdb run remotly anyhow now. At the Bug-symbol on the taskbar I took Debug Configurations - GDB Hardware Debugging. In Main C/C++ Applications I set the full path on the Samba share of the executable (`X:\abin\vlmi9506`). I also set a linked folder on `X:\abin` in the project. Then I modified my batch-script in GDB Setup. It's not directly calling gdb in the plink-session but a unix-shell-script, which opens gdb. By this I have the possibility to set some unix environment-variables for the program before doing debug. The call in my batch: ``` plink.exe prevoax1 -l suttera -pw XXXXX -i /proj/user/dev/suttera/vl/9506/test/vlmi9506ddd.run 20155 dev o m ``` In the unix script I started gdb with the command line params from eclipse, that I found in my former tryals. The call in the shell command looks like this: ``` gdb -nw -i mi -cd=$LVarPathExec $LVarPathExec/vlmi9506 ``` Then IBM just gives gdb 6.0 for AIX. I found version 6.8 in the net at <http://www.perzl.org/aix/index.php?n=Main.Gdb>. Our Admin installed it. I can now step through the program and watch variables. I even can write gdb-commands directly in the console-view. yabadabadooooooo Hope that helps to others as well. Can not tell, what was really the winner-action. But each answer gives more new questions. Now I got 3 of them. 1. When I start the debug config I have to click restart in the toolbar to come really in the main procedure. Is it possible to come directly in main without restarting? 2. On AIX our programs are first preprocessed for embedded sql. The preprocessed c-source is put in another directory. When I duble-click the line to set a breakpoint, I get the warning "unresolved breakpoint" and in the gdb-console I see, that the break is set to the preprocessed source which is wrong. Is it possible to set the breakpoints on the right source? 3. We are using CICS on AIX. With the xldb-Debugger and the CDCN-command of CICS we manage that debugging is started, when we come in our programs. Is it possible to get that remotely (in plink) with gdb-eclipse as well?
81,214
<p>I just want an ASP.NET DropDownList with no selected item. Setting SelectedIndex to -1 is of no avail, so far. I am using Framework 3.5 with AJAX, i.e. this DropDownList is within an UpdatePanel. Here is what I am doing:</p> <pre><code> protected void Page_Load (object sender, EventArgs e) { this.myDropDownList.SelectedIndex = -1; this.myDropDownList.ClearSelection(); this.myDropDownList.Items.Add("Item1"); this.myDropDownList.Items.Add("Item2"); } </code></pre> <p>The moment I add an element in the DropDown, its SelectedIndex changes to 0 and can be no more set to -1 (I tried calling SelectedIndex after adding items as well)... What I am doing wrong? Ant help would be appreciated!</p>
[ { "answer_id": 81246, "author": "bryansh", "author_id": 211367, "author_profile": "https://Stackoverflow.com/users/211367", "pm_score": 2, "selected": false, "text": "<p>I'm pretty sure that dropdown has to have some item selected; I usually add an empty list item</p>\n\n<p>this.myDropDo...
2008/09/17
[ "https://Stackoverflow.com/questions/81214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I just want an ASP.NET DropDownList with no selected item. Setting SelectedIndex to -1 is of no avail, so far. I am using Framework 3.5 with AJAX, i.e. this DropDownList is within an UpdatePanel. Here is what I am doing: ``` protected void Page_Load (object sender, EventArgs e) { this.myDropDownList.SelectedIndex = -1; this.myDropDownList.ClearSelection(); this.myDropDownList.Items.Add("Item1"); this.myDropDownList.Items.Add("Item2"); } ``` The moment I add an element in the DropDown, its SelectedIndex changes to 0 and can be no more set to -1 (I tried calling SelectedIndex after adding items as well)... What I am doing wrong? Ant help would be appreciated!
Bare in mind myDropDownList.Items.Add will add a new Listitem element at the bottom if you call it after performing a DataSource/DataBind call so use myDropDownList.Items.Insert method instead eg... ``` myDropDownList.DataSource = DataAccess.GetDropDownItems(); // Psuedo Code myDropDownList.DataTextField = "Value"; myDropDownList.DataValueField = "Id"; myDropDownList.DataBind(); myDropDownList.Items.Insert(0, new ListItem("Please select", "")); ``` Will add the 'Please select' drop down item to the top. And as mentioned there will always be exactly one Item selected in a drop down (ListBoxes are different I believe), and this defaults to the top one if none are explicitly selected.
81,236
<p>Which built in (if any) tool can I use to determine the allocation unit size of a certain NTFS partition ?</p>
[ { "answer_id": 81257, "author": "William", "author_id": 14829, "author_profile": "https://Stackoverflow.com/users/14829", "pm_score": 8, "selected": true, "text": "<p>Open an administrator command prompt, and do this command:</p>\n\n<pre><code>fsutil fsinfo ntfsinfo [your drive]\n</code>...
2008/09/17
[ "https://Stackoverflow.com/questions/81236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Which built in (if any) tool can I use to determine the allocation unit size of a certain NTFS partition ?
Open an administrator command prompt, and do this command: ``` fsutil fsinfo ntfsinfo [your drive] ``` The Bytes Per Cluster is the equivalent of the allocation unit.
81,238
<p>Is there some way to block access from a referrer using a .htaccess file or similar? My bandwidth is being eaten up by people referred from <a href="http://www.dizzler.com" rel="nofollow noreferrer">http://www.dizzler.com</a> which is a flash based site that allows you to browse a library of crawled publicly available mp3s.</p> <p><strong>Edit:</strong> Dizzler was still getting in (probably wasn't indicating referrer in all cases) so instead I moved all my mp3s to a new folder, disabled directory browsing, and created a robots.txt file to (hopefully) keep it from being indexed again. Accepted answer changed to reflect futility of my previous attempt :P</p>
[ { "answer_id": 81247, "author": "perimosocordiae", "author_id": 10601, "author_profile": "https://Stackoverflow.com/users/10601", "pm_score": 0, "selected": false, "text": "<p>It's not a very elegant solution, but you could block the site's crawler bot, then rename your mp3 files to brea...
2008/09/17
[ "https://Stackoverflow.com/questions/81238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ]
Is there some way to block access from a referrer using a .htaccess file or similar? My bandwidth is being eaten up by people referred from <http://www.dizzler.com> which is a flash based site that allows you to browse a library of crawled publicly available mp3s. **Edit:** Dizzler was still getting in (probably wasn't indicating referrer in all cases) so instead I moved all my mp3s to a new folder, disabled directory browsing, and created a robots.txt file to (hopefully) keep it from being indexed again. Accepted answer changed to reflect futility of my previous attempt :P
That's like saying you want to stop spam-bots from harvesting emails on your publicly visible page - it's very tough to tell the difference between users and bots without forcing your viewers to log in to confirm their identity. You could use robots.txt to disallow the spiders that actually follow those rules, but that's on their side, not your server's. There's a page that explains how to catch the ones that break the rules and explicitly ban them : [Using Apache to stop bad robots](http://www.evolt.org/article/Using_Apache_to_stop_bad_robots/18/15126/) [evolt.org] If you want an easy way to stop dizzler in particular using the .htaccess, you should be able to pop it open and add: ``` <Directory /directoryName/subDirectory> Order Allow,Deny Allow from all Deny from 66.232.150.219 </Directory> ```
81,243
<p>In Delphi, the application's main help file is assigned through the TApplication.HelpFile property. All calls to the application's help system then use this property (in conjunction with CurrentHelpFile) to determine the help file to which help calls should be routed.</p> <p>In addition to TApplication.HelpFile, each form also has a TForm.HelpFile property which can be used to specify a different (separate) help file for help calls originating from that specific form.</p> <p>If an application's main help window is already open however, and a help call is made display help from a secondary help file, both help windows hang. Neither of the help windows can now be accessed, and neither can be closed. The only way to get rid of the help windows is to close the application, which results in both help windows being automatically closed as well.</p> <p>Example:</p> <pre><code>Application.HelpFile := 'Main Help.chm'; //assign the main help file name Application.HelpContext(0); //dispays the main help window Form1.HelpFile := 'Secondary Help.chm'; //assign a different help file Application.HelpContext(0); //should display a second help window </code></pre> <p>The last line of code above opens the secondary help window (but with no content) and then both help windows hang.</p> <p>My Question is this:</p> <ol> <li><p>Is it possible to display two HTMLHelp windows at the same time, and if so, what is the procedure to be followed?</p></li> <li><p>If not, is there a way to tell whether or not an application's help window is already open, and then close it programatically before displaying a different help window?</p></li> </ol> <p>(I am Using Delphi 2007 with HTMLHelp files on Windows Vista)</p> <p><strong>UPDATE: 2008-09-18</strong></p> <p>Opening two help files at the same time does in fact work as expected using the code above. The problem seems to be with the actual help files I was using - not the code.</p> <p>I tried the same code with different help files, and it worked fine.</p> <p>Strangely enough, the two help files I was using each works fine on it's own - it's only when you try to open both at the same time that they hang, and only if you open them from code (in Windows explorer I can open both at the same time without a problem).</p> <p>Anyway - the problem is definitely with the help files and not the code - so the original questions is now pretty much invalid.</p> <p><strong>UPDATE 2: 2008-09-18</strong></p> <p>I eventually found the cause of the hanging help windows. I will post the answer below and accept it as the correct one for future reference. I have also changed the questions title.</p> <p>Oops... It seems that I cannot accept my own answer...</p> <p>Please vote it up so it stays at the top.</p>
[ { "answer_id": 81318, "author": "Graza", "author_id": 11820, "author_profile": "https://Stackoverflow.com/users/11820", "pm_score": 0, "selected": false, "text": "<p>Inexperienced with help files here, and even moreso with Vista, but I can offer you a possible workaround...</p>\n\n<p>Bui...
2008/09/17
[ "https://Stackoverflow.com/questions/81243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5888/" ]
In Delphi, the application's main help file is assigned through the TApplication.HelpFile property. All calls to the application's help system then use this property (in conjunction with CurrentHelpFile) to determine the help file to which help calls should be routed. In addition to TApplication.HelpFile, each form also has a TForm.HelpFile property which can be used to specify a different (separate) help file for help calls originating from that specific form. If an application's main help window is already open however, and a help call is made display help from a secondary help file, both help windows hang. Neither of the help windows can now be accessed, and neither can be closed. The only way to get rid of the help windows is to close the application, which results in both help windows being automatically closed as well. Example: ``` Application.HelpFile := 'Main Help.chm'; //assign the main help file name Application.HelpContext(0); //dispays the main help window Form1.HelpFile := 'Secondary Help.chm'; //assign a different help file Application.HelpContext(0); //should display a second help window ``` The last line of code above opens the secondary help window (but with no content) and then both help windows hang. My Question is this: 1. Is it possible to display two HTMLHelp windows at the same time, and if so, what is the procedure to be followed? 2. If not, is there a way to tell whether or not an application's help window is already open, and then close it programatically before displaying a different help window? (I am Using Delphi 2007 with HTMLHelp files on Windows Vista) **UPDATE: 2008-09-18** Opening two help files at the same time does in fact work as expected using the code above. The problem seems to be with the actual help files I was using - not the code. I tried the same code with different help files, and it worked fine. Strangely enough, the two help files I was using each works fine on it's own - it's only when you try to open both at the same time that they hang, and only if you open them from code (in Windows explorer I can open both at the same time without a problem). Anyway - the problem is definitely with the help files and not the code - so the original questions is now pretty much invalid. **UPDATE 2: 2008-09-18** I eventually found the cause of the hanging help windows. I will post the answer below and accept it as the correct one for future reference. I have also changed the questions title. Oops... It seems that I cannot accept my own answer... Please vote it up so it stays at the top.
Assuming you have two help files called "Help File 1.chm" and "Help File 2.chm" and you are opening these help files from your Delphi code. To open Help File 1, the following code will work: ``` procedure TForm1.Button1Click(Sender: TObject); begin Application.HelpFile := 'Help File 1.chm'; Application.HelpContext(0); end; ``` To open Help File 2, the following code will work: ``` procedure TForm1.Button1Click(Sender: TObject); begin Application.HelpFile := 'Help File 2.chm'; Application.HelpContext(0); end; ``` But to open both files at the same time, the following code will cause **both help windows to hang**. ``` procedure TForm1.Button1Click(Sender: TObject); begin Application.HelpFile := 'Help File 1.chm'; Application.HelpContext(0); Application.HelpFile := 'Help File 2.chm'; Application.HelpContext(0); end; ``` **SOLUTION:** The problem is caused by the fact that there are **spaces in the help file names**. Removing the spaces from the file names will fix the problem. The following code will work fine: ``` procedure TForm1.Button1Click(Sender: TObject); begin Application.HelpFile := 'HelpFile1.chm'; Application.HelpContext(0); Application.HelpFile := 'HelpFile2.chm'; Application.HelpContext(0); end; ```
81,260
<p>Is there a tool or script which easily merges a bunch of <a href="http://en.wikipedia.org/wiki/JAR_%28file_format%29" rel="noreferrer">JAR</a> files into one JAR file? A bonus would be to easily set the main-file manifest and make it executable.</p> <p>The concrete case is a <a href="http://jrst.labs.libre-entreprise.org/en/user/functionality.html" rel="noreferrer">Java restructured text tool</a>. I would like to run it with something like:</p> <blockquote> <p>java -jar rst.jar</p> </blockquote> <p>As far as I can tell, it has no dependencies which indicates that it shouldn't be an easy single-file tool, but the downloaded ZIP file contains a lot of libraries.</p> <pre><code> 0 11-30-07 10:01 jrst-0.8.1/ 922 11-30-07 09:53 jrst-0.8.1/jrst.bat 898 11-30-07 09:53 jrst-0.8.1/jrst.sh 2675 11-30-07 09:42 jrst-0.8.1/readmeEN.txt 108821 11-30-07 09:59 jrst-0.8.1/jrst-0.8.1.jar 2675 11-30-07 09:42 jrst-0.8.1/readme.txt 0 11-30-07 10:01 jrst-0.8.1/lib/ 81508 11-30-07 09:49 jrst-0.8.1/lib/batik-util-1.6-1.jar 2450757 11-30-07 09:49 jrst-0.8.1/lib/icu4j-2.6.1.jar 559366 11-30-07 09:49 jrst-0.8.1/lib/commons-collections-3.1.jar 83613 11-30-07 09:49 jrst-0.8.1/lib/commons-io-1.3.1.jar 207723 11-30-07 09:49 jrst-0.8.1/lib/commons-lang-2.1.jar 52915 11-30-07 09:49 jrst-0.8.1/lib/commons-logging-1.1.jar 260172 11-30-07 09:49 jrst-0.8.1/lib/commons-primitives-1.0.jar 313898 11-30-07 09:49 jrst-0.8.1/lib/dom4j-1.6.1.jar 1994150 11-30-07 09:49 jrst-0.8.1/lib/fop-0.93-jdk15.jar 55147 11-30-07 09:49 jrst-0.8.1/lib/activation-1.0.2.jar 355030 11-30-07 09:49 jrst-0.8.1/lib/mail-1.3.3.jar 77977 11-30-07 09:49 jrst-0.8.1/lib/servlet-api-2.3.jar 226915 11-30-07 09:49 jrst-0.8.1/lib/jaxen-1.1.1.jar 153253 11-30-07 09:49 jrst-0.8.1/lib/jdom-1.0.jar 50789 11-30-07 09:49 jrst-0.8.1/lib/jewelcli-0.41.jar 324952 11-30-07 09:49 jrst-0.8.1/lib/looks-1.2.2.jar 121070 11-30-07 09:49 jrst-0.8.1/lib/junit-3.8.1.jar 358085 11-30-07 09:49 jrst-0.8.1/lib/log4j-1.2.12.jar 72150 11-30-07 09:49 jrst-0.8.1/lib/logkit-1.0.1.jar 342897 11-30-07 09:49 jrst-0.8.1/lib/lutinwidget-0.9.jar 2160934 11-30-07 09:49 jrst-0.8.1/lib/docbook-xsl-nwalsh-1.71.1.jar 301249 11-30-07 09:49 jrst-0.8.1/lib/xmlgraphics-commons-1.1.jar 68610 11-30-07 09:49 jrst-0.8.1/lib/sdoc-0.5.0-beta.jar 3149655 11-30-07 09:49 jrst-0.8.1/lib/xalan-2.6.0.jar 1010675 11-30-07 09:49 jrst-0.8.1/lib/xercesImpl-2.6.2.jar 194205 11-30-07 09:49 jrst-0.8.1/lib/xml-apis-1.3.02.jar 78440 11-30-07 09:49 jrst-0.8.1/lib/xmlParserAPIs-2.0.2.jar 86249 11-30-07 09:49 jrst-0.8.1/lib/xmlunit-1.1.jar 108874 11-30-07 09:49 jrst-0.8.1/lib/xom-1.0.jar 63966 11-30-07 09:49 jrst-0.8.1/lib/avalon-framework-4.1.3.jar 138228 11-30-07 09:49 jrst-0.8.1/lib/batik-gui-util-1.6-1.jar 216394 11-30-07 09:49 jrst-0.8.1/lib/l2fprod-common-0.1.jar 121689 11-30-07 09:49 jrst-0.8.1/lib/lutinutil-0.26.jar 76687 11-30-07 09:49 jrst-0.8.1/lib/batik-ext-1.6-1.jar 124724 11-30-07 09:49 jrst-0.8.1/lib/xmlParserAPIs-2.6.2.jar </code></pre> <p>As you can see, it is somewhat desirable to not need to do this manually.</p> <p>So far I've only tried AutoJar and ProGuard, both of which were fairly easy to get running. It appears that there's some issue with the constant pool in the JAR files.</p> <p>Apparently jrst is slightly broken, so I'll make a go of fixing it. The <a href="http://en.wikipedia.org/wiki/Apache_Maven" rel="noreferrer">Maven</a> <code>pom.xml</code> file was apparently broken too, so I'll have to fix that before fixing jrst ... I feel like a bug-magnet :-)</p> <hr> <p>Update: I never got around to fixing this application, but I checked out <a href="http://en.wikipedia.org/wiki/Eclipse_%28software%29" rel="noreferrer">Eclipse</a>'s "Runnable JAR export wizard" which is based on a fat JAR. I found this very easy to use for deploying my own code.</p> <p>Some of the other excellent suggestions might be better for builds in a non-Eclipse environment, oss probably should make a nice build using <a href="http://en.wikipedia.org/wiki/Apache_Ant" rel="noreferrer">Ant</a>. (Maven, so far has just given me pain, but others love it.)</p>
[ { "answer_id": 81273, "author": "larsivi", "author_id": 14047, "author_profile": "https://Stackoverflow.com/users/14047", "pm_score": 4, "selected": false, "text": "<p>If you are a <a href=\"http://en.wikipedia.org/wiki/Apache_Maven\" rel=\"nofollow noreferrer\">Maven</a> user, typically...
2008/09/17
[ "https://Stackoverflow.com/questions/81260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12677/" ]
Is there a tool or script which easily merges a bunch of [JAR](http://en.wikipedia.org/wiki/JAR_%28file_format%29) files into one JAR file? A bonus would be to easily set the main-file manifest and make it executable. The concrete case is a [Java restructured text tool](http://jrst.labs.libre-entreprise.org/en/user/functionality.html). I would like to run it with something like: > > java -jar rst.jar > > > As far as I can tell, it has no dependencies which indicates that it shouldn't be an easy single-file tool, but the downloaded ZIP file contains a lot of libraries. ``` 0 11-30-07 10:01 jrst-0.8.1/ 922 11-30-07 09:53 jrst-0.8.1/jrst.bat 898 11-30-07 09:53 jrst-0.8.1/jrst.sh 2675 11-30-07 09:42 jrst-0.8.1/readmeEN.txt 108821 11-30-07 09:59 jrst-0.8.1/jrst-0.8.1.jar 2675 11-30-07 09:42 jrst-0.8.1/readme.txt 0 11-30-07 10:01 jrst-0.8.1/lib/ 81508 11-30-07 09:49 jrst-0.8.1/lib/batik-util-1.6-1.jar 2450757 11-30-07 09:49 jrst-0.8.1/lib/icu4j-2.6.1.jar 559366 11-30-07 09:49 jrst-0.8.1/lib/commons-collections-3.1.jar 83613 11-30-07 09:49 jrst-0.8.1/lib/commons-io-1.3.1.jar 207723 11-30-07 09:49 jrst-0.8.1/lib/commons-lang-2.1.jar 52915 11-30-07 09:49 jrst-0.8.1/lib/commons-logging-1.1.jar 260172 11-30-07 09:49 jrst-0.8.1/lib/commons-primitives-1.0.jar 313898 11-30-07 09:49 jrst-0.8.1/lib/dom4j-1.6.1.jar 1994150 11-30-07 09:49 jrst-0.8.1/lib/fop-0.93-jdk15.jar 55147 11-30-07 09:49 jrst-0.8.1/lib/activation-1.0.2.jar 355030 11-30-07 09:49 jrst-0.8.1/lib/mail-1.3.3.jar 77977 11-30-07 09:49 jrst-0.8.1/lib/servlet-api-2.3.jar 226915 11-30-07 09:49 jrst-0.8.1/lib/jaxen-1.1.1.jar 153253 11-30-07 09:49 jrst-0.8.1/lib/jdom-1.0.jar 50789 11-30-07 09:49 jrst-0.8.1/lib/jewelcli-0.41.jar 324952 11-30-07 09:49 jrst-0.8.1/lib/looks-1.2.2.jar 121070 11-30-07 09:49 jrst-0.8.1/lib/junit-3.8.1.jar 358085 11-30-07 09:49 jrst-0.8.1/lib/log4j-1.2.12.jar 72150 11-30-07 09:49 jrst-0.8.1/lib/logkit-1.0.1.jar 342897 11-30-07 09:49 jrst-0.8.1/lib/lutinwidget-0.9.jar 2160934 11-30-07 09:49 jrst-0.8.1/lib/docbook-xsl-nwalsh-1.71.1.jar 301249 11-30-07 09:49 jrst-0.8.1/lib/xmlgraphics-commons-1.1.jar 68610 11-30-07 09:49 jrst-0.8.1/lib/sdoc-0.5.0-beta.jar 3149655 11-30-07 09:49 jrst-0.8.1/lib/xalan-2.6.0.jar 1010675 11-30-07 09:49 jrst-0.8.1/lib/xercesImpl-2.6.2.jar 194205 11-30-07 09:49 jrst-0.8.1/lib/xml-apis-1.3.02.jar 78440 11-30-07 09:49 jrst-0.8.1/lib/xmlParserAPIs-2.0.2.jar 86249 11-30-07 09:49 jrst-0.8.1/lib/xmlunit-1.1.jar 108874 11-30-07 09:49 jrst-0.8.1/lib/xom-1.0.jar 63966 11-30-07 09:49 jrst-0.8.1/lib/avalon-framework-4.1.3.jar 138228 11-30-07 09:49 jrst-0.8.1/lib/batik-gui-util-1.6-1.jar 216394 11-30-07 09:49 jrst-0.8.1/lib/l2fprod-common-0.1.jar 121689 11-30-07 09:49 jrst-0.8.1/lib/lutinutil-0.26.jar 76687 11-30-07 09:49 jrst-0.8.1/lib/batik-ext-1.6-1.jar 124724 11-30-07 09:49 jrst-0.8.1/lib/xmlParserAPIs-2.6.2.jar ``` As you can see, it is somewhat desirable to not need to do this manually. So far I've only tried AutoJar and ProGuard, both of which were fairly easy to get running. It appears that there's some issue with the constant pool in the JAR files. Apparently jrst is slightly broken, so I'll make a go of fixing it. The [Maven](http://en.wikipedia.org/wiki/Apache_Maven) `pom.xml` file was apparently broken too, so I'll have to fix that before fixing jrst ... I feel like a bug-magnet :-) --- Update: I never got around to fixing this application, but I checked out [Eclipse](http://en.wikipedia.org/wiki/Eclipse_%28software%29)'s "Runnable JAR export wizard" which is based on a fat JAR. I found this very easy to use for deploying my own code. Some of the other excellent suggestions might be better for builds in a non-Eclipse environment, oss probably should make a nice build using [Ant](http://en.wikipedia.org/wiki/Apache_Ant). (Maven, so far has just given me pain, but others love it.)
Eclipse 3.4 JDT's Runnable JAR export wizard. In Eclipse 3.5, this has been extended. Now you can chose how you want to treat your referenced JAR files.
81,268
<p>I have been sick and tired Googling the solution for doing case-insensitive search on Sybase ASE (Sybase data/column names are case sensitive). The Sybase documentation proudly says that there is only one way to do such search which is using the Upper and Lower functions, but the adage goes, it has performance problems. And believe me they are right, if your table has huge data the performance is so awkward you are never gonna use Upper and Lower again. My question to fellow developers is: how do you guys tackle this? </p> <p>P.S. Don't advise to change the sort-order or move to any other Database please, in real world developers don't control the databases.</p>
[ { "answer_id": 81327, "author": "Peter", "author_id": 5189, "author_profile": "https://Stackoverflow.com/users/5189", "pm_score": 1, "selected": false, "text": "<p>If you cannot change the sort-order on the database(best option), then the indexes on unknown case fields will not help. Th...
2008/09/17
[ "https://Stackoverflow.com/questions/81268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15395/" ]
I have been sick and tired Googling the solution for doing case-insensitive search on Sybase ASE (Sybase data/column names are case sensitive). The Sybase documentation proudly says that there is only one way to do such search which is using the Upper and Lower functions, but the adage goes, it has performance problems. And believe me they are right, if your table has huge data the performance is so awkward you are never gonna use Upper and Lower again. My question to fellow developers is: how do you guys tackle this? P.S. Don't advise to change the sort-order or move to any other Database please, in real world developers don't control the databases.
Try creating a `functional index`, like ``` Create Index INDX_MY_SEARCH on TABLE_NAME(LOWER(@MySearch) ```
81,280
<p>The question says it all basically. </p> <p>I want in a </p> <pre><code>class MyClass </code></pre> <p>to listen to a routed event. Can it be done ?</p>
[ { "answer_id": 81578, "author": "tucuxi", "author_id": 15472, "author_profile": "https://Stackoverflow.com/users/15472", "pm_score": 0, "selected": false, "text": "<p>If you can create an <em>inner</em> class of MyClass (call it MyInnerClass) that derives from FrameworkElement while reta...
2008/09/17
[ "https://Stackoverflow.com/questions/81280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5246/" ]
The question says it all basically. I want in a ``` class MyClass ``` to listen to a routed event. Can it be done ?
Actually I wiredup the event the wrong way :| I had ``` EventManager.RegisterClassHandler ( typeof ( MyClass )...... ``` Instead of ``` EventManager.RegisterClassHandler ( typeof ( TheClassThatOwnedTheEvent ) ``` So .. my bad.
81,283
<p>How do people usually detect the MIME type of an uploaded file using ASP.NET?</p>
[ { "answer_id": 81312, "author": "Kinjal Dixit", "author_id": 6629, "author_profile": "https://Stackoverflow.com/users/6629", "pm_score": 6, "selected": true, "text": "<p>in the aspx page:</p>\n\n<pre><code>&lt;asp:FileUpload ID=\"FileUpload1\" runat=\"server\" /&gt;\n</code></pre>\n\n<p>...
2008/09/17
[ "https://Stackoverflow.com/questions/81283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15396/" ]
How do people usually detect the MIME type of an uploaded file using ASP.NET?
in the aspx page: ``` <asp:FileUpload ID="FileUpload1" runat="server" /> ``` in the codebehind (c#): ``` string contentType = FileUpload1.PostedFile.ContentType ```
81,285
<p>I re-image one of my machines regularly; and have a script that I run after the OS install completes to configure my machine; such that it works how I like.</p> <p>I happen to have my data on another drive...and I'd like to add code to my script to change the location of the Documents directory from "C:\Users\bryansh\Documents" to "D:\Users\bryansh\Documents".</p> <p>Does anybody have any insight, before I fire up regmon and really roll up my sleeves?</p>
[ { "answer_id": 81312, "author": "Kinjal Dixit", "author_id": 6629, "author_profile": "https://Stackoverflow.com/users/6629", "pm_score": 6, "selected": true, "text": "<p>in the aspx page:</p>\n\n<pre><code>&lt;asp:FileUpload ID=\"FileUpload1\" runat=\"server\" /&gt;\n</code></pre>\n\n<p>...
2008/09/17
[ "https://Stackoverflow.com/questions/81285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/211367/" ]
I re-image one of my machines regularly; and have a script that I run after the OS install completes to configure my machine; such that it works how I like. I happen to have my data on another drive...and I'd like to add code to my script to change the location of the Documents directory from "C:\Users\bryansh\Documents" to "D:\Users\bryansh\Documents". Does anybody have any insight, before I fire up regmon and really roll up my sleeves?
in the aspx page: ``` <asp:FileUpload ID="FileUpload1" runat="server" /> ``` in the codebehind (c#): ``` string contentType = FileUpload1.PostedFile.ContentType ```
81,294
<pre><code>struct foo { unsigned x:1; } f; printf("%d\n", (int)sizeof(f.x = 1)); </code></pre> <p>What is the expected output and why? Taking the size of a bitfield lvalue directly isn't allowed. But by using the assignment operator, it seems we can still take the size of a bitfield type.</p> <p>What is the "size of a bitfield in bytes"? Is it the size of the storage unit holding the bitfield? Is it the number of bits taken up by the bf rounded up to the nearest byte count?</p> <p>Or is the construct undefined behavior because there is nothing in the standard that answers the above questions? Multiple compilers on the same platform are giving me inconsistent results.</p>
[ { "answer_id": 81348, "author": "Jason Dagit", "author_id": 5113, "author_profile": "https://Stackoverflow.com/users/5113", "pm_score": 0, "selected": false, "text": "<p>Wouldn't</p>\n\n<pre><code>(f.x = 1)\n</code></pre>\n\n<p>be an expression evaluating to true (technically in evaluate...
2008/09/17
[ "https://Stackoverflow.com/questions/81294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` struct foo { unsigned x:1; } f; printf("%d\n", (int)sizeof(f.x = 1)); ``` What is the expected output and why? Taking the size of a bitfield lvalue directly isn't allowed. But by using the assignment operator, it seems we can still take the size of a bitfield type. What is the "size of a bitfield in bytes"? Is it the size of the storage unit holding the bitfield? Is it the number of bits taken up by the bf rounded up to the nearest byte count? Or is the construct undefined behavior because there is nothing in the standard that answers the above questions? Multiple compilers on the same platform are giving me inconsistent results.
You are right, integer promotions aren't applied to the operand of `sizeof`: > > The integer promotions are applied only: as part of the usual arithmetic conversions, to certain argument expressions, to the operands of the unary +, -, and ~ operators, and to both operands of the shift operators, as specified by their respective subclauses. > > > The real question is whether bitfields have their own types. Joseph Myers told me: > > The conclusion > from C90 DRs was that bit-fields have their own types, and from C99 DRs > was to leave whether they have their own types implementation-defined, and > GCC follows the C90 DRs and so the assignment has type int:1 and is not > promoted as an operand of sizeof. > > > This was discussed in [Defect Report #315](http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_315.htm). To summarize: your code is legal but implementation-defined.
81,295
<p>I have a webservice that that uses message layer security with X.509 certificates in WSE 3.0. The service uses a X509v3 policy to sign various elements in the soapheader.</p> <p>I need to do some custom checks on the certificates so I've tried to implement a custom X509SecurityTokenManager and added a section in web.config.</p> <p>When I call the service with my Wseproxy I would expect a error (NotImplementedException) but the call goes trough and, in the example below, "foo" is printed at the console.</p> <p>The question is: What have missed? The binarySecurityTokenManager type in web.config matches the full classname of RDI.Server.X509TokenManager. X509TokenManager inherits from X509SecurityTokenManager (altough methods are just stubs).</p> <pre><code>using System; using System.Xml; using System.Security.Permissions; using System.Security.Cryptography; using Microsoft.Web.Services3; using Microsoft.Web.Services3.Security.Tokens; namespace RDI.Server { [SecurityPermissionAttribute(SecurityAction.Demand,Flags = SecurityPermissionFlag.UnmanagedCode)] public class X509TokenManager : Microsoft.Web.Services3.Security.Tokens.X509SecurityTokenManager { public X509TokenManager() : base() { throw new NotImplementedException("Stub"); } public X509TokenManager(XmlNodeList configData) : base(configData) { throw new NotImplementedException("Stub"); } protected override void AuthenticateToken(X509SecurityToken token) { base.AuthenticateToken(token); throw new NotImplementedException("Stub"); } } } </code></pre> <p>The first few lines of my web.config, edited for brevity</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;configuration&gt;&lt;configSections&gt;&lt;section name="microsoft.web.services3" type="..." /&gt; &lt;/configSections&gt; &lt;microsoft.web.services3&gt; &lt;policy fileName="wse3policyCache.config" /&gt; &lt;security&gt; &lt;binarySecurityTokenManager&gt; &lt;add type="RDI.Server.X509TokenManager" valueType="http://docs.oasis-open.org/..." /&gt; &lt;/binarySecurityTokenManager&gt; &lt;/security&gt; &lt;/microsoft.web.services3&gt;` </code></pre> <p>(Btw, how do one format xml nicely here at stackoverflow?)</p> <pre><code>Administration.AdministrationWse test = new TestConnector.Administration.AdministrationWse(); X509Certificate2 cert = GetCert("RDIDemoUser2"); X509SecurityToken x509Token = new X509SecurityToken(cert); test.SetPolicy("X509"); test.SetClientCredential(x509Token); string message = test.Ping("foo"); Console.WriteLine(message); </code></pre> <p>I'm stuck at .NET 2.0 (VS2005) for the time being so I presume WCF is out of the question, otherwise interoperability isn't a problem, as I will have control of both clients and services in the system.</p>
[ { "answer_id": 81630, "author": "Kieran Benton", "author_id": 5777, "author_profile": "https://Stackoverflow.com/users/5777", "pm_score": 0, "selected": false, "text": "<p>Not particular constructive advice I know, but if I was you I'd get off WSE3.0 as soon as possible. We did some work...
2008/09/17
[ "https://Stackoverflow.com/questions/81295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15406/" ]
I have a webservice that that uses message layer security with X.509 certificates in WSE 3.0. The service uses a X509v3 policy to sign various elements in the soapheader. I need to do some custom checks on the certificates so I've tried to implement a custom X509SecurityTokenManager and added a section in web.config. When I call the service with my Wseproxy I would expect a error (NotImplementedException) but the call goes trough and, in the example below, "foo" is printed at the console. The question is: What have missed? The binarySecurityTokenManager type in web.config matches the full classname of RDI.Server.X509TokenManager. X509TokenManager inherits from X509SecurityTokenManager (altough methods are just stubs). ``` using System; using System.Xml; using System.Security.Permissions; using System.Security.Cryptography; using Microsoft.Web.Services3; using Microsoft.Web.Services3.Security.Tokens; namespace RDI.Server { [SecurityPermissionAttribute(SecurityAction.Demand,Flags = SecurityPermissionFlag.UnmanagedCode)] public class X509TokenManager : Microsoft.Web.Services3.Security.Tokens.X509SecurityTokenManager { public X509TokenManager() : base() { throw new NotImplementedException("Stub"); } public X509TokenManager(XmlNodeList configData) : base(configData) { throw new NotImplementedException("Stub"); } protected override void AuthenticateToken(X509SecurityToken token) { base.AuthenticateToken(token); throw new NotImplementedException("Stub"); } } } ``` The first few lines of my web.config, edited for brevity ``` <?xml version="1.0"?> <configuration><configSections><section name="microsoft.web.services3" type="..." /> </configSections> <microsoft.web.services3> <policy fileName="wse3policyCache.config" /> <security> <binarySecurityTokenManager> <add type="RDI.Server.X509TokenManager" valueType="http://docs.oasis-open.org/..." /> </binarySecurityTokenManager> </security> </microsoft.web.services3>` ``` (Btw, how do one format xml nicely here at stackoverflow?) ``` Administration.AdministrationWse test = new TestConnector.Administration.AdministrationWse(); X509Certificate2 cert = GetCert("RDIDemoUser2"); X509SecurityToken x509Token = new X509SecurityToken(cert); test.SetPolicy("X509"); test.SetClientCredential(x509Token); string message = test.Ping("foo"); Console.WriteLine(message); ``` I'm stuck at .NET 2.0 (VS2005) for the time being so I presume WCF is out of the question, otherwise interoperability isn't a problem, as I will have control of both clients and services in the system.
The problem was located elsewhere. My serverproject was an web-app and some options wasn't available for web-apps just for web-sites. So I made a small web-site project and compared web.configs and noticed that some lines diffed. These lines was in the website web.config but not in my other projekt ``` <soapServerProtocolFactory type="Microsoft.Web.Services3.WseProtocolFactory, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> <soapExtensionImporterTypes> <add type="Microsoft.Web.Services3.Description.WseExtensionImporter, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> </soapExtensionImporterTypes> ``` After I added those lines i got the expected error.
81,306
<p>We're currently having a debate whether it's better to throw faults over a WCF channel, versus passing a message indicating the status or the response from a service.</p> <p>Faults come with built-in support from WCF where by you can use the built-in error handlers and react accordingly. This, however, carries overhead as throwing exceptions in .NET can be quite costly.</p> <p>Messages can contain the necessary information to determine what happened with your service call without the overhead of throwing an exception. It does however need several lines of repetitive code to analyze the message and determine actions following its contents.</p> <p>We took a stab at creating a generic message object we could utilize in our services, and this is what we came up with:</p> <pre><code>public class ReturnItemDTO&lt;T&gt; { [DataMember] public bool Success { get; set; } [DataMember] public string ErrorMessage { get; set; } [DataMember] public T Item { get; set; } } </code></pre> <p>If all my service calls return this item, I can consistently check the "Success" property to determine if all went well. I then have an error message string in the event indicating something went wrong, and a generic item containing a Dto if needed.</p> <p>The exception information will have to be logged away to a central logging service and not passed back from the service.</p> <p>Thoughts? Comments? Ideas? Suggestions?</p> <p><strong>Some further clarification on my question</strong></p> <p>An issue I'm having with fault contracts is communicating business rules.</p> <p>Like, if someone logs in, and their account is locked, how do I communicate that? Their login obviously fails, but it fails due to the reason "Account Locked".</p> <p>So do I:</p> <p>A) use a boolean, throw Fault with message account locked</p> <p>B) return AuthenticatedDTO with relevant information</p>
[ { "answer_id": 81339, "author": "Paul van Brenk", "author_id": 1837197, "author_profile": "https://Stackoverflow.com/users/1837197", "pm_score": 6, "selected": true, "text": "<blockquote>\n <p>This however carries overhead as throwing exceptions in .NET can be quite costly.</p>\n</block...
2008/09/17
[ "https://Stackoverflow.com/questions/81306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15360/" ]
We're currently having a debate whether it's better to throw faults over a WCF channel, versus passing a message indicating the status or the response from a service. Faults come with built-in support from WCF where by you can use the built-in error handlers and react accordingly. This, however, carries overhead as throwing exceptions in .NET can be quite costly. Messages can contain the necessary information to determine what happened with your service call without the overhead of throwing an exception. It does however need several lines of repetitive code to analyze the message and determine actions following its contents. We took a stab at creating a generic message object we could utilize in our services, and this is what we came up with: ``` public class ReturnItemDTO<T> { [DataMember] public bool Success { get; set; } [DataMember] public string ErrorMessage { get; set; } [DataMember] public T Item { get; set; } } ``` If all my service calls return this item, I can consistently check the "Success" property to determine if all went well. I then have an error message string in the event indicating something went wrong, and a generic item containing a Dto if needed. The exception information will have to be logged away to a central logging service and not passed back from the service. Thoughts? Comments? Ideas? Suggestions? **Some further clarification on my question** An issue I'm having with fault contracts is communicating business rules. Like, if someone logs in, and their account is locked, how do I communicate that? Their login obviously fails, but it fails due to the reason "Account Locked". So do I: A) use a boolean, throw Fault with message account locked B) return AuthenticatedDTO with relevant information
> > This however carries overhead as throwing exceptions in .NET can be quite costly. > > > You're serializing and de-serializing objects to XML and sending them over a slow network.. the overhead from throwing an exception is negligable compared to that. I usually stick to throwing exceptions, since they clearly communicate something went wrong and *all* webservice toolkits have a good way of handling them. In your sample I would throw an UnauthorizedAccessException with the message "Account Locked". *Clarification:* The .NET wcf services translate exceptions to FaultContracts by default, but you can change this behaviour. [MSDN:Specifying and Handling Faults in Contracts and Services](http://msdn.microsoft.com/en-us/library/ms733721.aspx)
81,317
<p>I have been making a little toy web application in C# along the lines of Rob Connery's Asp.net MVC storefront.</p> <p>I find that I have a repository interface, call it IFooRepository, with methods, say</p> <pre><code>IQueryable&lt;Foo&gt; GetFoo(); void PersistFoo(Foo foo); </code></pre> <p>And I have three implementations of this: ISqlFooRepository, IFileFooRepostory, and IMockFooRepository.</p> <p>I also have some test cases. What I would like to do, and haven't worked out how to do yet, is to run the same test cases against each of these three implementations, and have a green tick for each test pass on each interface type.</p> <p>e.g.</p> <pre><code>[TestMethod] Public void GetFoo_NotNull_Test() { IFooRepository repository = GetRepository(); var results = repository. GetFoo(); Assert.IsNotNull(results); } </code></pre> <p>I want this test method to be run three times, with some variation in the environment that allows it to get three different kinds of repository. At present I have three cut-and-pasted test classes that differ only in the implementation of the private helper method IFooRepository GetRepository(); Obviously, this is smelly.</p> <p>However, I cannot just remove duplication by consolidating the cut and pasted methods, since they need to be present, public and marked as test for the test to run.</p> <p>I am using the Microsoft testing framework, and would prefer to stay with it if I can. But a suggestion of how to do this in, say, MBUnit would also be of some interest.</p>
[ { "answer_id": 81326, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 2, "selected": false, "text": "<p>In MbUnit, you might be able to use the RowTest attribute to specify parameters on your test.</p>\n\n<pre><code>[RowTest]...
2008/09/17
[ "https://Stackoverflow.com/questions/81317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5599/" ]
I have been making a little toy web application in C# along the lines of Rob Connery's Asp.net MVC storefront. I find that I have a repository interface, call it IFooRepository, with methods, say ``` IQueryable<Foo> GetFoo(); void PersistFoo(Foo foo); ``` And I have three implementations of this: ISqlFooRepository, IFileFooRepostory, and IMockFooRepository. I also have some test cases. What I would like to do, and haven't worked out how to do yet, is to run the same test cases against each of these three implementations, and have a green tick for each test pass on each interface type. e.g. ``` [TestMethod] Public void GetFoo_NotNull_Test() { IFooRepository repository = GetRepository(); var results = repository. GetFoo(); Assert.IsNotNull(results); } ``` I want this test method to be run three times, with some variation in the environment that allows it to get three different kinds of repository. At present I have three cut-and-pasted test classes that differ only in the implementation of the private helper method IFooRepository GetRepository(); Obviously, this is smelly. However, I cannot just remove duplication by consolidating the cut and pasted methods, since they need to be present, public and marked as test for the test to run. I am using the Microsoft testing framework, and would prefer to stay with it if I can. But a suggestion of how to do this in, say, MBUnit would also be of some interest.
Create an abstract class that contains concrete versions of the tests and an abstract GetRepository method which returns IFooRepository. Create three classes that derive from the abstract class, each of which implements GetRepository in a way that returns the appropriate IFooRepository implementation. Add all three classes to your test suite, and you're ready to go. To be able to selectively run the tests for some providers and not others, consider using the MbUnit '[FixtureCategory]' attribute to categorise your tests - suggested categories are 'quick' 'slow' 'db' 'important' and 'unimportant' (The last two are jokes - honest!)
81,323
<p>Is there a way to change the encoding used by the String(byte[]) constructor ?</p> <p>In my own code I use String(byte[],String) to specify the encoding but I am using an external library that I cannot change.</p> <pre><code>String src = "with accents: é à"; byte[] bytes = src.getBytes("UTF-8"); System.out.println("UTF-8 decoded: "+new String(bytes,"UTF-8")); System.out.println("Default decoded: "+new String(bytes)); </code></pre> <p>The output for this is :</p> <pre>UTF-8 decoded: with accents: é à Default decoded: with accents: é à </pre> <p>I have tried changing the system property <code>file.encoding</code> but it does not work.</p>
[ { "answer_id": 81363, "author": "jrudolph", "author_id": 7647, "author_profile": "https://Stackoverflow.com/users/7647", "pm_score": 1, "selected": false, "text": "<p>Quoted from <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/nio/charset/Charset.html\" rel=\"nofollow noreferrer\"...
2008/09/17
[ "https://Stackoverflow.com/questions/81323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7198/" ]
Is there a way to change the encoding used by the String(byte[]) constructor ? In my own code I use String(byte[],String) to specify the encoding but I am using an external library that I cannot change. ``` String src = "with accents: é à"; byte[] bytes = src.getBytes("UTF-8"); System.out.println("UTF-8 decoded: "+new String(bytes,"UTF-8")); System.out.println("Default decoded: "+new String(bytes)); ``` The output for this is : ``` UTF-8 decoded: with accents: é à Default decoded: with accents: é à ``` I have tried changing the system property `file.encoding` but it does not work.
You need to change the locale before launching the JVM; see: [Java, bug ID 4163515](http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=6f932817e77b249681417c21bfaf?bug_id=4163515) Some places seem to imply you can do this by setting the file.encoding variable when launching the JVM, such as ``` java -Dfile.encoding=UTF-8 ... ``` ...but I haven't tried this myself. The safest way is to set an environment variable in the operating system.
81,346
<p>I hope this question is not considered too basic for this forum, but we'll see. I'm wondering how to refactor some code for better performance that is getting run a bunch of times.</p> <p>Say I'm creating a word frequency list, using a Map (probably a HashMap), where each key is a String with the word that's being counted and the value is an Integer that's incremented each time a token of the word is found.</p> <p>In Perl, incrementing such a value would be trivially easy:</p> <pre><code>$map{$word}++; </code></pre> <p>But in Java, it's much more complicated. Here the way I'm currently doing it:</p> <pre><code>int count = map.containsKey(word) ? map.get(word) : 0; map.put(word, count + 1); </code></pre> <p>Which of course relies on the autoboxing feature in the newer Java versions. I wonder if you can suggest a more efficient way of incrementing such a value. Are there even good performance reasons for eschewing the Collections framework and using a something else instead?</p> <p>Update: I've done a test of several of the answers. See below.</p>
[ { "answer_id": 81401, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 1, "selected": false, "text": "<p>The various primitive wrappers, e.g., <code>Integer</code> are immutable so there's really not a more concise way to do w...
2008/09/17
[ "https://Stackoverflow.com/questions/81346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10204/" ]
I hope this question is not considered too basic for this forum, but we'll see. I'm wondering how to refactor some code for better performance that is getting run a bunch of times. Say I'm creating a word frequency list, using a Map (probably a HashMap), where each key is a String with the word that's being counted and the value is an Integer that's incremented each time a token of the word is found. In Perl, incrementing such a value would be trivially easy: ``` $map{$word}++; ``` But in Java, it's much more complicated. Here the way I'm currently doing it: ``` int count = map.containsKey(word) ? map.get(word) : 0; map.put(word, count + 1); ``` Which of course relies on the autoboxing feature in the newer Java versions. I wonder if you can suggest a more efficient way of incrementing such a value. Are there even good performance reasons for eschewing the Collections framework and using a something else instead? Update: I've done a test of several of the answers. See below.
Some test results ----------------- I've gotten a lot of good answers to this question--thanks folks--so I decided to run some tests and figure out which method is actually fastest. The five methods I tested are these: * the "ContainsKey" method that I presented in [the question](https://stackoverflow.com/questions/81346/most-efficient-way-to-increment-a-map-value-in-java) * the "TestForNull" method suggested by Aleksandar Dimitrov * the "AtomicLong" method suggested by Hank Gay * the "Trove" method suggested by jrudolph * the "MutableInt" method suggested by phax.myopenid.com Method ------ Here's what I did... 1. created five classes that were identical except for the differences shown below. Each class had to perform an operation typical of the scenario I presented: opening a 10MB file and reading it in, then performing a frequency count of all the word tokens in the file. Since this took an average of only 3 seconds, I had it perform the frequency count (not the I/O) 10 times. 2. timed the loop of 10 iterations but *not the I/O operation* and recorded the total time taken (in clock seconds) essentially using [Ian Darwin's method in the Java Cookbook](http://books.google.com/books?id=t85jM-ZwTX0C&printsec=frontcover&dq=java+cookbook&sig=ACfU3U1lAe1vnbVUwdIcWeTpaxZi1xVUXQ#PPA734,M1). 3. performed all five tests in series, and then did this another three times. 4. averaged the four results for each method. Results ------- I'll present the results first and the code below for those who are interested. The **ContainsKey** method was, as expected, the slowest, so I'll give the speed of each method in comparison to the speed of that method. * **ContainsKey:** 30.654 seconds (baseline) * **AtomicLong:** 29.780 seconds (1.03 times as fast) * **TestForNull:** 28.804 seconds (1.06 times as fast) * **Trove:** 26.313 seconds (1.16 times as fast) * **MutableInt:** 25.747 seconds (1.19 times as fast) Conclusions ----------- It would appear that only the MutableInt method and the Trove method are significantly faster, in that only they give a performance boost of more than 10%. However, if threading is an issue, AtomicLong might be more attractive than the others (I'm not really sure). I also ran TestForNull with `final` variables, but the difference was negligible. Note that I haven't profiled memory usage in the different scenarios. I'd be happy to hear from anybody who has good insights into how the MutableInt and Trove methods would be likely to affect memory usage. Personally, I find the MutableInt method the most attractive, since it doesn't require loading any third-party classes. So unless I discover problems with it, that's the way I'm most likely to go. The code -------- Here is the crucial code from each method. ### ContainsKey ``` import java.util.HashMap; import java.util.Map; ... Map<String, Integer> freq = new HashMap<String, Integer>(); ... int count = freq.containsKey(word) ? freq.get(word) : 0; freq.put(word, count + 1); ``` ### TestForNull ``` import java.util.HashMap; import java.util.Map; ... Map<String, Integer> freq = new HashMap<String, Integer>(); ... Integer count = freq.get(word); if (count == null) { freq.put(word, 1); } else { freq.put(word, count + 1); } ``` ### AtomicLong ``` import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; ... final ConcurrentMap<String, AtomicLong> map = new ConcurrentHashMap<String, AtomicLong>(); ... map.putIfAbsent(word, new AtomicLong(0)); map.get(word).incrementAndGet(); ``` ### Trove ``` import gnu.trove.TObjectIntHashMap; ... TObjectIntHashMap<String> freq = new TObjectIntHashMap<String>(); ... freq.adjustOrPutValue(word, 1, 1); ``` ### MutableInt ``` import java.util.HashMap; import java.util.Map; ... class MutableInt { int value = 1; // note that we start at 1 since we're counting public void increment () { ++value; } public int get () { return value; } } ... Map<String, MutableInt> freq = new HashMap<String, MutableInt>(); ... MutableInt count = freq.get(word); if (count == null) { freq.put(word, new MutableInt()); } else { count.increment(); } ```
81,350
<p>What are the private IP address ranges?</p>
[ { "answer_id": 81365, "author": "Sargun Dhillon", "author_id": 10432, "author_profile": "https://Stackoverflow.com/users/10432", "pm_score": 6, "selected": true, "text": "<p>You will find the answers to this in <a href=\"http://www.faqs.org/rfcs/rfc1918.html\" rel=\"noreferrer\">RFC 1918...
2008/09/17
[ "https://Stackoverflow.com/questions/81350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11034/" ]
What are the private IP address ranges?
You will find the answers to this in [RFC 1918](http://www.faqs.org/rfcs/rfc1918.html). Though, I have listed them below for you. ``` 10.0.0.0 - 10.255.255.255 (10/8 prefix) 172.16.0.0 - 172.31.255.255 (172.16/12 prefix) 192.168.0.0 - 192.168.255.255 (192.168/16 prefix) ``` It is a common misconception that 169.254.0.0/16 is a private IP address block. This is not true. It is link local, basically it is meant to be only used within networks, but it isn't official RFC1918. Additional information about IPv4 addresses can be found in [RFC 3300](http://www.faqs.org/rfcs/rfc3300.html). On the other hand IPv6 doesn't have an equivalent to RFC1918, but any sort of site-local work should be done in fc00::/7. This is further touched on in [RFC 4193](http://www.faqs.org/rfcs/rfc4193.html).
81,361
<p>I have set up a repository using SVN and uploaded projects. There are multiple users working on these projects. But, not everyone requires access to all projects. I want to set up user permissions for each project.</p> <p>How can I achieve this?</p>
[ { "answer_id": 81396, "author": "Mladen Mihajlovic", "author_id": 11421, "author_profile": "https://Stackoverflow.com/users/11421", "pm_score": 2, "selected": false, "text": "<p>The best way is to set up Apache and to set the access through it. Check the <a href=\"http://svnbook.red-bean...
2008/09/17
[ "https://Stackoverflow.com/questions/81361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15425/" ]
I have set up a repository using SVN and uploaded projects. There are multiple users working on these projects. But, not everyone requires access to all projects. I want to set up user permissions for each project. How can I achieve this?
In your **svn\repos\YourRepo\conf** folder you will find two files, **authz** and **passwd**. These are the two you need to adjust. In the **passwd** file you need to add some usernames and passwords. I assume you have already done this since you have people using it: ``` [users] User1=password1 User2=password2 ``` Then you want to assign permissions accordingly with the **authz** file: Create the conceptual groups you want, and add people to it: ``` [groups] allaccess = user1 someaccess = user2 ``` Then choose what access they have from both the permissions and project level. So let's give our "all access" guys all access from the root: ``` [/] @allaccess = rw ``` But only give our "some access" guys read-only access to some lower level project: ``` [/someproject] @someaccess = r ``` You will also find some simple documentation in the **authz** and **passwd** files.
81,392
<p>If you declare variables of type byte or short and attempt to perform arithmetic operations on these, you receive the error "Type mismatch: cannot convert int to short" (or correspondingly "Type mismatch: cannot convert int to byte"). </p> <pre><code>byte a = 23; byte b = 34; byte c = a + b; </code></pre> <p>In this example, the compile error is on the third line.</p>
[ { "answer_id": 81394, "author": "Brad Richards", "author_id": 7732, "author_profile": "https://Stackoverflow.com/users/7732", "pm_score": 5, "selected": true, "text": "<p>Although the arithmetic operators are defined to operate on any numeric type, according the Java language specificati...
2008/09/17
[ "https://Stackoverflow.com/questions/81392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7732/" ]
If you declare variables of type byte or short and attempt to perform arithmetic operations on these, you receive the error "Type mismatch: cannot convert int to short" (or correspondingly "Type mismatch: cannot convert int to byte"). ``` byte a = 23; byte b = 34; byte c = a + b; ``` In this example, the compile error is on the third line.
Although the arithmetic operators are defined to operate on any numeric type, according the Java language specification (5.6.2 Binary Numeric Promotion), operands of type byte and short are automatically promoted to int before being handed to the operators. To perform arithmetic operations on variables of type byte or short, you must enclose the expression in parentheses (inside of which operations will be carried out as type int), and then cast the result back to the desired type. ``` byte a = 23; byte b = 34; byte c = (byte) (a + b); ``` Here's a follow-on question to the real Java gurus: why? The types byte and short are perfectly fine numeric types. Why does Java not allow direct arithmetic operations on these types? (The answer is not "loss of precision", as there is no apparent reason to convert to int in the first place.) Update: jrudolph suggests that this behavior is based on the operations available in the JVM, specifically, that only full- and double-word operators are implemented. Hence, to operator on bytes and shorts, they must be converted to int.
81,410
<p>I've got a <a href="http://notebooks.readerville.com/" rel="noreferrer">site</a> that provides blog-friendly widgets via JavaScript. These work fine in most circumstances, including self-hosted Wordpress blogs. With blogs hosted at Wordpress.com, however, JavaScript isn't allowed in sidebar text modules. Has anyone seen a workaround for this limitation?</p>
[ { "answer_id": 81505, "author": "matt lohkamp", "author_id": 14026, "author_profile": "https://Stackoverflow.com/users/14026", "pm_score": 4, "selected": true, "text": "<p>you could always petition wp to add your widget to their 'approved' list, but who knows how long that would take. yo...
2008/09/17
[ "https://Stackoverflow.com/questions/81410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6478/" ]
I've got a [site](http://notebooks.readerville.com/) that provides blog-friendly widgets via JavaScript. These work fine in most circumstances, including self-hosted Wordpress blogs. With blogs hosted at Wordpress.com, however, JavaScript isn't allowed in sidebar text modules. Has anyone seen a workaround for this limitation?
you could always petition wp to add your widget to their 'approved' list, but who knows how long that would take. you're talking about a way to circumvent the rules they have in place about posting arbitrary script. myspace javascript exploits in particular have increased awareness of the possibility of such workarounds, so you might have a tough time getting around the restrictions - however, here's a classic ones to try: put the javascript in a weird place, like anywhere that executes a URL. for instance: ``` <div style="background:url('javascript:alert(this);');" /> ``` sometimes the word 'javascript' gets cut out, but occasionally you can sneak it through as java\nscript, or something similar. sometimes quotes get stripped out - try String.fromCharCode(34) to get around that. Also, in general, using eval("codepart1" + "codepart2") to get around restricted words or characters. sneaking in javascript is a tricky business, mostly utilizing unorthodox (possibly un-documented) browser behavior in order to execute arbitrary javascript on a page. Welcome to hacking.
81,448
<p>In Oracle, what is the difference between :</p> <pre><code>CREATE TABLE CLIENT ( NAME VARCHAR2(11 BYTE), ID_CLIENT NUMBER ) </code></pre> <p>and</p> <pre><code>CREATE TABLE CLIENT ( NAME VARCHAR2(11 CHAR), -- or even VARCHAR2(11) ID_CLIENT NUMBER ) </code></pre>
[ { "answer_id": 81465, "author": "Matthias Kestenholz", "author_id": 317346, "author_profile": "https://Stackoverflow.com/users/317346", "pm_score": 5, "selected": false, "text": "<p>One has exactly space for 11 bytes, the other for exactly 11 characters. Some charsets such as Unicode var...
2008/09/17
[ "https://Stackoverflow.com/questions/81448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12388/" ]
In Oracle, what is the difference between : ``` CREATE TABLE CLIENT ( NAME VARCHAR2(11 BYTE), ID_CLIENT NUMBER ) ``` and ``` CREATE TABLE CLIENT ( NAME VARCHAR2(11 CHAR), -- or even VARCHAR2(11) ID_CLIENT NUMBER ) ```
Let us assume the database character set is UTF-8, which is the recommended setting in recent versions of Oracle. In this case, some characters take more than 1 byte to store in the database. If you define the field as `VARCHAR2(11 BYTE)`, Oracle can use up to 11 bytes for storage, but you may not actually be able to store 11 characters in the field, because some of them take more than one byte to store, e.g. non-English characters. By defining the field as `VARCHAR2(11 CHAR)` you tell Oracle it can use enough space to store 11 characters, no matter how many bytes it takes to store each one. A single character may require up to 4 bytes.
81,451
<p>I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through <code>db.TextProperty</code> and <code>db.BlobProperty</code>.</p> <p>I'll be glad anyone can provide code sample (both the client and the server side) on how this can be done.</p>
[ { "answer_id": 81479, "author": "Guido", "author_id": 12388, "author_profile": "https://Stackoverflow.com/users/12388", "pm_score": 1, "selected": false, "text": "<p>You can not store files as there is not a traditional file system. You can only store them in their own DataStore (in a f...
2008/09/17
[ "https://Stackoverflow.com/questions/81451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through `db.TextProperty` and `db.BlobProperty`. I'll be glad anyone can provide code sample (both the client and the server side) on how this can be done.
Here is a complete, working file. I pulled the original from the Google site and modified it to make it slightly more real world. A few things to notice: 1. This code uses the [BlobStore API](http://code.google.com/appengine/docs/python/blobstore/) 2. The purpose of this line in the ServeHandler class is to "fix" the key so that it gets rid of any name mangling that may have occurred in the browser (I didn't observe any in Chrome) ``` blob_key = str(urllib.unquote(blob_key)) ``` 3. The "save\_as" clause at the end of this is important. It will make sure that the file name does not get mangled when it is sent to your browser. Get rid of it to observe what happens. ``` self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True) ``` Good Luck! ``` import os import urllib from google.appengine.ext import blobstore from google.appengine.ext import webapp from google.appengine.ext.webapp import blobstore_handlers from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app class MainHandler(webapp.RequestHandler): def get(self): upload_url = blobstore.create_upload_url('/upload') self.response.out.write('<html><body>') self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url) self.response.out.write("""Upload File: <input type="file" name="file"><br> <input type="submit" name="submit" value="Submit"> </form></body></html>""") for b in blobstore.BlobInfo.all(): self.response.out.write('<li><a href="/serve/%s' % str(b.key()) + '">' + str(b.filename) + '</a>') class UploadHandler(blobstore_handlers.BlobstoreUploadHandler): def post(self): upload_files = self.get_uploads('file') blob_info = upload_files[0] self.redirect('/') class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler): def get(self, blob_key): blob_key = str(urllib.unquote(blob_key)) if not blobstore.get(blob_key): self.error(404) else: self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True) def main(): application = webapp.WSGIApplication( [('/', MainHandler), ('/upload', UploadHandler), ('/serve/([^/]+)?', ServeHandler), ], debug=True) run_wsgi_app(application) if __name__ == '__main__': main() ```
81,512
<p>I have three unordered lists that have been created as Scriptaculous Sortables so that the user can drag items within the lists and also between them:</p> <pre><code>var lists = ["pageitems","rowitems","columnitems"]; Sortable.create("pageitems", { dropOnEmpty: true, containment: lists, constraint: false }); Sortable.create("rowitems", { dropOnEmpty: true, containment: lists, constraint: false }); Sortable.create("columnitems", { dropOnEmpty: true, containment: lists, constraint: false }); </code></pre> <p>How can I make it so that if the user drags all the items out of a list, they're able to put them back again? At the moment it won't allow items to be dragged onto an empty list.</p>
[ { "answer_id": 82201, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 3, "selected": true, "text": "<p>Maybe the empty list has no height, and therefore no droppable area available. If that's the case, perhaps you just need t...
2008/09/17
[ "https://Stackoverflow.com/questions/81512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have three unordered lists that have been created as Scriptaculous Sortables so that the user can drag items within the lists and also between them: ``` var lists = ["pageitems","rowitems","columnitems"]; Sortable.create("pageitems", { dropOnEmpty: true, containment: lists, constraint: false }); Sortable.create("rowitems", { dropOnEmpty: true, containment: lists, constraint: false }); Sortable.create("columnitems", { dropOnEmpty: true, containment: lists, constraint: false }); ``` How can I make it so that if the user drags all the items out of a list, they're able to put them back again? At the moment it won't allow items to be dragged onto an empty list.
Maybe the empty list has no height, and therefore no droppable area available. If that's the case, perhaps you just need to set a minimum height, or some padding on the block.
81,520
<p>How can you suppress the <code>Terminated</code> message that comes up after you kill a process in a bash script?</p> <p>I tried <code>set +bm</code>, but that doesn't work.</p> <p>I know another solution involves calling <code>exec 2&gt; /dev/null</code>, but is that reliable? How do I reset it back so that I can continue to see stderr?</p>
[ { "answer_id": 81539, "author": "Matthias Kestenholz", "author_id": 317346, "author_profile": "https://Stackoverflow.com/users/317346", "pm_score": 3, "selected": false, "text": "<p>Maybe detach the process from the current shell process by calling <code>disown</code>?</p>\n" }, { ...
2008/09/17
[ "https://Stackoverflow.com/questions/81520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14437/" ]
How can you suppress the `Terminated` message that comes up after you kill a process in a bash script? I tried `set +bm`, but that doesn't work. I know another solution involves calling `exec 2> /dev/null`, but is that reliable? How do I reset it back so that I can continue to see stderr?
The short answer is that you can't. Bash always prints the status of foreground jobs. The monitoring flag only applies for background jobs, and only for interactive shells, not scripts. see notify\_of\_job\_status() in jobs.c. As you say, you can redirect so standard error is pointing to /dev/null but then you miss any other error messages. You can make it temporary by doing the redirection in a subshell which runs the script. This leaves the original environment alone. ``` (script 2> /dev/null) ``` which will lose all error messages, but just from that script, not from anything else run in that shell. You can save and restore standard error, by redirecting a new filedescriptor to point there: ``` exec 3>&2 # 3 is now a copy of 2 exec 2> /dev/null # 2 now points to /dev/null script # run script with redirected stderr exec 2>&3 # restore stderr to saved exec 3>&- # close saved version ``` But I wouldn't recommend this -- the only upside from the first one is that it saves a sub-shell invocation, while being more complicated and, possibly even altering the behavior of the script, if the script alters file descriptors. --- **EDIT:** *For more appropriate answer check answer given by [Mark Edgar](https://stackoverflow.com/users/129332/mark-edgar)*
81,521
<p>I have settled a web synchronization between SQLSERVER 2005 as publisher and SQLEXPRESS as suscriber. Web synchro has to be launched manually through IE interface (menu tools/synchronize) and to be selected among available synchronizations.</p> <p>Everything is working fine except that I did not find a way to automate the synchro, which I still have to launch manually. Any idea?</p> <p>I have no idea if this synchro can be launched from SQLEXPRESS by running a specific T-SQL code (in this case my problem could be solved indirectly).</p>
[ { "answer_id": 81539, "author": "Matthias Kestenholz", "author_id": 317346, "author_profile": "https://Stackoverflow.com/users/317346", "pm_score": 3, "selected": false, "text": "<p>Maybe detach the process from the current shell process by calling <code>disown</code>?</p>\n" }, { ...
2008/09/17
[ "https://Stackoverflow.com/questions/81521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11436/" ]
I have settled a web synchronization between SQLSERVER 2005 as publisher and SQLEXPRESS as suscriber. Web synchro has to be launched manually through IE interface (menu tools/synchronize) and to be selected among available synchronizations. Everything is working fine except that I did not find a way to automate the synchro, which I still have to launch manually. Any idea? I have no idea if this synchro can be launched from SQLEXPRESS by running a specific T-SQL code (in this case my problem could be solved indirectly).
The short answer is that you can't. Bash always prints the status of foreground jobs. The monitoring flag only applies for background jobs, and only for interactive shells, not scripts. see notify\_of\_job\_status() in jobs.c. As you say, you can redirect so standard error is pointing to /dev/null but then you miss any other error messages. You can make it temporary by doing the redirection in a subshell which runs the script. This leaves the original environment alone. ``` (script 2> /dev/null) ``` which will lose all error messages, but just from that script, not from anything else run in that shell. You can save and restore standard error, by redirecting a new filedescriptor to point there: ``` exec 3>&2 # 3 is now a copy of 2 exec 2> /dev/null # 2 now points to /dev/null script # run script with redirected stderr exec 2>&3 # restore stderr to saved exec 3>&- # close saved version ``` But I wouldn't recommend this -- the only upside from the first one is that it saves a sub-shell invocation, while being more complicated and, possibly even altering the behavior of the script, if the script alters file descriptors. --- **EDIT:** *For more appropriate answer check answer given by [Mark Edgar](https://stackoverflow.com/users/129332/mark-edgar)*
81,533
<p>I'm currently trying to improve the design of a legacy db and I have the following situation</p> <p>Currently I have a table SalesLead in which we store the the LeadSource.</p> <pre><code>Create Table SalesLead( .... LeadSource varchar(20) .... ) </code></pre> <p>The Lead Sources are helpfully stored in a table.</p> <pre><code>Create Table LeadSource ( LeadSourceId int, /*the PK*/ LeadSource varchar(20) ) </code></pre> <p>And so I just want to Create a foreign key from one to the other and drop the non-normalized column.</p> <p>All standard stuff, I hope.</p> <p>Here is my problem. I can't seem to get away from the issue that instead of writing</p> <pre><code> SELECT * FROM SalesLead Where LeadSource = 'foo' </code></pre> <p>Which is totally unambiguous I now have to write </p> <pre><code>SELECT * FROM SalesLead where FK_LeadSourceID = 1 </code></pre> <p>or </p> <pre><code>SELECT * FROM SalesLead INNER JOIN LeadSource ON SalesLead.FK_LeadSourceID = LeadSource.LeadSourceId where LeadSource.LeadSource = "foo" </code></pre> <p>Which breaks if we ever alter the content of the LeadSource field.</p> <p>In my application when ever I want to alter the value of SalesLead's LeadSource I don't want to update from 1 to 2 (for example) as I don't want to have developers having to remember these <strong>magic numbers</strong>. The ids are arbitrary and should be kept so.</p> <p><strong><em>How do I remove or negate the dependency on them in my app's code?</em></strong></p> <p><strong>Edit</strong> Languages my solution will have to support</p> <ul> <li>.NET 2.0 + 3 (for what its worth asp.net, vb.net and c#)</li> <li>vba (access)</li> <li>db (MSSQL 2000)</li> </ul> <p><strong>Edit 2.0</strong> The join is fine is just that 'foo' may change on request to 'foobar' and I don't want to haul through the queries.</p>
[ { "answer_id": 81553, "author": "LohanJ", "author_id": 11286, "author_profile": "https://Stackoverflow.com/users/11286", "pm_score": 1, "selected": false, "text": "<p>Did you consider an updatable view? Depending on your database server and the integrity of your database design you will ...
2008/09/17
[ "https://Stackoverflow.com/questions/81533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm currently trying to improve the design of a legacy db and I have the following situation Currently I have a table SalesLead in which we store the the LeadSource. ``` Create Table SalesLead( .... LeadSource varchar(20) .... ) ``` The Lead Sources are helpfully stored in a table. ``` Create Table LeadSource ( LeadSourceId int, /*the PK*/ LeadSource varchar(20) ) ``` And so I just want to Create a foreign key from one to the other and drop the non-normalized column. All standard stuff, I hope. Here is my problem. I can't seem to get away from the issue that instead of writing ``` SELECT * FROM SalesLead Where LeadSource = 'foo' ``` Which is totally unambiguous I now have to write ``` SELECT * FROM SalesLead where FK_LeadSourceID = 1 ``` or ``` SELECT * FROM SalesLead INNER JOIN LeadSource ON SalesLead.FK_LeadSourceID = LeadSource.LeadSourceId where LeadSource.LeadSource = "foo" ``` Which breaks if we ever alter the content of the LeadSource field. In my application when ever I want to alter the value of SalesLead's LeadSource I don't want to update from 1 to 2 (for example) as I don't want to have developers having to remember these **magic numbers**. The ids are arbitrary and should be kept so. ***How do I remove or negate the dependency on them in my app's code?*** **Edit** Languages my solution will have to support * .NET 2.0 + 3 (for what its worth asp.net, vb.net and c#) * vba (access) * db (MSSQL 2000) **Edit 2.0** The join is fine is just that 'foo' may change on request to 'foobar' and I don't want to haul through the queries.
If you want to de-normalize the table, simply add the LeadSource (Varchar) column to your SalesLead table, instead of using a FK or an ID. On the other hand, if your language has support for ENUM structures, the "magic numbers" should be safely stored in an enum, so you could: ``` SELECT * FROM SALESLEAD WHERE LeadSouce = (int) EnmLeadSource.Foo; //pseudocode ``` And your code will have a ``` public enum EnmLeadSource { Foo = 1, Bar = 2 } ``` It is OK to remove some excessive normalization if this causes you more trouble than what it fixes. However, bear in mind that if you use a VARCHAR field (as oposed to a Magic Number) you must maintain consistency and it could be hard to localize later if you need multiple languages or cultures. The best approach after Normalization seems to be the usage of an Enum structure. It keeps the code clean and you can always pass enums across methods and functions. (I'm assuming .NET here but in other languages as well) **Update**: Since you're using .NET, the DB Backend is "irrelevant" if you're constructing a query through code. Imagine this function: ``` public void GiveMeSalesLeadGiven( EnmLeadSource thisLeadSource ) { // Construct your string using the value of thisLeadSource } ``` In the table you'll have a LeadSource (INT) column. But the fact that it has 1,2 or N won't matter to you. If you later need to change foo to foobar, that can mean that: 1) All the "number 1" have to be number "2". You'll have to update the table. 2) Or You need Foo to now be number 2 and Bar number 1. You just change the Enum (but make sure that the table values remain consistent). The Enum is a very useful structure if properly used. Hope this helps.
81,556
<p>Opening an Infopath form with parameter can be done like this:</p> <pre><code>System.Diagnostics.Process.Start(PathToInfopath + "infopath.exe", "Template.xsn /InputParameters Id=123"); </code></pre> <p>But that requires I know the path to Infopath.exe which changes with each version of Office. Is there a way to simply launch the template and pass a parameter? Or is there a standard way to find where Infopath.exe resides?</p>
[ { "answer_id": 82291, "author": "Steve", "author_id": 15526, "author_profile": "https://Stackoverflow.com/users/15526", "pm_score": 1, "selected": false, "text": "<p>Play around with System.Diagnostics.ProcessStartInfo which allows you to specify a file you wish to open and also allows y...
2008/09/17
[ "https://Stackoverflow.com/questions/81556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Opening an Infopath form with parameter can be done like this: ``` System.Diagnostics.Process.Start(PathToInfopath + "infopath.exe", "Template.xsn /InputParameters Id=123"); ``` But that requires I know the path to Infopath.exe which changes with each version of Office. Is there a way to simply launch the template and pass a parameter? Or is there a standard way to find where Infopath.exe resides?
Play around with System.Diagnostics.ProcessStartInfo which allows you to specify a file you wish to open and also allows you to specify arguments. You can then use Process.Start(ProcessStartInfo) to kick off the process. The framework will determine which application to run based on the file specified in the ProcessStartInfo. I don't have Infopath installed so I unfortunately can't try it out. But hopefully it helps you out a little.
81,589
<p>My workplace has sales people using a 3rd party desktop application that connects directly the a Sql Server and the software is leaving hundreds of sleeping connections for each user. Is there anyway to clear these connection programmatically?</p>
[ { "answer_id": 83416, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Which version of SQL Server do you run? You can write a stored procedure to do this, looking at the data from sp_who and the...
2008/09/17
[ "https://Stackoverflow.com/questions/81589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5802/" ]
My workplace has sales people using a 3rd party desktop application that connects directly the a Sql Server and the software is leaving hundreds of sleeping connections for each user. Is there anyway to clear these connection programmatically?
Which version of SQL Server do you run? You can write a stored procedure to do this, looking at the data from sp\_who and then making some guess about the last activity. There's a "LastBatch" column that does the last time something was submitted by this user. I'd say if that is over an hour old (or whatever interval), execute a KILL for that SPID. You could do this in SQL 2005 like this: ``` declare @spid int , @cmd varchar(200) declare Mycurs cursor for select spid from master..sysprocesses where status = 'sleeping' and last_batch > dateadd( s, -1, getdate()) open mycurs fetch next from mycurs into @spid while @@fetch_status = 0 begin select @cmd = 'kill ' + cast(@spid as varchar) exec(@cmd ) fetch next from mycurs into @spid end deallocate MyCurs ```
81,627
<p>I am using Qt Dialogs in one of my application. I need to hide/delete the help button. But i am not able to locate where exactly I get the handle to his help button. Not sure if its a particular flag on the Qt window.</p>
[ { "answer_id": 81927, "author": "amos", "author_id": 15429, "author_profile": "https://Stackoverflow.com/users/15429", "pm_score": 7, "selected": true, "text": "<p>By default the <em>Qt::WindowContextHelpButtonHint</em> flag is added to dialogs.\nYou can control this with the <em>WindowF...
2008/09/17
[ "https://Stackoverflow.com/questions/81627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11212/" ]
I am using Qt Dialogs in one of my application. I need to hide/delete the help button. But i am not able to locate where exactly I get the handle to his help button. Not sure if its a particular flag on the Qt window.
By default the *Qt::WindowContextHelpButtonHint* flag is added to dialogs. You can control this with the *WindowFlags* parameter to the dialog constructor. For instance you can specify only the *TitleHint* and *SystemMenu* flags by doing: ``` QDialog *d = new QDialog(0, Qt::WindowSystemMenuHint | Qt::WindowTitleHint); d->exec(); ``` If you add the *Qt::WindowContextHelpButtonHint* flag you will get the help button back. In PyQt you can do: ``` from PyQt4 import QtGui, QtCore app = QtGui.QApplication([]) d = QtGui.QDialog(None, QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint) d.exec_() ``` More details on window flags can be found on the [WindowType enum](https://doc.qt.io/qt-5.7/qt.html#WindowType-enum) in the Qt documentation.
81,628
<p>I'd like to build a query string based on values taken from 5 groups of radio buttons.</p> <p>Selecting any of the groups is optional so you could pick set A or B or both. How would I build the querystring based on this? I'm using VB.NET 1.1</p> <p>The asp:Radiobuttonlist control does not like null values so I'm resorting to normal html radio buttons. My question is how do I string up the selected values into a querystring</p> <p>I have something like this right now:</p> <p>HTML:</p> <pre><code>&lt;input type="radio" name="apBoat" id="Apb1" value="1" /&gt; detail1 &lt;input type="radio" name="apBoat" id="Apb2" value="2" /&gt; detail2 &lt;input type="radio" name="cBoat" id="Cb1" value="1" /&gt; detail1 &lt;input type="radio" name="cBoat" id="Cb2" value="2" /&gt; detail2 </code></pre> <p>VB.NET</p> <pre><code>Public Sub btnSubmit_click(ByVal sender As Object, ByVal e As System.EventArgs) Dim queryString As String = "nextpage.aspx?" Dim aBoat, bBoat, cBoat bas String aBoat = "apb=" &amp; Request("aBoat") bBoat = "bBoat=" &amp; Request("bBoat") cBoat = "cBoat=" &amp; Request("cBoat ") queryString += aBoat &amp; bBoat &amp; cBoat Response.Redirect(queryString) End Sub </code></pre> <p>Is this the best way to build the query string or should I take a different approach altogether? Appreciate all the help I can get. Thanks much.</p>
[ { "answer_id": 81678, "author": "Jon", "author_id": 12261, "author_profile": "https://Stackoverflow.com/users/12261", "pm_score": 0, "selected": false, "text": "<p>You could use StringBuilder instead of creating those three different strings. You can help it out by preallocating about ho...
2008/09/17
[ "https://Stackoverflow.com/questions/81628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12232/" ]
I'd like to build a query string based on values taken from 5 groups of radio buttons. Selecting any of the groups is optional so you could pick set A or B or both. How would I build the querystring based on this? I'm using VB.NET 1.1 The asp:Radiobuttonlist control does not like null values so I'm resorting to normal html radio buttons. My question is how do I string up the selected values into a querystring I have something like this right now: HTML: ``` <input type="radio" name="apBoat" id="Apb1" value="1" /> detail1 <input type="radio" name="apBoat" id="Apb2" value="2" /> detail2 <input type="radio" name="cBoat" id="Cb1" value="1" /> detail1 <input type="radio" name="cBoat" id="Cb2" value="2" /> detail2 ``` VB.NET ``` Public Sub btnSubmit_click(ByVal sender As Object, ByVal e As System.EventArgs) Dim queryString As String = "nextpage.aspx?" Dim aBoat, bBoat, cBoat bas String aBoat = "apb=" & Request("aBoat") bBoat = "bBoat=" & Request("bBoat") cBoat = "cBoat=" & Request("cBoat ") queryString += aBoat & bBoat & cBoat Response.Redirect(queryString) End Sub ``` Is this the best way to build the query string or should I take a different approach altogether? Appreciate all the help I can get. Thanks much.
The easiest way would be to use a non-server-side <form> tag with the method="get" then when the form was submitted you would automatically get the querystring you are after (and don't forget to add <label> tags and associate them with your radio buttons): ``` <form action="..." method="get"> <input type="radio" name="apBoat" id="Apb1" value="1" /> <label for="Apb1">detail1</label> <input type="radio" name="apBoat" id="Apb2" value="2" /> <label for="Apb2">detail2</label> <input type="radio" name="cBoat" id="Cb1" value="1" /> <label for="Cb1">detail1</label> <input type="radio" name="cBoat" id="Cb2" value="2" /> <label for="Cb2">detail2</label> </form> ```
81,631
<p>I want: all links which not contained filename (not .html, .jpg, .png, .css) redirect with state 301 to directory, for example: <a href="http://mysite.com/article" rel="nofollow noreferrer">http://mysite.com/article</a> -> <a href="http://mysite.com/article/" rel="nofollow noreferrer">http://mysite.com/article/</a> But <a href="http://mysite.com/article/article-15.html" rel="nofollow noreferrer">http://mysite.com/article/article-15.html</a> not redirects. What regulat expression I must write to .htaccess for adding slash to virtual directories?</p>
[ { "answer_id": 81648, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Clarification needed:</p>\n\n<p>Given the url:\n<a href=\"http://server/path/file\" rel=\"nofollow noreferrer\">http://serve...
2008/09/17
[ "https://Stackoverflow.com/questions/81631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13427/" ]
I want: all links which not contained filename (not .html, .jpg, .png, .css) redirect with state 301 to directory, for example: <http://mysite.com/article> -> <http://mysite.com/article/> But <http://mysite.com/article/article-15.html> not redirects. What regulat expression I must write to .htaccess for adding slash to virtual directories?
I think the following might work: ``` RewriteEngine on RewriteCond %{REQUEST_URI} ^/[^\.]+[^/]$ RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1/ [R=301,L] ``` When it comes to mod\_rewrite I can never be sure without testing though...
81,644
<p>I am using mysql++ in order to connect to a MySQL database to perform a bunch of data queries. Due to the fact that the tables I am reading from are constantly being written to, and that I need a consistent view of the data, I lock the tables first. However, MySQL has no concept of 'NOWAIT' in its lock query, thus if the tables are locked by something else that keeps them locked for a long time, my application sits there waiting. What I want it to do is to be able to return and say something like 'Lock could no be obtained' and try again in a few seconds. My general attempt at this timeout is below.</p> <p>If I run this after locking the table on the database, I get the message that the timeout is hit, but I don't know how to then get the mysql_query line to terminate. I'd appreciate any help/ideas!</p> <pre><code> volatile sig_atomic_t success = 1; void catch_alarm(int sig) { cout &lt;&lt; "Timeout reached" &lt;&lt; endl; success = 0; signal(sig,catch_alarm); } // connect to db etc. // *SNIP signal (SIGALRM, catch_alarm); alarm(2); mysql_query(p_connection,"LOCK TABLES XYZ as write"); </code></pre>
[ { "answer_id": 81663, "author": "INS", "author_id": 13136, "author_profile": "https://Stackoverflow.com/users/13136", "pm_score": 0, "selected": false, "text": "<p>You could execute the blocking query in a different thread and never being bothered with the timeout. When some data arrives...
2008/09/17
[ "https://Stackoverflow.com/questions/81644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am using mysql++ in order to connect to a MySQL database to perform a bunch of data queries. Due to the fact that the tables I am reading from are constantly being written to, and that I need a consistent view of the data, I lock the tables first. However, MySQL has no concept of 'NOWAIT' in its lock query, thus if the tables are locked by something else that keeps them locked for a long time, my application sits there waiting. What I want it to do is to be able to return and say something like 'Lock could no be obtained' and try again in a few seconds. My general attempt at this timeout is below. If I run this after locking the table on the database, I get the message that the timeout is hit, but I don't know how to then get the mysql\_query line to terminate. I'd appreciate any help/ideas! ``` volatile sig_atomic_t success = 1; void catch_alarm(int sig) { cout << "Timeout reached" << endl; success = 0; signal(sig,catch_alarm); } // connect to db etc. // *SNIP signal (SIGALRM, catch_alarm); alarm(2); mysql_query(p_connection,"LOCK TABLES XYZ as write"); ```
You can implement a "cancel-like" behavior this way: You execute the query on a separate thread, that keeps running whether or not the timeout occurs. The timeout occurs on the main thread, and sets a variable to "1" marking that it occurred. Then you do whatever you want to do on your main thread. The query thread, once the query completes, checks if the timeout has occurred. If it hasn't, it does the rest of the work it needs to do. If it HAS, it just unlocks the tables it just locked. I know it sounds a bit wasteful, but the lock-unlock period should be basically instantaneous, and you get as close to the result you want as possible.
81,674
<p>I am looking for an easy way to check if an object in C# is serializable.</p> <p>As we know you make an object serializable by either implementing the <em>ISerializable</em> interface or by placing the <em>[Serializable]</em> at the top of the class.</p> <p>What I am looking for is a quick way to check this without having to reflect the class to get it's attributes. The interface would be quick using an <em>is</em> statement.</p> <p>Using @Flard's suggestion this is the code that I have come up with, scream is there is a better way.</p> <pre><code>private static bool IsSerializable(T obj) { return ((obj is ISerializable) || (Attribute.IsDefined(typeof (T), typeof (SerializableAttribute)))); } </code></pre> <p>Or even better just get the type of the object and then use the IsSerializable property on the type:</p> <pre><code>typeof(T).IsSerializable </code></pre> <p>Remember though this this seems to only just the class that we are dealing with if the class contains other classes you probably want to check them all or try and serialize and wait for errors as @pb pointed out.</p>
[ { "answer_id": 81705, "author": "Grad van Horck", "author_id": 12569, "author_profile": "https://Stackoverflow.com/users/12569", "pm_score": 3, "selected": false, "text": "<pre><code>Attribute.IsDefined(typeof (YourClass), typeof (SerializableAttribute));\n</code></pre>\n\n<p>Probably in...
2008/09/17
[ "https://Stackoverflow.com/questions/81674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/231/" ]
I am looking for an easy way to check if an object in C# is serializable. As we know you make an object serializable by either implementing the *ISerializable* interface or by placing the *[Serializable]* at the top of the class. What I am looking for is a quick way to check this without having to reflect the class to get it's attributes. The interface would be quick using an *is* statement. Using @Flard's suggestion this is the code that I have come up with, scream is there is a better way. ``` private static bool IsSerializable(T obj) { return ((obj is ISerializable) || (Attribute.IsDefined(typeof (T), typeof (SerializableAttribute)))); } ``` Or even better just get the type of the object and then use the IsSerializable property on the type: ``` typeof(T).IsSerializable ``` Remember though this this seems to only just the class that we are dealing with if the class contains other classes you probably want to check them all or try and serialize and wait for errors as @pb pointed out.
You have a lovely property on the `Type` class called `IsSerializable`.
81,686
<p>We have a NET app that gets installed to the Program Files folder. The app itself writes some files and creates some directories to its app folder. But when a normal windows user tries to use our application it crashes because that user does not have permission to write to app folder. Is there any folder in both WinXP and WinVista to which all users have writing permissions by default? All User folder or something like that?</p>
[ { "answer_id": 81738, "author": "RickL", "author_id": 7261, "author_profile": "https://Stackoverflow.com/users/7261", "pm_score": 0, "selected": false, "text": "<p>I'm not sure that there is a single path to which all non-administrator users have permission to write to.</p>\n\n<p>I think...
2008/09/17
[ "https://Stackoverflow.com/questions/81686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15528/" ]
We have a NET app that gets installed to the Program Files folder. The app itself writes some files and creates some directories to its app folder. But when a normal windows user tries to use our application it crashes because that user does not have permission to write to app folder. Is there any folder in both WinXP and WinVista to which all users have writing permissions by default? All User folder or something like that?
There is no such folder. But you can create one. There is CSIDL\_COMMON\_APPDATA which in Vista maps to %ProgramData% (c:\ProgramData) and in XP maps to c:\Documents and Settings\AllUsers\Application Data Feel free to create a folder there in your installer and set the ACL so that everyone can write to that folder. Keep in mind that COMMON\_APPDATA was implemented in Version 5 of the common controls library which means that it's available in Windows 2000 and later. In NT4, you can create that folder in your installation directory and in Windows 98 and below it doesn't matter anyways due to these systems not having a permission system anyways. Here is some sample InnoSetup code to create that folder: ``` [Dirs] Name: {code:getDBPath}; Flags: uninsalwaysuninstall; Permissions: authusers-modify [Code] function getDBPath(Param: String): String; var Version: TWindowsVersion; begin Result := ExpandConstant('{app}\data'); GetWindowsVersionEx(Version); if (Version.Major >= 5) then begin Result := ExpandConstant('{commonappdata}\myprog'); end; end; ```
81,698
<p>Are the any task tracking systems with command-line interface? </p> <p>Here is a list of features I'm interested in:</p> <ul> <li>Simple task template<br> Something like plain-text file with property:type pairs, for example:</li> </ul> <blockquote> <pre><code>description:string some-property:integer required </code></pre> </blockquote> <ul> <li>command line interface<br> for example: </li> </ul> <blockquote> <pre><code>// Creates task &lt;task tracker&gt;.exe -create {description: "Foo", some-property: 1} // Search for tasks with description field starting from F &lt;task tracker&gt;.exe -find { description: "F*" } </code></pre> </blockquote> <ul> <li><p>XCopy deployment<br> It should not require to install heavy DBMS</p></li> <li><p>Multiple users support<br> So it's not just a to-do list for a single person</p></li> </ul>
[ { "answer_id": 81758, "author": "Peter Hilton", "author_id": 2670, "author_profile": "https://Stackoverflow.com/users/2670", "pm_score": 3, "selected": false, "text": "<p>Interesting idea; the closest thing I have heard of is <a href=\"http://todotxt.com/\" rel=\"noreferrer\">todo.txt</a...
2008/09/17
[ "https://Stackoverflow.com/questions/81698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1196/" ]
Are the any task tracking systems with command-line interface? Here is a list of features I'm interested in: * Simple task template Something like plain-text file with property:type pairs, for example: > > > ``` > description:string > some-property:integer required > > ``` > > * command line interface for example: > > > ``` > // Creates task > <task tracker>.exe -create {description: "Foo", some-property: 1} > // Search for tasks with description field starting from F > <task tracker>.exe -find { description: "F*" } > > ``` > > * XCopy deployment It should not require to install heavy DBMS * Multiple users support So it's not just a to-do list for a single person
> > Ditz is a simple, light-weight distributed issue tracker designed to work > with distributed version control systems like darcs and git. > > > Ditz: <http://web.archive.org/web/20121212202849/http://gitorious.org/ditz> Also cloned here: <https://github.com/jashmenn/ditz>
81,716
<p>I am trying to use MinGW to compile a C program under Windows XP. The gcc.exe gives the following error:</p> <p><strong>stdio.h : No such file or directory</strong></p> <p>The code (hello.c) looks like this:</p> <pre><code>#include &lt; stdio.h &gt; void main() { printf("\nHello World\n"); } </code></pre> <p>I use a batch file to call gcc. The batch file looks like this:</p> <pre><code>@echo off set OLDPATH=%PATH% set path=C:\devtools\MinGW\bin;%PATH% set LIBRARY_PATH=C:\devtools\MinGW\lib set C_INCLUDE_PATH=C:\devtools\MinGW\include gcc.exe hello.c set path=%OLDPATH% </code></pre> <p>I have tried the option <strong>-I</strong> without effect. What do I do wrong?</p>
[ { "answer_id": 81731, "author": "Leigh Caldwell", "author_id": 3267, "author_profile": "https://Stackoverflow.com/users/3267", "pm_score": 4, "selected": true, "text": "<p>Try changing the first line to:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n</code></pre>\n\n<p>without the spaces. ...
2008/09/17
[ "https://Stackoverflow.com/questions/81716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3565/" ]
I am trying to use MinGW to compile a C program under Windows XP. The gcc.exe gives the following error: **stdio.h : No such file or directory** The code (hello.c) looks like this: ``` #include < stdio.h > void main() { printf("\nHello World\n"); } ``` I use a batch file to call gcc. The batch file looks like this: ``` @echo off set OLDPATH=%PATH% set path=C:\devtools\MinGW\bin;%PATH% set LIBRARY_PATH=C:\devtools\MinGW\lib set C_INCLUDE_PATH=C:\devtools\MinGW\include gcc.exe hello.c set path=%OLDPATH% ``` I have tried the option **-I** without effect. What do I do wrong?
Try changing the first line to: ``` #include <stdio.h> ``` without the spaces. It is trying to look for a file called " stdio.h " with a space at the beginning and end.
81,723
<p>I have the concept of <code>NodeType</code>s and <code>Node</code>s. A <code>NodeType</code> is a bunch of meta-data which you can create <code>Node</code> instances from (a lot like the whole Class / Object relationship).</p> <p>I have various <code>NodeType</code> implementations and various Node implementations. </p> <p>In my AbstractNodeType (top level for NodeTypes) I have ab abstract <code>createInstance()</code> method that will, once implemented by the subclass, creates the correct Node instance:</p> <pre><code>public abstract class AbstractNodeType { // .. public abstract &lt;T extends AbstractNode&gt; T createInstance(); } </code></pre> <p>In my <code>NodeType</code> implementations I implement the method like this:</p> <pre><code>public class ThingType { // .. public Thing createInstance() { return new Thing(/* .. */); } } // FYI public class Thing extends AbstractNode { /* .. */ } </code></pre> <p>This is all well and good, but <code>public Thing createInstance()</code> creates a warning about type safety. Specifically:</p> <blockquote> <p>Type safety: The return type Thing for createInstance() from the type ThingType needs unchecked conversion to conform to T from the type AbstractNodeType</p> </blockquote> <p><strong>What am I doing wrong to cause such a warning?</strong></p> <p><strong>How can I re-factor my code to fix this?</strong></p> <p><em><code>@SuppressWarnings("unchecked")</code> is not good, I wish to fix this by coding it correctly, not ignoring the problem!</em></p>
[ { "answer_id": 81742, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 3, "selected": true, "text": "<p>You can just replace <code>&lt;T extends AbstractNode&gt; T</code> with <code>AbstractNode</code> thanks to the magic of <...
2008/09/17
[ "https://Stackoverflow.com/questions/81723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1666/" ]
I have the concept of `NodeType`s and `Node`s. A `NodeType` is a bunch of meta-data which you can create `Node` instances from (a lot like the whole Class / Object relationship). I have various `NodeType` implementations and various Node implementations. In my AbstractNodeType (top level for NodeTypes) I have ab abstract `createInstance()` method that will, once implemented by the subclass, creates the correct Node instance: ``` public abstract class AbstractNodeType { // .. public abstract <T extends AbstractNode> T createInstance(); } ``` In my `NodeType` implementations I implement the method like this: ``` public class ThingType { // .. public Thing createInstance() { return new Thing(/* .. */); } } // FYI public class Thing extends AbstractNode { /* .. */ } ``` This is all well and good, but `public Thing createInstance()` creates a warning about type safety. Specifically: > > Type safety: The return type Thing for > createInstance() from the type > ThingType needs unchecked conversion > to conform to T from the type > AbstractNodeType > > > **What am I doing wrong to cause such a warning?** **How can I re-factor my code to fix this?** *`@SuppressWarnings("unchecked")` is not good, I wish to fix this by coding it correctly, not ignoring the problem!*
You can just replace `<T extends AbstractNode> T` with `AbstractNode` thanks to the magic of [covariant returns](http://en.wikipedia.org/wiki/Covariant_return_type). `Java 5` added support, but it didn't receive the pub it deserved.
81,730
<p>In .NET, after this code, what mechanism stops the <code>Thread</code> object from being garbage collected?</p> <pre><code>new Thread(Foo).Start(); GC.Collect(); </code></pre> <p>Yes, it's safe to assume <strong>something</strong> has a reference to the thread, I was just wandering what exactly. For some reason Reflector doesn't show me <code>System.Threading</code>, so I can't dig it myself (I know MS released the source code for the .NET framework, I just don't have it handy).</p>
[ { "answer_id": 81739, "author": "Jon", "author_id": 12261, "author_profile": "https://Stackoverflow.com/users/12261", "pm_score": 0, "selected": false, "text": "<p>Well, it's safe to assume that if a thread is running somewhere that something has a reference to it so wouldn't that be eno...
2008/09/17
[ "https://Stackoverflow.com/questions/81730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ]
In .NET, after this code, what mechanism stops the `Thread` object from being garbage collected? ``` new Thread(Foo).Start(); GC.Collect(); ``` Yes, it's safe to assume **something** has a reference to the thread, I was just wandering what exactly. For some reason Reflector doesn't show me `System.Threading`, so I can't dig it myself (I know MS released the source code for the .NET framework, I just don't have it handy).
The runtime keeps a reference to the thread as long as it is running. The GC wont collect it as long as anyone still keeps that reference.
81,768
<p>I have a Yahoo map with lots of markers (~500). The map performs well enough until I close the page, at which point it pauses (in Firefox) and brings up a "Stop running this script?" dialog (in IE7). If given long enough the script does complete its work.</p> <p>Is there anything I can do to reduce this delay?</p> <p>This stripped down code exhibits the problem:</p> <pre><code>&lt;script type="text/javascript"&gt; var map = new YMap(document.getElementById('map')); map.drawZoomAndCenter("Algeria", 17); for (var i = 0; i &lt; 500; i += 1) { var geoPoint = new YGeoPoint((Math.random()-0.5)*180.0, (Math.random()-0.5)*360.0); var marker = new YMarker(geoPoint); map.addOverlay(marker); } &lt;/script&gt; </code></pre> <p>I'm aware of some memory leaks with the event handlers if you're dynamically adding and removing markers, but these are static (though the problem may be related). Oh, and I <em>know</em> this many markers on a map may not be the best way to convey the data, but that's not the answer I'm looking for ;)</p> <p><strong>Edit:</strong> Following a suggestion below I've tried:</p> <pre><code>window.onbeforeunload = function() { map.removeMarkersAll(); } </code></pre> <p>and </p> <pre><code>window.onbeforeunload = function() { mapElement = document.getElementById('map'); mapElement.parentNode.removeChild(mapElement); } </code></pre> <p>but neither worked :(</p>
[ { "answer_id": 83328, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "<p>You could try removing all the markers, or even removing the map from the DOM using the \"onbeforeunl...
2008/09/17
[ "https://Stackoverflow.com/questions/81768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4914/" ]
I have a Yahoo map with lots of markers (~500). The map performs well enough until I close the page, at which point it pauses (in Firefox) and brings up a "Stop running this script?" dialog (in IE7). If given long enough the script does complete its work. Is there anything I can do to reduce this delay? This stripped down code exhibits the problem: ``` <script type="text/javascript"> var map = new YMap(document.getElementById('map')); map.drawZoomAndCenter("Algeria", 17); for (var i = 0; i < 500; i += 1) { var geoPoint = new YGeoPoint((Math.random()-0.5)*180.0, (Math.random()-0.5)*360.0); var marker = new YMarker(geoPoint); map.addOverlay(marker); } </script> ``` I'm aware of some memory leaks with the event handlers if you're dynamically adding and removing markers, but these are static (though the problem may be related). Oh, and I *know* this many markers on a map may not be the best way to convey the data, but that's not the answer I'm looking for ;) **Edit:** Following a suggestion below I've tried: ``` window.onbeforeunload = function() { map.removeMarkersAll(); } ``` and ``` window.onbeforeunload = function() { mapElement = document.getElementById('map'); mapElement.parentNode.removeChild(mapElement); } ``` but neither worked :(
Use Javascript profiler and see which function is slow. Then you'll have better idea how to make a workaround or at least how to remove expensive cleanup (and let it leak in IE6).
81,788
<p>I couldn't find a decent ThreadPool implementation for Ruby, so I wrote mine (based partly on code from here: <a href="http://web.archive.org/web/20081204101031/http://snippets.dzone.com:80/posts/show/3276" rel="nofollow noreferrer">http://web.archive.org/web/20081204101031/http://snippets.dzone.com:80/posts/show/3276</a> , but changed to wait/signal and other implementation for ThreadPool shutdown. However after some time of running (having 100 threads and handling about 1300 tasks), it dies with deadlock on line 25 - it waits for a new job there. Any ideas, why it might happen?</p> <pre><code>require 'thread' begin require 'fastthread' rescue LoadError $stderr.puts "Using the ruby-core thread implementation" end class ThreadPool class Worker def initialize(callback) @mutex = Mutex.new @cv = ConditionVariable.new @callback = callback @mutex.synchronize {@running = true} @thread = Thread.new do while @mutex.synchronize {@running} block = get_block if block block.call reset_block # Signal the ThreadPool that this worker is ready for another job @callback.signal else # Wait for a new job @mutex.synchronize {@cv.wait(@mutex)} # &lt;=== Is this line 25? end end end end def name @thread.inspect end def get_block @mutex.synchronize {@block} end def set_block(block) @mutex.synchronize do raise RuntimeError, "Thread already busy." if @block @block = block # Signal the thread in this class, that there's a job to be done @cv.signal end end def reset_block @mutex.synchronize {@block = nil} end def busy? @mutex.synchronize {!@block.nil?} end def stop @mutex.synchronize {@running = false} # Signal the thread not to wait for a new job @cv.signal @thread.join end end attr_accessor :max_size def initialize(max_size = 10) @max_size = max_size @workers = [] @mutex = Mutex.new @cv = ConditionVariable.new end def size @mutex.synchronize {@workers.size} end def busy? @mutex.synchronize {@workers.any? {|w| w.busy?}} end def shutdown @mutex.synchronize {@workers.each {|w| w.stop}} end alias :join :shutdown def process(block=nil,&amp;blk) block = blk if block_given? while true @mutex.synchronize do worker = get_worker if worker return worker.set_block(block) else # Wait for a free worker @cv.wait(@mutex) end end end end # Used by workers to report ready status def signal @cv.signal end private def get_worker free_worker || create_worker end def free_worker @workers.each {|w| return w unless w.busy?}; nil end def create_worker return nil if @workers.size &gt;= @max_size worker = Worker.new(self) @workers &lt;&lt; worker worker end end </code></pre>
[ { "answer_id": 82034, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 1, "selected": false, "text": "<p>I'm slightly biased here, but I would suggest modelling this in some process language and model check it. Freely availabl...
2008/09/17
[ "https://Stackoverflow.com/questions/81788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12695/" ]
I couldn't find a decent ThreadPool implementation for Ruby, so I wrote mine (based partly on code from here: <http://web.archive.org/web/20081204101031/http://snippets.dzone.com:80/posts/show/3276> , but changed to wait/signal and other implementation for ThreadPool shutdown. However after some time of running (having 100 threads and handling about 1300 tasks), it dies with deadlock on line 25 - it waits for a new job there. Any ideas, why it might happen? ``` require 'thread' begin require 'fastthread' rescue LoadError $stderr.puts "Using the ruby-core thread implementation" end class ThreadPool class Worker def initialize(callback) @mutex = Mutex.new @cv = ConditionVariable.new @callback = callback @mutex.synchronize {@running = true} @thread = Thread.new do while @mutex.synchronize {@running} block = get_block if block block.call reset_block # Signal the ThreadPool that this worker is ready for another job @callback.signal else # Wait for a new job @mutex.synchronize {@cv.wait(@mutex)} # <=== Is this line 25? end end end end def name @thread.inspect end def get_block @mutex.synchronize {@block} end def set_block(block) @mutex.synchronize do raise RuntimeError, "Thread already busy." if @block @block = block # Signal the thread in this class, that there's a job to be done @cv.signal end end def reset_block @mutex.synchronize {@block = nil} end def busy? @mutex.synchronize {!@block.nil?} end def stop @mutex.synchronize {@running = false} # Signal the thread not to wait for a new job @cv.signal @thread.join end end attr_accessor :max_size def initialize(max_size = 10) @max_size = max_size @workers = [] @mutex = Mutex.new @cv = ConditionVariable.new end def size @mutex.synchronize {@workers.size} end def busy? @mutex.synchronize {@workers.any? {|w| w.busy?}} end def shutdown @mutex.synchronize {@workers.each {|w| w.stop}} end alias :join :shutdown def process(block=nil,&blk) block = blk if block_given? while true @mutex.synchronize do worker = get_worker if worker return worker.set_block(block) else # Wait for a free worker @cv.wait(@mutex) end end end end # Used by workers to report ready status def signal @cv.signal end private def get_worker free_worker || create_worker end def free_worker @workers.each {|w| return w unless w.busy?}; nil end def create_worker return nil if @workers.size >= @max_size worker = Worker.new(self) @workers << worker worker end end ```
Ok, so the main problem with the implementation is: how to make sure no signal is lost and avoid dead locks ? In my experience, this is REALLY hard to achieve with condition variables and mutex, but easy with semaphores. It so happens that ruby implement an object called Queue (or SizedQueue) that should solve the problem. Here is my suggested implementation: ``` require 'thread' begin require 'fasttread' rescue LoadError $stderr.puts "Using the ruby-core thread implementation" end class ThreadPool class Worker def initialize(thread_queue) @mutex = Mutex.new @cv = ConditionVariable.new @queue = thread_queue @running = true @thread = Thread.new do @mutex.synchronize do while @running @cv.wait(@mutex) block = get_block if block @mutex.unlock block.call @mutex.lock reset_block end @queue << self end end end end def name @thread.inspect end def get_block @block end def set_block(block) @mutex.synchronize do raise RuntimeError, "Thread already busy." if @block @block = block # Signal the thread in this class, that there's a job to be done @cv.signal end end def reset_block @block = nil end def busy? @mutex.synchronize { !@block.nil? } end def stop @mutex.synchronize do @running = false @cv.signal end @thread.join end end attr_accessor :max_size def initialize(max_size = 10) @max_size = max_size @queue = Queue.new @workers = [] end def size @workers.size end def busy? @queue.size < @workers.size end def shutdown @workers.each { |w| w.stop } @workers = [] end alias :join :shutdown def process(block=nil,&blk) block = blk if block_given? worker = get_worker worker.set_block(block) end private def get_worker if !@queue.empty? or @workers.size == @max_size return @queue.pop else worker = Worker.new(@queue) @workers << worker worker end end end ``` And here is a simple test code: ``` tp = ThreadPool.new 500 (1..1000).each { |i| tp.process { (2..10).inject(1) { |memo,val| sleep(0.1); memo*val }; print "Computation #{i} done. Nb of tasks: #{tp.size}\n" } } tp.shutdown ```
81,870
<p>For example:</p> <pre><code>int a = 12; cout &lt;&lt; typeof(a) &lt;&lt; endl; </code></pre> <p>Expected output:</p> <pre><code>int </code></pre>
[ { "answer_id": 81886, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 8, "selected": false, "text": "<p>Try:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;typeinfo&gt;\n\n// …\nstd::cout &lt;&lt...
2008/09/17
[ "https://Stackoverflow.com/questions/81870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6508/" ]
For example: ``` int a = 12; cout << typeof(a) << endl; ``` Expected output: ``` int ```
C++11 update to a very old question: Print variable type in C++. The accepted (and good) answer is to use `typeid(a).name()`, where `a` is a variable name. Now in C++11 we have `decltype(x)`, which can turn an expression into a type. And `decltype()` comes with its own set of very interesting rules. For example `decltype(a)` and `decltype((a))` will generally be different types (and for good and understandable reasons once those reasons are exposed). Will our trusty `typeid(a).name()` help us explore this brave new world? No. But the tool that will is not that complicated. And it is that tool which I am using as an answer to this question. I will compare and contrast this new tool to `typeid(a).name()`. And this new tool is actually built on top of `typeid(a).name()`. **The fundamental issue:** ``` typeid(a).name() ``` throws away cv-qualifiers, references, and lvalue/rvalue-ness. For example: ``` const int ci = 0; std::cout << typeid(ci).name() << '\n'; ``` For me outputs: ``` i ``` and I'm guessing on MSVC outputs: ``` int ``` I.e. the `const` is gone. This is not a QOI (Quality Of Implementation) issue. The standard mandates this behavior. What I'm recommending below is: ``` template <typename T> std::string type_name(); ``` which would be used like this: ``` const int ci = 0; std::cout << type_name<decltype(ci)>() << '\n'; ``` and for me outputs: ``` int const ``` `<disclaimer>` I have not tested this on MSVC. `</disclaimer>` But I welcome feedback from those who do. **The C++11 Solution** I am using `__cxa_demangle` for non-MSVC platforms as recommend by [ipapadop](https://stackoverflow.com/users/487362/ipapadop) in his answer to demangle types. But on MSVC I'm trusting `typeid` to demangle names (untested). And this core is wrapped around some simple testing that detects, restores and reports cv-qualifiers and references to the input type. ``` #include <type_traits> #include <typeinfo> #ifndef _MSC_VER # include <cxxabi.h> #endif #include <memory> #include <string> #include <cstdlib> template <class T> std::string type_name() { typedef typename std::remove_reference<T>::type TR; std::unique_ptr<char, void(*)(void*)> own ( #ifndef _MSC_VER abi::__cxa_demangle(typeid(TR).name(), nullptr, nullptr, nullptr), #else nullptr, #endif std::free ); std::string r = own != nullptr ? own.get() : typeid(TR).name(); if (std::is_const<TR>::value) r += " const"; if (std::is_volatile<TR>::value) r += " volatile"; if (std::is_lvalue_reference<T>::value) r += "&"; else if (std::is_rvalue_reference<T>::value) r += "&&"; return r; } ``` **The Results** With this solution I can do this: ``` int& foo_lref(); int&& foo_rref(); int foo_value(); int main() { int i = 0; const int ci = 0; std::cout << "decltype(i) is " << type_name<decltype(i)>() << '\n'; std::cout << "decltype((i)) is " << type_name<decltype((i))>() << '\n'; std::cout << "decltype(ci) is " << type_name<decltype(ci)>() << '\n'; std::cout << "decltype((ci)) is " << type_name<decltype((ci))>() << '\n'; std::cout << "decltype(static_cast<int&>(i)) is " << type_name<decltype(static_cast<int&>(i))>() << '\n'; std::cout << "decltype(static_cast<int&&>(i)) is " << type_name<decltype(static_cast<int&&>(i))>() << '\n'; std::cout << "decltype(static_cast<int>(i)) is " << type_name<decltype(static_cast<int>(i))>() << '\n'; std::cout << "decltype(foo_lref()) is " << type_name<decltype(foo_lref())>() << '\n'; std::cout << "decltype(foo_rref()) is " << type_name<decltype(foo_rref())>() << '\n'; std::cout << "decltype(foo_value()) is " << type_name<decltype(foo_value())>() << '\n'; } ``` and the output is: ``` decltype(i) is int decltype((i)) is int& decltype(ci) is int const decltype((ci)) is int const& decltype(static_cast<int&>(i)) is int& decltype(static_cast<int&&>(i)) is int&& decltype(static_cast<int>(i)) is int decltype(foo_lref()) is int& decltype(foo_rref()) is int&& decltype(foo_value()) is int ``` Note (for example) the difference between `decltype(i)` and `decltype((i))`. The former is the type of the *declaration* of `i`. The latter is the "type" of the *expression* `i`. (expressions never have reference type, but as a convention `decltype` represents lvalue expressions with lvalue references). Thus this tool is an excellent vehicle just to learn about `decltype`, in addition to exploring and debugging your own code. In contrast, if I were to build this just on `typeid(a).name()`, without adding back lost cv-qualifiers or references, the output would be: ``` decltype(i) is int decltype((i)) is int decltype(ci) is int decltype((ci)) is int decltype(static_cast<int&>(i)) is int decltype(static_cast<int&&>(i)) is int decltype(static_cast<int>(i)) is int decltype(foo_lref()) is int decltype(foo_rref()) is int decltype(foo_value()) is int ``` I.e. Every reference and cv-qualifier is stripped off. **C++14 Update** Just when you think you've got a solution to a problem nailed, someone always comes out of nowhere and shows you a much better way. :-) [This answer](https://stackoverflow.com/a/35943472/576911) from [Jamboree](https://stackoverflow.com/users/2969631/jamboree) shows how to get the type name in C++14 at compile time. It is a brilliant solution for a couple reasons: 1. It's at compile time! 2. You get the compiler itself to do the job instead of a library (even a std::lib). This means more accurate results for the latest language features (like lambdas). [Jamboree's](https://stackoverflow.com/users/2969631/jamboree) [answer](https://stackoverflow.com/a/35943472/576911) doesn't quite lay everything out for VS, and I'm tweaking his code a little bit. But since this answer gets a lot of views, take some time to go over there and upvote his answer, without which, this update would never have happened. ``` #include <cstddef> #include <stdexcept> #include <cstring> #include <ostream> #ifndef _MSC_VER # if __cplusplus < 201103 # define CONSTEXPR11_TN # define CONSTEXPR14_TN # define NOEXCEPT_TN # elif __cplusplus < 201402 # define CONSTEXPR11_TN constexpr # define CONSTEXPR14_TN # define NOEXCEPT_TN noexcept # else # define CONSTEXPR11_TN constexpr # define CONSTEXPR14_TN constexpr # define NOEXCEPT_TN noexcept # endif #else // _MSC_VER # if _MSC_VER < 1900 # define CONSTEXPR11_TN # define CONSTEXPR14_TN # define NOEXCEPT_TN # elif _MSC_VER < 2000 # define CONSTEXPR11_TN constexpr # define CONSTEXPR14_TN # define NOEXCEPT_TN noexcept # else # define CONSTEXPR11_TN constexpr # define CONSTEXPR14_TN constexpr # define NOEXCEPT_TN noexcept # endif #endif // _MSC_VER class static_string { const char* const p_; const std::size_t sz_; public: typedef const char* const_iterator; template <std::size_t N> CONSTEXPR11_TN static_string(const char(&a)[N]) NOEXCEPT_TN : p_(a) , sz_(N-1) {} CONSTEXPR11_TN static_string(const char* p, std::size_t N) NOEXCEPT_TN : p_(p) , sz_(N) {} CONSTEXPR11_TN const char* data() const NOEXCEPT_TN {return p_;} CONSTEXPR11_TN std::size_t size() const NOEXCEPT_TN {return sz_;} CONSTEXPR11_TN const_iterator begin() const NOEXCEPT_TN {return p_;} CONSTEXPR11_TN const_iterator end() const NOEXCEPT_TN {return p_ + sz_;} CONSTEXPR11_TN char operator[](std::size_t n) const { return n < sz_ ? p_[n] : throw std::out_of_range("static_string"); } }; inline std::ostream& operator<<(std::ostream& os, static_string const& s) { return os.write(s.data(), s.size()); } template <class T> CONSTEXPR14_TN static_string type_name() { #ifdef __clang__ static_string p = __PRETTY_FUNCTION__; return static_string(p.data() + 31, p.size() - 31 - 1); #elif defined(__GNUC__) static_string p = __PRETTY_FUNCTION__; # if __cplusplus < 201402 return static_string(p.data() + 36, p.size() - 36 - 1); # else return static_string(p.data() + 46, p.size() - 46 - 1); # endif #elif defined(_MSC_VER) static_string p = __FUNCSIG__; return static_string(p.data() + 38, p.size() - 38 - 7); #endif } ``` This code will auto-backoff on the `constexpr` if you're still stuck in ancient C++11. And if you're painting on the cave wall with C++98/03, the `noexcept` is sacrificed as well. **C++17 Update** In the comments below [Lyberta](https://stackoverflow.com/users/3624760/lyberta) points out that the new `std::string_view` can replace `static_string`: ``` template <class T> constexpr std::string_view type_name() { using namespace std; #ifdef __clang__ string_view p = __PRETTY_FUNCTION__; return string_view(p.data() + 34, p.size() - 34 - 1); #elif defined(__GNUC__) string_view p = __PRETTY_FUNCTION__; # if __cplusplus < 201402 return string_view(p.data() + 36, p.size() - 36 - 1); # else return string_view(p.data() + 49, p.find(';', 49) - 49); # endif #elif defined(_MSC_VER) string_view p = __FUNCSIG__; return string_view(p.data() + 84, p.size() - 84 - 7); #endif } ``` I've updated the constants for VS thanks to the very nice detective work by Jive Dadson in the comments below. Update: ------- Be sure to check out [this](https://stackoverflow.com/a/56766138/576911) rewrite or [this](https://stackoverflow.com/a/64490578/576911) rewrite below which eliminate the unreadable magic numbers in my latest formulation.
81,896
<p>I have a script that works fine on my test server (using IIS6). The script processes an ajax request and sends a response with the following line:</p> <pre><code>header( 'application/javascript' ); </code></pre> <p>But on my live server, this line crashes the page and causes a 500 error.</p> <p>Do I need to allow PHP to send different MIME types in IIS7? If so, how do I do this? I can't find any way on the interface.</p>
[ { "answer_id": 81940, "author": "Sietse", "author_id": 6400, "author_profile": "https://Stackoverflow.com/users/6400", "pm_score": 8, "selected": true, "text": "<p>The header is incorrect, try this instead:</p>\n\n<pre><code>header('Content-Type: application/javascript');\n</code></pre>\...
2008/09/17
[ "https://Stackoverflow.com/questions/81896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15567/" ]
I have a script that works fine on my test server (using IIS6). The script processes an ajax request and sends a response with the following line: ``` header( 'application/javascript' ); ``` But on my live server, this line crashes the page and causes a 500 error. Do I need to allow PHP to send different MIME types in IIS7? If so, how do I do this? I can't find any way on the interface.
The header is incorrect, try this instead: ``` header('Content-Type: application/javascript'); ```
81,905
<p>I have a table in my database the records start and stop times for a specific task. Here is a sample of the data:</p> <pre><code>Start Stop 9/15/2008 5:59:46 PM 9/15/2008 6:26:28 PM 9/15/2008 6:30:45 PM 9/15/2008 6:40:49 PM 9/16/2008 8:30:45 PM 9/15/2008 9:20:29 PM 9/16/2008 12:30:45 PM 12/31/9999 12:00:00 AM </code></pre> <p>I would like to write a script that totals up the elapsed minutes for these time frames, and wherever there is a 12/31/9999 date, I want it to use the current date and time, as this is still in progress.</p> <p>How would I do this using Transact-SQL?</p>
[ { "answer_id": 81928, "author": "Paul van Brenk", "author_id": 1837197, "author_profile": "https://Stackoverflow.com/users/1837197", "pm_score": 0, "selected": false, "text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/ms189794.aspx\" rel=\"nofollow noreferrer\">datediff fu...
2008/09/17
[ "https://Stackoverflow.com/questions/81905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768/" ]
I have a table in my database the records start and stop times for a specific task. Here is a sample of the data: ``` Start Stop 9/15/2008 5:59:46 PM 9/15/2008 6:26:28 PM 9/15/2008 6:30:45 PM 9/15/2008 6:40:49 PM 9/16/2008 8:30:45 PM 9/15/2008 9:20:29 PM 9/16/2008 12:30:45 PM 12/31/9999 12:00:00 AM ``` I would like to write a script that totals up the elapsed minutes for these time frames, and wherever there is a 12/31/9999 date, I want it to use the current date and time, as this is still in progress. How would I do this using Transact-SQL?
``` SELECT SUM( CASE WHEN Stop = '31 dec 9999' THEN DateDiff(mi, Start, Stop) ELSE DateDiff(mi, Start, GetDate()) END ) AS TotalMinutes FROM task ``` However, a better solution would be to make the `Stop field nullable, and make it null when the task is still running. That way, you could do this:` ``` SELECT SUM( DateDiff( mi, Start, IsNull(Stop, GetDate() ) ) AS TotalMinutes FROM task ```
81,934
<p>I need a way to easily export and then import data in a MySQL table from a remote server to my home server. I don't have direct access to the server, and no utilities such as phpMyAdmin are installed. I do, however, have the ability to put PHP scripts on the server.</p> <p>How do I get at the data?</p> <p><em>I ask this question purely to record my way to do it</em></p>
[ { "answer_id": 81951, "author": "Jrgns", "author_id": 6681, "author_profile": "https://Stackoverflow.com/users/6681", "pm_score": 4, "selected": false, "text": "<p>I did it by exporting to CSV, and then importing with whatever utility is available. I quite like the use of the php://outpu...
2008/09/17
[ "https://Stackoverflow.com/questions/81934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6681/" ]
I need a way to easily export and then import data in a MySQL table from a remote server to my home server. I don't have direct access to the server, and no utilities such as phpMyAdmin are installed. I do, however, have the ability to put PHP scripts on the server. How do I get at the data? *I ask this question purely to record my way to do it*
You could use SQL for this: ``` $file = 'backups/mytable.sql'; $result = mysql_query("SELECT * INTO OUTFILE '$file' FROM `##table##`"); ``` Then just point a browser or FTP client at the directory/file (backups/mytable.sql). This is also a nice way to do incremental backups, given the filename a timestamp for example. To get it back in to your DataBase from that file you can use: ``` $file = 'backups/mytable.sql'; $result = mysql_query("LOAD DATA INFILE '$file' INTO TABLE `##table##`"); ``` The other option is to use PHP to invoke a system command on the server and run 'mysqldump': ``` $file = 'backups/mytable.sql'; system("mysqldump --opt -h ##databaseserver## -u ##username## -p ##password## ##database | gzip > ".$file); ```
81,972
<p>The question I want to ask is thus:</p> <p>Is casting down the inheritance tree (ie. towards a more specialiased class) from inside an abstract class excusable, or even a good thing, or is it always a poor choice with better options available?</p> <p>Now, the example of why I think it can be used for good.</p> <p>I recently implemented <a href="http://www.bittorrent.org/beps/bep_0003.html#the-connectivity-is-as-follows" rel="nofollow noreferrer">Bencoding from the BitTorrent protocol</a> in C#. A simple enough problem, how to represent the data. I chose to do it this way,</p> <p>We have an <code>abstract BItem</code> class, which provides some basic functionality, including the <code>static BItem Decode(string)</code> that is used to decode a Bencoded string into the necessary structure.</p> <p>There are also four derived classes, <code>BString</code>, <code>BInteger</code>, <code>BList</code> and <code>BDictionary</code>, representing the four different data types that be encoded. Now, here is the tricky part. <code>BList</code> and <code>BDictionary</code> have <code>this[int]</code> and <code>this[string]</code> accessors respectively to allow access to the array-like qualities of these data types.</p> <p>The potentially horrific part is coming now:</p> <pre><code>BDictionary torrent = (BDictionary) BItem.DecodeFile("my.torrent"); int filelength = (BInteger)((BDictionary)((BList)((BDictionary) torrent["info"])["files"])[0])["length"]; </code></pre> <p>Well, you get the picture... Ouch, that's hard on the eyes, not to mention the brain. So, I introduced something extra into the abstract class:</p> <pre><code>public BItem this[int index] { get { return ((BList)this)[index]; } } public BItem this[string index] { get { return ((BDictionary)this)[index]; } } </code></pre> <p>Now we could rewrite that old code as:</p> <pre><code>BDictionary torrent = (BDictionary)BItem.DecodeFile("my.torrent"); int filelength = (BInteger)torrent["info"]["files"][0]["length"]; </code></pre> <p>Wow, hey presto, MUCH more readable code. But did I just sell part of my soul for implying knowledge of subclasses into the abstract class?</p> <p>EDIT: In response to some of the answers coming in, you're completely off track for this particular question since the structure is variable, for instance my example of <code>torrent["info"]["files"][0]["length"]</code> is valid, but so is <code>torrent["announce-list"][0][0]</code>, and both would be in 90% of torrent files out there. Generics isn't the way to go, with this problem atleast :(. Have a click through to the spec I linked, it's only 4 small dot-points large.</p>
[ { "answer_id": 81990, "author": "petr k.", "author_id": 15497, "author_profile": "https://Stackoverflow.com/users/15497", "pm_score": 2, "selected": false, "text": "<p>You really should not access any derived classes from the base class as it pretty much breaks the idea of OOP. Readibili...
2008/09/17
[ "https://Stackoverflow.com/questions/81972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ]
The question I want to ask is thus: Is casting down the inheritance tree (ie. towards a more specialiased class) from inside an abstract class excusable, or even a good thing, or is it always a poor choice with better options available? Now, the example of why I think it can be used for good. I recently implemented [Bencoding from the BitTorrent protocol](http://www.bittorrent.org/beps/bep_0003.html#the-connectivity-is-as-follows) in C#. A simple enough problem, how to represent the data. I chose to do it this way, We have an `abstract BItem` class, which provides some basic functionality, including the `static BItem Decode(string)` that is used to decode a Bencoded string into the necessary structure. There are also four derived classes, `BString`, `BInteger`, `BList` and `BDictionary`, representing the four different data types that be encoded. Now, here is the tricky part. `BList` and `BDictionary` have `this[int]` and `this[string]` accessors respectively to allow access to the array-like qualities of these data types. The potentially horrific part is coming now: ``` BDictionary torrent = (BDictionary) BItem.DecodeFile("my.torrent"); int filelength = (BInteger)((BDictionary)((BList)((BDictionary) torrent["info"])["files"])[0])["length"]; ``` Well, you get the picture... Ouch, that's hard on the eyes, not to mention the brain. So, I introduced something extra into the abstract class: ``` public BItem this[int index] { get { return ((BList)this)[index]; } } public BItem this[string index] { get { return ((BDictionary)this)[index]; } } ``` Now we could rewrite that old code as: ``` BDictionary torrent = (BDictionary)BItem.DecodeFile("my.torrent"); int filelength = (BInteger)torrent["info"]["files"][0]["length"]; ``` Wow, hey presto, MUCH more readable code. But did I just sell part of my soul for implying knowledge of subclasses into the abstract class? EDIT: In response to some of the answers coming in, you're completely off track for this particular question since the structure is variable, for instance my example of `torrent["info"]["files"][0]["length"]` is valid, but so is `torrent["announce-list"][0][0]`, and both would be in 90% of torrent files out there. Generics isn't the way to go, with this problem atleast :(. Have a click through to the spec I linked, it's only 4 small dot-points large.
I think I would make the this[int] and this[string] accessors virtual and override them in BList/BDictionary. Classes where the accessors does not make sense should cast a NotSupportedException() (perhaps by having a default implementation in BItem). That makes your code work in the same way and gives you a more readable error in case you should write ``` (BInteger)torrent["info"][0]["files"]["length"]; ``` by mistake.
82,003
<p>I have a remote DB2 database that I'm accessing through ODBC. When I have a query like</p> <pre><code>SELECT t.foo, t.bar, t.problemcolumn FROM problemtable t WHERE t.bar &lt; 60; </code></pre> <p>it works like a charm, so the table and columns obviously exist.</p> <p>But if I specify the problem column in the WHERE clause</p> <pre><code>SELECT t.foo, t.bar, t.problemcolumn FROM problemtable t WHERE t.problemcolumn = 'x' AND t.bar &lt; 60; </code></pre> <p>it gives me an error </p> <pre><code>Table "problemtable" does not exist. </code></pre> <p>What could possibly be the reason for this? I've double checked the spellings and I can trigger the problem just by including the problemcolumn in the where-clause.</p>
[ { "answer_id": 82070, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 2, "selected": false, "text": "<p>Sorry for the obvious answer, but does the problemtable exist? Your code looks like pseudo code because ...
2008/09/17
[ "https://Stackoverflow.com/questions/82003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2087/" ]
I have a remote DB2 database that I'm accessing through ODBC. When I have a query like ``` SELECT t.foo, t.bar, t.problemcolumn FROM problemtable t WHERE t.bar < 60; ``` it works like a charm, so the table and columns obviously exist. But if I specify the problem column in the WHERE clause ``` SELECT t.foo, t.bar, t.problemcolumn FROM problemtable t WHERE t.problemcolumn = 'x' AND t.bar < 60; ``` it gives me an error ``` Table "problemtable" does not exist. ``` What could possibly be the reason for this? I've double checked the spellings and I can trigger the problem just by including the problemcolumn in the where-clause.
Sorry for the obvious answer, but does the problemtable exist? Your code looks like pseudo code because of the table/column names, but be sure to double check your spelling. It's not a view which might even consist of joined tables across different databases/servers?
82,008
<p>I have xml where some of the element values are unicode characters. Is it possible to represent this in an ANSI encoding?</p> <p>E.g.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;xml&gt; &lt;value&gt;受&lt;/value&gt; &lt;/xml&gt; </code></pre> <p>to</p> <pre><code>&lt;?xml version="1.0" encoding="Windows-1252"?&gt; &lt;xml&gt; &lt;value&gt;&amp;#27544;&lt;/value&gt; &lt;/xml&gt; </code></pre> <p>I deserialize the XML and then attempt to serialize it using XmlTextWriter specifying the Default encoding (Default is Windows-1252). All the unicode characters end up as question marks. I'm using VS 2008, C# 3.5</p>
[ { "answer_id": 82021, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 2, "selected": false, "text": "<p>If I understand the question, then yes. You just need a <code>;</code> after the <code>27544</code>:</p>\n\n<pre><cod...
2008/09/17
[ "https://Stackoverflow.com/questions/82008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9539/" ]
I have xml where some of the element values are unicode characters. Is it possible to represent this in an ANSI encoding? E.g. ``` <?xml version="1.0" encoding="utf-8"?> <xml> <value>受</value> </xml> ``` to ``` <?xml version="1.0" encoding="Windows-1252"?> <xml> <value>&#27544;</value> </xml> ``` I deserialize the XML and then attempt to serialize it using XmlTextWriter specifying the Default encoding (Default is Windows-1252). All the unicode characters end up as question marks. I'm using VS 2008, C# 3.5
Okay I tested it with the following code: ``` string xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><xml><value>受</value></xml>"; XmlWriterSettings settings = new XmlWriterSettings { Encoding = Encoding.Default }; MemoryStream ms = new MemoryStream(); using (XmlWriter writer = XmlTextWriter.Create(ms, settings)) XElement.Parse(xml).WriteTo(writer); string value = Encoding.Default.GetString(ms.ToArray()); ``` And it correctly escaped the unicode character thus: ``` <?xml version="1.0" encoding="Windows-1252"?><xml><value>&#x53D7;</value></xml> ``` I must be doing something wrong somewhere else. Thanks for the help.
82,047
<p>I have a requirement to validate an incoming file against an XSD. Both will be on the server file system.<br /></p> <p>I've looked at <code>dbms_xmlschema</code>, but have had issues getting it to work.</p> <p>Could it be easier to do it with some Java?<br />What's the simplest class I could put in the database?</p> <p>Here's a simple example:</p> <pre><code>DECLARE v_schema_url VARCHAR2(200) := 'http://www.example.com/schema.xsd'; v_blob bLOB; v_clob CLOB; v_xml XMLTYPE; BEGIN begin dbms_xmlschema.deleteschema(v_schema_url); exception when others then null; end; dbms_xmlschema.registerSchema(schemaURL =&gt; v_schema_url, schemaDoc =&gt; ' &lt;xs:schema targetNamespace="http://www.example.com" xmlns:ns="http://www.example.com" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified" version="3.0"&gt; &lt;xs:element name="something" type="xs:string"/&gt; &lt;/xs:schema&gt;', local =&gt; TRUE); v_xml := XMLTYPE.createxml('&lt;something xmlns="http://www.xx.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.com/schema.xsd"&gt; data &lt;/something&gt;'); IF v_xml.isschemavalid(v_schema_url) = 1 THEN dbms_output.put_line('valid'); ELSE dbms_output.put_line('not valid'); END IF; END; </code></pre> <p>This generates the following error:</p> <pre><code>ORA-01031: insufficient privileges ORA-06512: at "XDB.DBMS_XDBZ0", line 275 ORA-06512: at "XDB.DBMS_XDBZ", line 7 ORA-06512: at line 1 ORA-06512: at "XDB.DBMS_XMLSCHEMA_INT", line 3 ORA-06512: at "XDB.DBMS_XMLSCHEMA", line 14 ORA-06512: at line 12 </code></pre>
[ { "answer_id": 83488, "author": "Adam Hawkes", "author_id": 6703, "author_profile": "https://Stackoverflow.com/users/6703", "pm_score": -1, "selected": false, "text": "<p>If I remember correctly, that error message is given when XDB (Oracle's XML DataBase package) is not properly install...
2008/09/17
[ "https://Stackoverflow.com/questions/82047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1895/" ]
I have a requirement to validate an incoming file against an XSD. Both will be on the server file system. I've looked at `dbms_xmlschema`, but have had issues getting it to work. Could it be easier to do it with some Java? What's the simplest class I could put in the database? Here's a simple example: ``` DECLARE v_schema_url VARCHAR2(200) := 'http://www.example.com/schema.xsd'; v_blob bLOB; v_clob CLOB; v_xml XMLTYPE; BEGIN begin dbms_xmlschema.deleteschema(v_schema_url); exception when others then null; end; dbms_xmlschema.registerSchema(schemaURL => v_schema_url, schemaDoc => ' <xs:schema targetNamespace="http://www.example.com" xmlns:ns="http://www.example.com" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified" version="3.0"> <xs:element name="something" type="xs:string"/> </xs:schema>', local => TRUE); v_xml := XMLTYPE.createxml('<something xmlns="http://www.xx.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.com/schema.xsd"> data </something>'); IF v_xml.isschemavalid(v_schema_url) = 1 THEN dbms_output.put_line('valid'); ELSE dbms_output.put_line('not valid'); END IF; END; ``` This generates the following error: ``` ORA-01031: insufficient privileges ORA-06512: at "XDB.DBMS_XDBZ0", line 275 ORA-06512: at "XDB.DBMS_XDBZ", line 7 ORA-06512: at line 1 ORA-06512: at "XDB.DBMS_XMLSCHEMA_INT", line 3 ORA-06512: at "XDB.DBMS_XMLSCHEMA", line 14 ORA-06512: at line 12 ```
**Update** XML Schema registration requires following privileges: ``` grant alter session to <USER>; grant create type to <USER>; /* required when gentypes => true */ grant create table to <USER>; /* required when gentables => true */ ``` For some reason it's not enough if those privileges are granted indirectly via roles, but the privileges need *to be granted directly to schema/user*. **Original Answer** I have also noticed that default values of parameters `gentables` and `gentypes` raise `insufficient privileges` exception. Probably I'm just lacking of some privileges to use those features, but at the moment I don't have a good understanding what they do. I'm just happy to disable them and validation seems to work fine. I'm running on Oracle Database 11g Release 11.2.0.1.0 gentypes => true, gentables => true ----------------------------------- ``` dbms_xmlschema.registerschema(schemaurl => name, schemadoc => xmltype(schema), local => true --gentypes => false, --gentables => false ); ORA-01031: insufficient privileges ORA-06512: at "XDB.DBMS_XMLSCHEMA_INT", line 55 ORA-06512: at "XDB.DBMS_XMLSCHEMA", line 159 ORA-06512: at "JANI.XML_VALIDATOR", line 38 ORA-06512: at line 7 ``` gentypes => false, gentables => true ------------------------------------ ``` dbms_xmlschema.registerschema(schemaurl => name, schemadoc => xmltype(schema), local => true, gentypes => false --gentables => false ); ORA-31084: error while creating table "JANI"."example873_TAB" for element "example" ORA-01031: insufficient privileges ORA-06512: at "XDB.DBMS_XMLSCHEMA_INT", line 55 ORA-06512: at "XDB.DBMS_XMLSCHEMA", line 159 ORA-06512: at "JANI.XML_VALIDATOR", line 38 ORA-06512: at line 7 ``` gentypes => true, gentables => false ------------------------------------ ``` dbms_xmlschema.registerschema(schemaurl => name, schemadoc => xmltype(schema), local => true, --gentypes => false gentables => false ); ORA-01031: insufficient privileges ORA-06512: at "XDB.DBMS_XMLSCHEMA_INT", line 55 ORA-06512: at "XDB.DBMS_XMLSCHEMA", line 159 ORA-06512: at "JANI.XML_VALIDATOR", line 38 ORA-06512: at line 7 ``` gentypes => false, gentables => false ------------------------------------- ``` dbms_xmlschema.registerschema(schemaurl => name, schemadoc => xmltype(schema), local => true, gentypes => false, gentables => false ); PL/SQL procedure successfully completed. ```
82,058
<p>Given the following JSON Date representation:</p> <pre><code>"\/Date(1221644506800-0700)\/" </code></pre> <p>How do you deserialize this into it's JavaScript Date-type form?</p> <p>I've tried using MS AJAX JavaScrioptSerializer as shown below:</p> <pre><code>Sys.Serialization.JavaScriptSerializer.deserialize("\/Date(1221644506800-0700)\/") </code></pre> <p>However, all I get back is the literal string date.</p>
[ { "answer_id": 82244, "author": "Daniel", "author_id": 6852, "author_profile": "https://Stackoverflow.com/users/6852", "pm_score": 1, "selected": false, "text": "<p>The big number is the standard JS time</p>\n\n<pre><code>new Date(1221644506800)\n</code></pre>\n\n<p>Wed Sep 17 2008 19:41...
2008/09/17
[ "https://Stackoverflow.com/questions/82058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9275/" ]
Given the following JSON Date representation: ``` "\/Date(1221644506800-0700)\/" ``` How do you deserialize this into it's JavaScript Date-type form? I've tried using MS AJAX JavaScrioptSerializer as shown below: ``` Sys.Serialization.JavaScriptSerializer.deserialize("\/Date(1221644506800-0700)\/") ``` However, all I get back is the literal string date.
Provided you know the string is definitely a date I prefer to do this : ``` new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10)) ```
82,064
<p>I have a version number of the following form:</p> <p>version.release.modification</p> <p>where version, release and modification are either a set of digits or the '*' wildcard character. Additionally, any of these numbers (and any preceding .) may be missing.</p> <p>So the following are valid and parse as:</p> <pre><code>1.23.456 = version 1, release 23, modification 456 1.23 = version 1, release 23, any modification 1.23.* = version 1, release 23, any modification 1.* = version 1, any release, any modification 1 = version 1, any release, any modification * = any version, any release, any modification </code></pre> <p>But these are not valid:</p> <pre><code>*.12 *123.1 12* 12.*.34 </code></pre> <p>Can anyone provide me a not-too-complex regex to validate and retrieve the release, version and modification numbers?</p>
[ { "answer_id": 82104, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": false, "text": "<p>This might work:</p>\n\n<pre><code>^(\\*|\\d+(\\.\\d+){0,2}(\\.\\*)?)$\n</code></pre>\n\n<p>At the top level, \"*\" is ...
2008/09/17
[ "https://Stackoverflow.com/questions/82064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7271/" ]
I have a version number of the following form: version.release.modification where version, release and modification are either a set of digits or the '\*' wildcard character. Additionally, any of these numbers (and any preceding .) may be missing. So the following are valid and parse as: ``` 1.23.456 = version 1, release 23, modification 456 1.23 = version 1, release 23, any modification 1.23.* = version 1, release 23, any modification 1.* = version 1, any release, any modification 1 = version 1, any release, any modification * = any version, any release, any modification ``` But these are not valid: ``` *.12 *123.1 12* 12.*.34 ``` Can anyone provide me a not-too-complex regex to validate and retrieve the release, version and modification numbers?
I'd express the format as: > > "1-3 dot-separated components, each numeric except that the last one may be \*" > > > As a regexp, that's: ``` ^(\d+\.)?(\d+\.)?(\*|\d+)$ ``` [Edit to add: this solution is a concise way to validate, but it has been pointed out that extracting the values requires extra work. It's a matter of taste whether to deal with this by complicating the regexp, or by processing the matched groups. In my solution, the groups capture the `"."` characters. This can be dealt with using non-capturing groups as in ajborley's answer. Also, the rightmost group will capture the last component, even if there are fewer than three components, and so for example a two-component input results in the first and last groups capturing and the middle one undefined. I think this can be dealt with by non-greedy groups where supported. Perl code to deal with both issues after the regexp could be something like this: ``` @version = (); @groups = ($1, $2, $3); foreach (@groups) { next if !defined; s/\.//; push @version, $_; } ($major, $minor, $mod) = (@version, "*", "*"); ``` Which isn't really any shorter than splitting on `"."` ]
82,074
<p>In a digital signal acquisition system, often data is pushed into an observer in the system by one thread. </p> <p>example from <a href="http://en.wikipedia.org/wiki/Observer_pattern" rel="nofollow noreferrer">Wikipedia/Observer_pattern</a>:</p> <pre><code>foreach (IObserver observer in observers) observer.Update(message); </code></pre> <p>When e.g. a user action from e.g. a GUI-thread requires the data to stop flowing, you want to break the subject-observer connection, and even dispose of the observer alltogether.</p> <p>One may argue: you should just stop the data source, and wait for a sentinel value to dispose of the connection. But that would incur more latency in the system.</p> <p>Of course, if the data pumping thread has just asked for the address of the observer, it might find it's sending a message to a destroyed object.</p> <p>Has someone created an 'official' Design Pattern countering this situation? Shouldn't they?</p>
[ { "answer_id": 82116, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 0, "selected": false, "text": "<p>You could send a message to all observers informing them the data source is terminating and let the observers remove themsel...
2008/09/17
[ "https://Stackoverflow.com/questions/82074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6610/" ]
In a digital signal acquisition system, often data is pushed into an observer in the system by one thread. example from [Wikipedia/Observer\_pattern](http://en.wikipedia.org/wiki/Observer_pattern): ``` foreach (IObserver observer in observers) observer.Update(message); ``` When e.g. a user action from e.g. a GUI-thread requires the data to stop flowing, you want to break the subject-observer connection, and even dispose of the observer alltogether. One may argue: you should just stop the data source, and wait for a sentinel value to dispose of the connection. But that would incur more latency in the system. Of course, if the data pumping thread has just asked for the address of the observer, it might find it's sending a message to a destroyed object. Has someone created an 'official' Design Pattern countering this situation? Shouldn't they?
If you want to have the data source to always be on the safe side of concurrency, you should have at least one pointer that is always safe for him to use. So the Observer object should have a lifetime that isn't ended before that of the data source. This can be done by only adding Observers, but never removing them. You could have each observer not do the core implementation itself, but have it delegate this task to an ObserverImpl object. You lock access to this impl object. This is no big deal, it just means the GUI unsubscriber would be blocked for a little while in case the observer is busy using the ObserverImpl object. If GUI responsiveness would be an issue, you can use some kind of concurrent job-queue mechanism with an unsubscription job pushed onto it. ( like PostMessage in Windows ) When unsubscribing, you just substitute the core implementation for a dummy implementation. Again this operation should grab the lock. This would indeed introduce some waiting for the data source, but since it's just a [ lock - pointer swap - unlock ] you could say that this is fast enough for real-time applications. If you want to avoid stacking Observer objects that just contain a dummy, you have to do some kind of bookkeeping, but this could boil down to something trivial like an object holding a pointer to the Observer object he needs from the list. Optimization : If you also keep the implementations ( the real one + the dummy ) alive as long as the Observer itself, you can do this without an actual lock, and use something like InterlockedExchangePointer to swap the pointers. Worst case scenario : delegating call is going on while pointer is swapped --> no big deal all objects stay alive and delegating can continue. Next delegating call will be to new implementation object. ( Barring any new swaps of course )
82,109
<p>I am using Java 1.4 with Log4J. </p> <p>Some of my code involves serializing and deserializing value objects (POJOs). </p> <p>Each of my POJOs declares a logger with</p> <pre><code>private final Logger log = Logger.getLogger(getClass()); </code></pre> <p>The serializer complains of org.apache.log4j.Logger not being Serializable.</p> <p>Should I use</p> <pre><code>private final transient Logger log = Logger.getLogger(getClass()); </code></pre> <p>instead?</p>
[ { "answer_id": 82130, "author": "mindas", "author_id": 7345, "author_profile": "https://Stackoverflow.com/users/7345", "pm_score": 4, "selected": false, "text": "<p>The logger must be static; this would make it non-serializable.</p>\n\n<p>There's no reason to make logger non-static, unle...
2008/09/17
[ "https://Stackoverflow.com/questions/82109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15452/" ]
I am using Java 1.4 with Log4J. Some of my code involves serializing and deserializing value objects (POJOs). Each of my POJOs declares a logger with ``` private final Logger log = Logger.getLogger(getClass()); ``` The serializer complains of org.apache.log4j.Logger not being Serializable. Should I use ``` private final transient Logger log = Logger.getLogger(getClass()); ``` instead?
How about using a static logger? Or do you need a different logger reference for each instance of the class? Static fields are not serialized by default; you can explicitly declare fields to serialize with a private, static, final array of `ObjectStreamField` named `serialPersistentFields`. [See Oracle documentation](http://java.sun.com/developer/technicalArticles/ALT/serialization/#2) Added content: As you use [getLogger(getClass())](http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Logger.html#getLogger(java.lang.String)), you will use the same logger in each instance. If you want to use separate logger for each instance you have to differentiate on the name of the logger in the getLogger() -method. e.g. getLogger(getClass().getName() + hashCode()). You should then use the transient attribute to make sure that the logger is not serialized.
82,123
<p>I'm new to BIRT and I'm trying to make the Report Engine running. I'm using the code snippets provided in <a href="http://www.eclipse.org/birt/phoenix/deploy/reportEngineAPI.php" rel="nofollow noreferrer">http://www.eclipse.org/birt/phoenix/deploy/reportEngineAPI.php</a></p> <p>But I have a strange exception:</p> <blockquote> <p>java.lang.AssertionError at org.eclipse.birt.core.framework.Platform.startup(Platform.java:86)</p> </blockquote> <p>and nothing in the log file.</p> <p>Maybe I missed something in the configuration? Could somebody give me a hint about what I can try to make it running?</p> <p>Here is the code I'm using:</p> <pre><code>public static void executeReport() { IReportEngine engine=null; EngineConfig config = null; try{ config = new EngineConfig( ); config.setBIRTHome("D:\\birt-runtime-2_3_0\\ReportEngine"); config.setLogConfig("d:/temp", Level.FINEST); Platform.startup( config ); IReportEngineFactory factory = (IReportEngineFactory) Platform .createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY ); engine = factory.createReportEngine( config ); IReportRunnable design = null; //Open the report design design = engine.openReportDesign("D:\\birt-runtime-2_3_0\\ReportEngine\\samples\\hello_world.rptdesign"); IRunAndRenderTask task = engine.createRunAndRenderTask(design); HTMLRenderOption options = new HTMLRenderOption(); options.setOutputFileName("output/resample/Parmdisp.html"); options.setOutputFormat("html"); task.setRenderOption(options); task.run(); task.close(); engine.destroy(); }catch( Exception ex){ ex.printStackTrace(); } finally { Platform.shutdown( ); } } </code></pre>
[ { "answer_id": 82229, "author": "cH1cK3n", "author_id": 15615, "author_profile": "https://Stackoverflow.com/users/15615", "pm_score": 2, "selected": false, "text": "<p>I had the same mistake a couple of month ago. I'm not quite sure what actually fixed it but my code looks like the follo...
2008/09/17
[ "https://Stackoverflow.com/questions/82123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/446104/" ]
I'm new to BIRT and I'm trying to make the Report Engine running. I'm using the code snippets provided in <http://www.eclipse.org/birt/phoenix/deploy/reportEngineAPI.php> But I have a strange exception: > > java.lang.AssertionError > at org.eclipse.birt.core.framework.Platform.startup(Platform.java:86) > > > and nothing in the log file. Maybe I missed something in the configuration? Could somebody give me a hint about what I can try to make it running? Here is the code I'm using: ``` public static void executeReport() { IReportEngine engine=null; EngineConfig config = null; try{ config = new EngineConfig( ); config.setBIRTHome("D:\\birt-runtime-2_3_0\\ReportEngine"); config.setLogConfig("d:/temp", Level.FINEST); Platform.startup( config ); IReportEngineFactory factory = (IReportEngineFactory) Platform .createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY ); engine = factory.createReportEngine( config ); IReportRunnable design = null; //Open the report design design = engine.openReportDesign("D:\\birt-runtime-2_3_0\\ReportEngine\\samples\\hello_world.rptdesign"); IRunAndRenderTask task = engine.createRunAndRenderTask(design); HTMLRenderOption options = new HTMLRenderOption(); options.setOutputFileName("output/resample/Parmdisp.html"); options.setOutputFormat("html"); task.setRenderOption(options); task.run(); task.close(); engine.destroy(); }catch( Exception ex){ ex.printStackTrace(); } finally { Platform.shutdown( ); } } ```
Just a thought, but I wonder if your use of a forward slash when setting the logger is causing a problem? instead of ``` config.setLogConfig("d:/temp", Level.FINEST); ``` you should use ``` config.setLogConfig("/temp", Level.FINEST); ``` or ``` config.setLogConfig("d:\\temp", Level.FINEST); ``` Finally, I realize that this is just some sample code, but you will certainly want to split your platform startup code out from your run and render task. The platform startup is very expensive and should only be done once per session. I have a couple of Eclipse projects that are setup in a Subversion server that demonstrate how to use the Report Engine API (REAPI) and the Design Engine API (DEAPI) that you may find useful as your code gets more complicated. To get the examples you will need either the Subclipse or the Subversive plugins and then you will need to connect to the following repository: ``` http://longlake.minnovent.com/repos/birt_example ``` The projects that you need are: ``` birt_api_example birt_runtime_lib script.lib ``` You may need to adjust some of the file locations in the BirtUtil class, but I think that most file locations are relative path. There is more information about how to use the examples projects on my blog at http:/birtworld.blogspot.com. In particular this article should help: [Testing And Debug of Reports](http://birtworld.blogspot.com/2008/04/testing-and-debug-of-reports.html)
82,191
<p>I'm creating a plugin, and am looking to use RSpec so I can build it using BDD. </p> <p>Is there a recommended method of doing this?</p>
[ { "answer_id": 82680, "author": "Dan Harper", "author_id": 14530, "author_profile": "https://Stackoverflow.com/users/14530", "pm_score": 0, "selected": false, "text": "<p>For an example of an existing plugin that uses rspec, check out the <a href=\"http://github.com/technoweenie/restful...
2008/09/17
[ "https://Stackoverflow.com/questions/82191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12037/" ]
I'm creating a plugin, and am looking to use RSpec so I can build it using BDD. Is there a recommended method of doing this?
OK, I think I have a solution: * Generate the plugin via script/generate plugin * change the Rakefile, and add `require 'spec/rake/spectask'` ``` desc 'Test the PLUGIN_NAME plugin.' Spec::Rake::SpecTask.new(:spec) do |t| t.libs << 'lib' t.verbose = true end ``` * Create a spec directory, and begin adding specs in \*\_spec.rb files, as normal You can also modify the default task to run spec instead of test, too.
82,214
<p>In the early days of SharePoint 2007 beta, I've come across the ability to customize the template used to emit the RSS feeds from lists. I can't find it again. Anybody know where it is?</p>
[ { "answer_id": 82680, "author": "Dan Harper", "author_id": 14530, "author_profile": "https://Stackoverflow.com/users/14530", "pm_score": 0, "selected": false, "text": "<p>For an example of an existing plugin that uses rspec, check out the <a href=\"http://github.com/technoweenie/restful...
2008/09/17
[ "https://Stackoverflow.com/questions/82214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1533/" ]
In the early days of SharePoint 2007 beta, I've come across the ability to customize the template used to emit the RSS feeds from lists. I can't find it again. Anybody know where it is?
OK, I think I have a solution: * Generate the plugin via script/generate plugin * change the Rakefile, and add `require 'spec/rake/spectask'` ``` desc 'Test the PLUGIN_NAME plugin.' Spec::Rake::SpecTask.new(:spec) do |t| t.libs << 'lib' t.verbose = true end ``` * Create a spec directory, and begin adding specs in \*\_spec.rb files, as normal You can also modify the default task to run spec instead of test, too.
82,235
<p>I'm experiencing the following very annoying behaviour when using JPA entitys in conjunction with Oracle 10g. </p> <p>Suppose you have the following entity.</p> <pre><code>@Entity @Table(name = "T_Order") public class TOrder implements Serializable { private static final long serialVersionUID = 2235742302377173533L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @Column(name = "activationDate") private Calendar activationDate; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Calendar getActivationDate() { return activationDate; } public void setActivationDate(Calendar activationDate) { this.activationDate = activationDate; } } </code></pre> <p>This entity is mapped to Oracle 10g, so in the DB there will be a table <code>T_ORDER</code> with a primary key <code>NUMBER</code> column <code>ID</code> and a <code>TIMESTAMP</code> column <code>activationDate</code>.</p> <p>Lets suppose I create an instance of this class with the activation date <code>15. Sep 2008 00:00AM</code>. My local timezone is CEST which is <code>GMT+02:00</code>. When I persist this object and select the data from the table <code>T_ORDER</code> using sqlplus, I find out that in the table actually <code>14. Sep 2008 22:00</code> is stored, which is ok so far, because the oracle db timezone is GMT.</p> <p>But now the annoying part. When I read this entity back into my JAVA program, I find out that the oracle time zone is ignored and I get <code>14. Sep 2008 22:00 CEST</code>, which is definitly wrong. </p> <p>So basically, when writing to the DB the timezone information will be used, when reading it will be ignored.</p> <p>Is there any solution for this out there? The most simple solution I guess would be to set the oracle dbs timezone to <code>GMT+02</code>, but unfortunatly I can't do this because there are other applications using the same server.</p> <p>We use the following technology</p> <p>MyEclipse 6.5 JPA with Hibernate 3.2 Oracle 10g thin JDBC Driver</p>
[ { "answer_id": 82416, "author": "Jeroen Wyseur", "author_id": 15490, "author_profile": "https://Stackoverflow.com/users/15490", "pm_score": 0, "selected": false, "text": "<p>I already had my share of problems with JPA and timestamps. I've been reading in the <a href=\"http://forums.oracl...
2008/09/17
[ "https://Stackoverflow.com/questions/82235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15657/" ]
I'm experiencing the following very annoying behaviour when using JPA entitys in conjunction with Oracle 10g. Suppose you have the following entity. ``` @Entity @Table(name = "T_Order") public class TOrder implements Serializable { private static final long serialVersionUID = 2235742302377173533L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @Column(name = "activationDate") private Calendar activationDate; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Calendar getActivationDate() { return activationDate; } public void setActivationDate(Calendar activationDate) { this.activationDate = activationDate; } } ``` This entity is mapped to Oracle 10g, so in the DB there will be a table `T_ORDER` with a primary key `NUMBER` column `ID` and a `TIMESTAMP` column `activationDate`. Lets suppose I create an instance of this class with the activation date `15. Sep 2008 00:00AM`. My local timezone is CEST which is `GMT+02:00`. When I persist this object and select the data from the table `T_ORDER` using sqlplus, I find out that in the table actually `14. Sep 2008 22:00` is stored, which is ok so far, because the oracle db timezone is GMT. But now the annoying part. When I read this entity back into my JAVA program, I find out that the oracle time zone is ignored and I get `14. Sep 2008 22:00 CEST`, which is definitly wrong. So basically, when writing to the DB the timezone information will be used, when reading it will be ignored. Is there any solution for this out there? The most simple solution I guess would be to set the oracle dbs timezone to `GMT+02`, but unfortunatly I can't do this because there are other applications using the same server. We use the following technology MyEclipse 6.5 JPA with Hibernate 3.2 Oracle 10g thin JDBC Driver
You should not use a Calendar for accessing dates from the database, for this exact reason. You should use `java.util.Date` as so: ``` @Temporal(TemporalType.TIMESTAMP) @Column(name="activationDate") public Date getActivationDate() { return this.activationDate; } ``` `java.util.Date` points to a moment in time, irrespective of any timezones. Calendar can be used to format a date for a particular timezone or locale.
82,256
<p>I've been given sudo access on one of our development RedHat linux boxes, and I seem to find myself quite often needing to redirect output to a location I don't normally have write access to.</p> <p>The trouble is, this contrived example doesn't work:</p> <pre><code>sudo ls -hal /root/ &gt; /root/test.out </code></pre> <p>I just receive the response:</p> <pre><code>-bash: /root/test.out: Permission denied </code></pre> <p>How can I get this to work?</p>
[ { "answer_id": 82274, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>How about writing a script?</p>\n\n<p>Filename: myscript</p>\n\n<pre><code>#!/bin/sh\n\n/bin/ls -lah /root &gt; /root/test.o...
2008/09/17
[ "https://Stackoverflow.com/questions/82256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6910/" ]
I've been given sudo access on one of our development RedHat linux boxes, and I seem to find myself quite often needing to redirect output to a location I don't normally have write access to. The trouble is, this contrived example doesn't work: ``` sudo ls -hal /root/ > /root/test.out ``` I just receive the response: ``` -bash: /root/test.out: Permission denied ``` How can I get this to work?
Your command does not work because the redirection is performed by your shell which does not have the permission to write to `/root/test.out`. The redirection of the output **is not** performed by sudo. There are multiple solutions: * Run a shell with sudo and give the command to it by using the `-c` option: ``` sudo sh -c 'ls -hal /root/ > /root/test.out' ``` * Create a script with your commands and run that script with sudo: ``` #!/bin/sh ls -hal /root/ > /root/test.out ``` Run `sudo ls.sh`. See Steve Bennett's [answer](https://stackoverflow.com/a/16514624/12892) if you don't want to create a temporary file. * Launch a shell with `sudo -s` then run your commands: ``` [nobody@so]$ sudo -s [root@so]# ls -hal /root/ > /root/test.out [root@so]# ^D [nobody@so]$ ``` * Use `sudo tee` (if you have to escape a lot when using the `-c` option): ``` sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null ``` The redirect to `/dev/null` is needed to stop [**tee**](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/tee.html) from outputting to the screen. To *append* instead of overwriting the output file (`>>`), use `tee -a` or `tee --append` (the last one is specific to [GNU coreutils](https://www.gnu.org/software/coreutils/manual/html_node/tee-invocation.html)). Thanks go to [Jd](https://stackoverflow.com/a/82274/12892), [Adam J. Forster](https://stackoverflow.com/a/82279/12892) and [Johnathan](https://stackoverflow.com/a/82553/12892) for the second, third and fourth solutions.
82,268
<p>I have to deal with text files in a motley selection of formats. Here's an example (Columns <strong>A</strong> and <strong>B</strong> are tab delimited):</p> <pre><code>A B a Name1=Val1, Name2=Val2, Name3=Val3 b Name1=Val4, Name3=Val5 c Name1=Val6, Name2=Val7, Name3=Val8 </code></pre> <p>The files could have headers or not, have mixed delimiting schemes, have columns with name/value pairs as above etc.<br> I often have the ad-hoc need to extract data from such files in various ways. For example from the above data I might want the value associated with Name2 where it is present. i.e.</p> <pre><code>A B a Val2 c Val7 </code></pre> <p>What tools/techniques are there for performing such manipulations as one line commands, using the above as an example but extensible to other cases?</p>
[ { "answer_id": 82282, "author": "auramo", "author_id": 4110, "author_profile": "https://Stackoverflow.com/users/4110", "pm_score": 1, "selected": false, "text": "<p>You have all the basic bash shell commands, for example grep, cut, sed and awk at your disposal. You can also use Perl or R...
2008/09/17
[ "https://Stackoverflow.com/questions/82268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6387/" ]
I have to deal with text files in a motley selection of formats. Here's an example (Columns **A** and **B** are tab delimited): ``` A B a Name1=Val1, Name2=Val2, Name3=Val3 b Name1=Val4, Name3=Val5 c Name1=Val6, Name2=Val7, Name3=Val8 ``` The files could have headers or not, have mixed delimiting schemes, have columns with name/value pairs as above etc. I often have the ad-hoc need to extract data from such files in various ways. For example from the above data I might want the value associated with Name2 where it is present. i.e. ``` A B a Val2 c Val7 ``` What tools/techniques are there for performing such manipulations as one line commands, using the above as an example but extensible to other cases?
I don't like sed too much, but it works for such things: ``` var="Name2";sed -n "1p;s/\([^ ]*\) .*$var=\([^ ,]*\).*/\1 \2/p" < filename ``` Gives you: ``` A B a Val2 c Val7 ```
82,319
<p>In the uncompressed situation I know I need to read the wav header, pull out the number of channels, bits, and sample rate and work it out from there: (channels) * (bits) * (samples/s) * (seconds) = (filesize)</p> <p>Is there a simpler way - a free library, or something in the .net framework perhaps?</p> <p>How would I do this if the .wav file is compressed (with the mpeg codec for example)?</p>
[ { "answer_id": 82344, "author": "xan", "author_id": 15667, "author_profile": "https://Stackoverflow.com/users/15667", "pm_score": 1, "selected": false, "text": "<p>You might find that the <a href=\"http://msdn.microsoft.com/en-us/xna/default.aspx\" rel=\"nofollow noreferrer\">XNA library...
2008/09/17
[ "https://Stackoverflow.com/questions/82319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1078/" ]
In the uncompressed situation I know I need to read the wav header, pull out the number of channels, bits, and sample rate and work it out from there: (channels) \* (bits) \* (samples/s) \* (seconds) = (filesize) Is there a simpler way - a free library, or something in the .net framework perhaps? How would I do this if the .wav file is compressed (with the mpeg codec for example)?
You may consider using the mciSendString(...) function (error checking is omitted for clarity): ``` using System; using System.Text; using System.Runtime.InteropServices; namespace Sound { public static class SoundInfo { [DllImport("winmm.dll")] private static extern uint mciSendString( string command, StringBuilder returnValue, int returnLength, IntPtr winHandle); public static int GetSoundLength(string fileName) { StringBuilder lengthBuf = new StringBuilder(32); mciSendString(string.Format("open \"{0}\" type waveaudio alias wave", fileName), null, 0, IntPtr.Zero); mciSendString("status wave length", lengthBuf, lengthBuf.Capacity, IntPtr.Zero); mciSendString("close wave", null, 0, IntPtr.Zero); int length = 0; int.TryParse(lengthBuf.ToString(), out length); return length; } } } ```
82,323
<p>I have a 3 column grid in a window with a GridSplitter on the first column. I want to set the MaxWidth of the first column to a third of the parent Window or Page <code>Width</code> (or <code>ActualWidth</code>) and I would prefer to do this in XAML if possible.</p> <p>This is some sample XAML to play with in XamlPad (or similar) which shows what I'm doing. </p> <pre><code>&lt;Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" &gt; &lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition x:Name="Column1" Width="200"/&gt; &lt;ColumnDefinition x:Name="Column2" MinWidth="50" /&gt; &lt;ColumnDefinition x:Name="Column3" Width="{ Binding ElementName=Column1, Path=Width }"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Label Grid.Column="0" Background="Green" /&gt; &lt;GridSplitter Grid.Column="0" Width="5" /&gt; &lt;Label Grid.Column="1" Background="Yellow" /&gt; &lt;Label Grid.Column="2" Background="Red" /&gt; &lt;/Grid&gt; &lt;/Page&gt; </code></pre> <p>As you can see, the right column width is bound to the width of the first column, so when you slide the left column using the splitter, the right column does the same :) If you slide the left column to the right, eventually it will slide over half the page/window and over to the right side of the window, pushing away column 2 and 3. </p> <p>I want to prevent this by setting the MaxWidth of column 1 to a third of the window width (or something like that). I can do this in code behind quite easily, but how to do it in "XAML Only"?</p> <p><strong><em>EDIT:</strong> David Schmitt suggested to use SharedSizeGroup instead of binding, which is an excellent suggestion. My sample code would look like this then:</em></p> <pre><code>&lt;Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" &gt; &lt;Grid IsSharedSizeScope="True"&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition x:Name="Column1" SharedSizeGroup="ColWidth" Width="40"/&gt; &lt;ColumnDefinition x:Name="Column2" MinWidth="50" Width="*" /&gt; &lt;ColumnDefinition x:Name="Column3" SharedSizeGroup="ColWidth"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Label Grid.Column="0" Background="Green" /&gt; &lt;GridSplitter Grid.Column="0" Width="5" /&gt; &lt;Label Grid.Column="1" Background="Yellow" /&gt; &lt;Label Grid.Column="2" Background="Red" /&gt; &lt;/Grid&gt; &lt;/Page&gt; </code></pre>
[ { "answer_id": 85173, "author": "Thomas", "author_id": 9970, "author_profile": "https://Stackoverflow.com/users/9970", "pm_score": 0, "selected": false, "text": "<p>Too lazy to actually write it up myself, but you should be able to use a mathematical converter and bind to your parent win...
2008/09/17
[ "https://Stackoverflow.com/questions/82323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6415/" ]
I have a 3 column grid in a window with a GridSplitter on the first column. I want to set the MaxWidth of the first column to a third of the parent Window or Page `Width` (or `ActualWidth`) and I would prefer to do this in XAML if possible. This is some sample XAML to play with in XamlPad (or similar) which shows what I'm doing. ``` <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" > <Grid> <Grid.ColumnDefinitions> <ColumnDefinition x:Name="Column1" Width="200"/> <ColumnDefinition x:Name="Column2" MinWidth="50" /> <ColumnDefinition x:Name="Column3" Width="{ Binding ElementName=Column1, Path=Width }"/> </Grid.ColumnDefinitions> <Label Grid.Column="0" Background="Green" /> <GridSplitter Grid.Column="0" Width="5" /> <Label Grid.Column="1" Background="Yellow" /> <Label Grid.Column="2" Background="Red" /> </Grid> </Page> ``` As you can see, the right column width is bound to the width of the first column, so when you slide the left column using the splitter, the right column does the same :) If you slide the left column to the right, eventually it will slide over half the page/window and over to the right side of the window, pushing away column 2 and 3. I want to prevent this by setting the MaxWidth of column 1 to a third of the window width (or something like that). I can do this in code behind quite easily, but how to do it in "XAML Only"? ***EDIT:*** David Schmitt suggested to use SharedSizeGroup instead of binding, which is an excellent suggestion. My sample code would look like this then: ``` <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" > <Grid IsSharedSizeScope="True"> <Grid.ColumnDefinitions> <ColumnDefinition x:Name="Column1" SharedSizeGroup="ColWidth" Width="40"/> <ColumnDefinition x:Name="Column2" MinWidth="50" Width="*" /> <ColumnDefinition x:Name="Column3" SharedSizeGroup="ColWidth"/> </Grid.ColumnDefinitions> <Label Grid.Column="0" Background="Green" /> <GridSplitter Grid.Column="0" Width="5" /> <Label Grid.Column="1" Background="Yellow" /> <Label Grid.Column="2" Background="Red" /> </Grid> </Page> ```
I think the XAML-only approach is somewhat circuitous, but here is a way to do it. ``` <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" > <!-- This contains our real grid, and a reference grid for binding the layout--> <Grid x:Name="Container"> <!-- hidden because it's behind the grid below --> <Grid x:Name="LayoutReference"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <!-- We need the border, because the column doesn't have an ActualWidth --> <Border x:Name="ReferenceBorder" Background="Black" /> <Border Background="White" Grid.Column="1" /> <Border Background="Black" Grid.Column="2" /> </Grid> <!-- I made this transparent, so we can see the reference --> <Grid Opacity="0.9"> <Grid.ColumnDefinitions> <ColumnDefinition x:Name="Column1" MaxWidth="{Binding ElementName=ReferenceBorder,Path=ActualWidth}"/> <ColumnDefinition x:Name="Column2" MinWidth="50" /> <ColumnDefinition x:Name="Column3" Width="{ Binding ElementName=Column1, Path=Width }"/> </Grid.ColumnDefinitions> <Label Grid.Column="0" Background="Green"/> <GridSplitter Grid.Column="0" Width="5" /> <Label Grid.Column="1" Background="Yellow" /> <Label Grid.Column="2" Background="Red" /> </Grid> </Grid> </Page> ```
82,332
<p>I am using C# to process a message in my Outlook inbox that contains attachments. One of the attachments is of type olEmbeddeditem. I need to be able to process the contents of that attachment. From what I can tell I need to save the attachment to disk and use CreateItemFromTemplate which would return an object. </p> <p>The issue I have is that an olEmbeddeditem can be any of the Outlook object types MailItem, ContactItem, MeetingItem, etc. How do you know which object type a particular olEmbeddeditem attachment is going to be so that you know the object that will be returned by CreateItemFromTemplate?</p> <p>Alternatively, if there is a better way to get olEmbeddeditem attachment contents into an object for processing I'd be open to that too.</p>
[ { "answer_id": 96403, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I found the following code on Google Groups for determining the type of an Outlook object:</p>\n\n<pre><code>Type t = SomeOu...
2008/09/17
[ "https://Stackoverflow.com/questions/82332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8391/" ]
I am using C# to process a message in my Outlook inbox that contains attachments. One of the attachments is of type olEmbeddeditem. I need to be able to process the contents of that attachment. From what I can tell I need to save the attachment to disk and use CreateItemFromTemplate which would return an object. The issue I have is that an olEmbeddeditem can be any of the Outlook object types MailItem, ContactItem, MeetingItem, etc. How do you know which object type a particular olEmbeddeditem attachment is going to be so that you know the object that will be returned by CreateItemFromTemplate? Alternatively, if there is a better way to get olEmbeddeditem attachment contents into an object for processing I'd be open to that too.
I found the following code on Google Groups for determining the type of an Outlook object: ``` Type t = SomeOutlookObject.GetType(); string messageClass = t.InvokeMember("MessageClass", BindingFlags.Public | BindingFlags.GetField | BindingFlags.GetProperty, null, SomeOutlookObject, new object[]{}).ToString(); Console.WriteLine("\tType: " + messageClass); ``` I don't know if that helps with an olEmbedded item, but it seems to identify regular messages, calendar items, etc.
82,359
<p>I've just inherited some old Struts code.</p> <p>If Struts (1.3) follows the MVC pattern, how do the Action classes fill the View with variables to render in HTML ?</p> <p>So far, I've seen the Action classes push variables in <code>(1)</code> the HTTP request with</p> <pre><code>request.setAttribute("name", user.getName()) </code></pre> <p><code>(2)</code> in ActionForm classes, using methods specific to the application:</p> <pre><code>UserForm form = (UserForm) actionForm; form.setUserName(user.getName()); </code></pre> <p>and <code>(3)</code> a requestScope variable, that I see in the JSP layer (the view uses JSP), but I can't see in the Action classes.</p> <pre><code>&lt;p style='color: red'&gt;&lt;c:out value='${requestScope.userName}' /&gt;&lt;/p&gt; </code></pre> <p>So, which of these is considered old-school, and what's the recommended way of pushing variables in the View in Struts ?</p>
[ { "answer_id": 82512, "author": "Arno", "author_id": 13685, "author_profile": "https://Stackoverflow.com/users/13685", "pm_score": 1, "selected": false, "text": "<p>My Struts days are long over, but as far as I remember we used to place one view-specific bean (which would work as a holde...
2008/09/17
[ "https://Stackoverflow.com/questions/82359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15649/" ]
I've just inherited some old Struts code. If Struts (1.3) follows the MVC pattern, how do the Action classes fill the View with variables to render in HTML ? So far, I've seen the Action classes push variables in `(1)` the HTTP request with ``` request.setAttribute("name", user.getName()) ``` `(2)` in ActionForm classes, using methods specific to the application: ``` UserForm form = (UserForm) actionForm; form.setUserName(user.getName()); ``` and `(3)` a requestScope variable, that I see in the JSP layer (the view uses JSP), but I can't see in the Action classes. ``` <p style='color: red'><c:out value='${requestScope.userName}' /></p> ``` So, which of these is considered old-school, and what's the recommended way of pushing variables in the View in Struts ?
As `Struts 1.3` is considered old-school, I'd recommend to go with the flow and use the style that already is used throughout the application you inherited. If all different styles are already used, pick the most used one. After that, pick your personal favourite. Mine would be 1 or 3 - the form (2) is usually best suited for data that will eventually be rendered inside some form controls. If this is the case - use the form, otherwise - don't.
82,380
<p>I need to do a multilingual website, with urls like</p> <pre><code>www.domain.com/en/home.aspx for english www.domain.com/es/home.aspx for spanish </code></pre> <p>In the past, I would set up two virtual directories in IIS, and then detect the URL in global.aspx and change the language according to the URL</p> <pre><code>Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs) Dim lang As String If HttpContext.Current.Request.Path.Contains("/en/") Then lang = "en" Else lang = "es" End If Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang) Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang) End Sub </code></pre> <p>The solution is more like a hack. I'm thinking about using Routing for a new website. </p> <p><strong>Do you know a better or more elegant way to do it?</strong></p> <p>edit: The question is about the URL handling, not about resources, etc.</p>
[ { "answer_id": 82590, "author": "thomasb", "author_id": 6776, "author_profile": "https://Stackoverflow.com/users/6776", "pm_score": 0, "selected": false, "text": "<p>I personnaly use <a href=\"http://msdn.microsoft.com/en-us/library/c6zyy3s9.aspx\" rel=\"nofollow noreferrer\">the resourc...
2008/09/17
[ "https://Stackoverflow.com/questions/82380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2385/" ]
I need to do a multilingual website, with urls like ``` www.domain.com/en/home.aspx for english www.domain.com/es/home.aspx for spanish ``` In the past, I would set up two virtual directories in IIS, and then detect the URL in global.aspx and change the language according to the URL ``` Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs) Dim lang As String If HttpContext.Current.Request.Path.Contains("/en/") Then lang = "en" Else lang = "es" End If Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang) Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang) End Sub ``` The solution is more like a hack. I'm thinking about using Routing for a new website. **Do you know a better or more elegant way to do it?** edit: The question is about the URL handling, not about resources, etc.
I decided to go with the new ASP.net Routing. Why not urlRewriting? Because I don't want to change the clean URL that routing gives to you. Here is the code: ``` Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) ' Code that runs on application startup RegisterRoutes(RouteTable.Routes) End Sub Public Sub RegisterRoutes(ByVal routes As RouteCollection) Dim reportRoute As Route Dim DefaultLang As String = "es" reportRoute = New Route("{lang}/{page}", New LangRouteHandler) '* if you want, you can contrain the values 'reportRoute.Constraints = New RouteValueDictionary(New With {.lang = "[a-z]{2}"}) reportRoute.Defaults = New RouteValueDictionary(New With {.lang = DefaultLang, .page = "home"}) routes.Add(reportRoute) End Sub ``` Then LangRouteHandler.vb class: ``` Public Class LangRouteHandler Implements IRouteHandler Public Function GetHttpHandler(ByVal requestContext As System.Web.Routing.RequestContext) As System.Web.IHttpHandler _ Implements System.Web.Routing.IRouteHandler.GetHttpHandler 'Fill the context with the route data, just in case some page needs it For Each value In requestContext.RouteData.Values HttpContext.Current.Items(value.Key) = value.Value Next Dim VirtualPath As String VirtualPath = "~/" + requestContext.RouteData.Values("page") + ".aspx" Dim redirectPage As IHttpHandler redirectPage = BuildManager.CreateInstanceFromVirtualPath(VirtualPath, GetType(Page)) Return redirectPage End Function End Class ``` Finally I use the default.aspx in the root to redirect to the default lang used in the browser list. Maybe this can be done with the route.Defaults, but don't work inside Visual Studio (maybe it works in the server) ``` Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Dim DefaultLang As String = "es" Dim SupportedLangs As String() = {"en", "es"} Dim BrowserLang As String = Mid(Request.UserLanguages(0).ToString(), 1, 2).ToLower If SupportedLangs.Contains(BrowserLang) Then DefaultLang = BrowserLang Response.Redirect(DefaultLang + "/") End Sub ``` Some sources: \* [Mike Ormond's blog](http://blogs.msdn.com/mikeormond/archive/2008/05/14/using-asp-net-routing-independent-of-mvc.aspx) \* [Chris Cavanagh’s Blog](http://chriscavanagh.wordpress.com/2008/04/25/systemwebrouting-with-webforms-sample/) \* [MSDN](http://msdn.microsoft.com/en-us/library/cc668201.aspx)
82,404
<p>Given the problem that a stored procedure on SQL Server 2005, which is looping through a cursor, must be run once an hour and it takes about 5 minutes to run, but it takes up a large chunk of processor time:</p> <p>edit: I'd remove the cursor if I could, unfortunatly, I have to be doing a bunch of processing and running other stored procs/queries based on the row.</p> <p>Can I use WAITFOR DELAY '0:0:0.1' before each fetch to act as SQL's version of .Net's Thread.Sleep? Thus allowing the other processes to complete faster at the cost of this procedure's execution time.</p> <p>Or is there another solution I'm not seeing?</p> <p>Thanks</p>
[ { "answer_id": 82780, "author": "baldy", "author_id": 2012, "author_profile": "https://Stackoverflow.com/users/2012", "pm_score": 1, "selected": false, "text": "<p>I'm not sure if that would solve the problem. IMHO the performance problem with cursors is around the amount of memory you ...
2008/09/17
[ "https://Stackoverflow.com/questions/82404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9610/" ]
Given the problem that a stored procedure on SQL Server 2005, which is looping through a cursor, must be run once an hour and it takes about 5 minutes to run, but it takes up a large chunk of processor time: edit: I'd remove the cursor if I could, unfortunatly, I have to be doing a bunch of processing and running other stored procs/queries based on the row. Can I use WAITFOR DELAY '0:0:0.1' before each fetch to act as SQL's version of .Net's Thread.Sleep? Thus allowing the other processes to complete faster at the cost of this procedure's execution time. Or is there another solution I'm not seeing? Thanks
Putting the WAITFOR inside the loop would indeed slow it down and allow other things to go faster. You might also consider a WHILE loop instead of a cursor - in my experience it runs faster. You might also consider moving your cursor to a fast-forward, read-only cursor - that can limit how much memory it takes up. ``` declare @minid int, @maxid int, @somevalue int select @minid = 1, @maxid = 5 while @minid <= @maxid begin set @somevalue = null select @somevalue = somefield from sometable where id = @minid print @somevalue set @minid = @minid + 1 waitfor delay '00:00:00.1' end ```
82,409
<p>If I have a table in my database called 'Users', there will be a class generated by LINQtoSQL called 'User' with an already declared empty constructor.</p> <p>What is the best practice if I want to override this constructor and add my own logic to it?</p>
[ { "answer_id": 82470, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 2, "selected": false, "text": "<p>It doesn't look like you can override the empty constructor. Instead, I would create a method that performs the functiona...
2008/09/17
[ "https://Stackoverflow.com/questions/82409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15717/" ]
If I have a table in my database called 'Users', there will be a class generated by LINQtoSQL called 'User' with an already declared empty constructor. What is the best practice if I want to override this constructor and add my own logic to it?
The default constructor which is generated by the O/R-Designer, calls a partial function called `OnCreated` - so the best practice is not to override the default constructor, but instead implement the partial function `OnCreated` in `MyDataClasses.cs` to initialize items: ``` partial void OnCreated() { Name = ""; } ``` If you are implementing other constructors, always take care to call the default constructor so the classes will be initialized properly - for example entitysets (relations) are constructed in the default constructor.
82,417
<p>Is it possible to hide or exclude certain data from a report if it's being rendered in a particular format (csv, xml, excel, pdf, html). The problem is that I want hyperlinks to other reports to not be rendered when the report is generated in Excel format - but they should be there when the report is rendered in HTML format.</p>
[ { "answer_id": 82835, "author": "Bob Dizzle", "author_id": 9581, "author_profile": "https://Stackoverflow.com/users/9581", "pm_score": 0, "selected": false, "text": "<p>I don't think this is possible in the 2000 version, but might be in later versions.</p>\n\n<p>If I remember right, we e...
2008/09/17
[ "https://Stackoverflow.com/questions/82417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15428/" ]
Is it possible to hide or exclude certain data from a report if it's being rendered in a particular format (csv, xml, excel, pdf, html). The problem is that I want hyperlinks to other reports to not be rendered when the report is generated in Excel format - but they should be there when the report is rendered in HTML format.
The way I did this w/SSRS 2005 for a web app using the ReportViewer control is I had a hidden boolean report parameter which was used in the report decide if to render text as hyperlinks or not. Then the trick was how to send that parameter value depending on the rendering format. The way I did that was by disabling the ReportViewer export controls (by setting its ShowExportControls property to false) and making my own ASP.NET buttons for each format I wanted to be exportable. The code for those buttons first set the hidden boolean parameter and refreshed the report: ``` ReportViewer1.ServerReport.SetParameters(New ReportParameter() {New ReportParameter("ExportView", "True")}) ReportViewer1.ServerReport.Refresh() ``` Then you need to programmatically export the report. See [this page](http://weblogs.asp.net/srkirkland/archive/2007/10/29/exporting-a-sql-server-reporting-services-2005-report-directly-to-pdf-or-excel.aspx) for an example of how to do that (ignore the first few lines of code that create and initialize a ReportViewer).
82,437
<p>Why is the following C# code not allowed:</p> <pre><code>public abstract class BaseClass { public abstract int Bar { get;} } public class ConcreteClass : BaseClass { public override int Bar { get { return 0; } set {} } } </code></pre> <blockquote> <p>CS0546 'ConcreteClass.Bar.set': cannot override because 'BaseClass.Bar' does not have an overridable set accessor</p> </blockquote>
[ { "answer_id": 82464, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": -1, "selected": false, "text": "<p>Because at the IL level, a read/write property translates into two (getter and setter) methods.</p>\n\n<p>When overriding,...
2008/09/17
[ "https://Stackoverflow.com/questions/82437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ]
Why is the following C# code not allowed: ``` public abstract class BaseClass { public abstract int Bar { get;} } public class ConcreteClass : BaseClass { public override int Bar { get { return 0; } set {} } } ``` > > CS0546 'ConcreteClass.Bar.set': cannot override because 'BaseClass.Bar' does not have an overridable set accessor > > >
Because the writer of Baseclass has explicitly declared that Bar has to be a read-only property. It doesn't make sense for derivations to break this contract and make it read-write. I'm with Microsoft on this one. Let's say I'm a new programmer who has been told to code against the Baseclass derivation. i write something that assumes that Bar cannot be written to (since the Baseclass explicitly states that it is a get only property). Now with your derivation, my code may break. e.g. ``` public class BarProvider { BaseClass _source; Bar _currentBar; public void setSource(BaseClass b) { _source = b; _currentBar = b.Bar; } public Bar getBar() { return _currentBar; } } ``` Since Bar cannot be set as per the BaseClass interface, BarProvider assumes that caching is a safe thing to do - Since Bar cannot be modified. But if set was possible in a derivation, this class could be serving stale values if someone modified the \_source object's Bar property externally. The point being '*Be Open, avoid doing sneaky things and surprising people*' **Update**: *Ilya Ryzhenkov asks 'Why don't interfaces play by the same rules then?'* Hmm.. this gets muddier as I think about it. An interface is a contract that says 'expect an implementation to have a read property named Bar.' **Personally** I'm much less likely to make that assumption of read-only if I saw an Interface. When i see a get-only property on an interface, I read it as 'Any implementation would expose this attribute Bar'... on a base-class it clicks as 'Bar is a read-only property'. Of course technically you're not breaking the contract.. you're doing more. So you're right in a sense.. I'd close by saying 'make it as hard as possible for misunderstandings to crop up'.
82,442
<p>Inspired by the MVC storefront the latest project I'm working on is using extension methods on IQueryable to filter results.</p> <p>I have this interface;</p> <pre><code>IPrimaryKey { int ID { get; } } </code></pre> <p>and I have this extension method</p> <pre><code>public static IPrimaryKey GetByID(this IQueryable&lt;IPrimaryKey&gt; source, int id) { return source(obj =&gt; obj.ID == id); } </code></pre> <p>Let's say I have a class, SimpleObj which implements IPrimaryKey. When I have an IQueryable of SimpleObj the GetByID method doesn't exist, unless I explicitally cast as an IQueryable of IPrimaryKey, which is less than ideal.</p> <p>Am I missing something here?</p>
[ { "answer_id": 82463, "author": "Garry Shutler", "author_id": 6369, "author_profile": "https://Stackoverflow.com/users/6369", "pm_score": 2, "selected": false, "text": "<p>This cannot work due to the fact that generics don't have the ability to follow inheritance patterns. ie. IQueryable...
2008/09/17
[ "https://Stackoverflow.com/questions/82442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15691/" ]
Inspired by the MVC storefront the latest project I'm working on is using extension methods on IQueryable to filter results. I have this interface; ``` IPrimaryKey { int ID { get; } } ``` and I have this extension method ``` public static IPrimaryKey GetByID(this IQueryable<IPrimaryKey> source, int id) { return source(obj => obj.ID == id); } ``` Let's say I have a class, SimpleObj which implements IPrimaryKey. When I have an IQueryable of SimpleObj the GetByID method doesn't exist, unless I explicitally cast as an IQueryable of IPrimaryKey, which is less than ideal. Am I missing something here?
It works, when done right. cfeduke's solution works. However, you don't have to make the `IPrimaryKey` interface generic, in fact, you don't have to change your original definition at all: ``` public static IPrimaryKey GetByID<T>(this IQueryable<T> source, int id) where T : IPrimaryKey { return source(obj => obj.ID == id); } ```
82,483
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/219594/net-whats-the-best-way-to-implement-a-catch-all-exceptions-handler">.NET - What’s the best way to implement a “catch all exceptions handler”</a> </p> </blockquote> <p>I have a .NET console app app that is crashing and displaying a message to the user. All of my code is in a <code>try{&lt;code&gt;} catch(Exception e){&lt;stuff&gt;}</code> block, but still errors are occasionally displayed.</p> <p>In a Win32 app, you can capture all possible exceptions/crashes by installing various exception handlers:</p> <pre><code>/* C++ exc handlers */ _set_se_translator SetUnhandledExceptionFilter _set_purecall_handler set_terminate set_unexpected _set_invalid_parameter_handler </code></pre> <p>What is the equivalent in the .NET world so I can handle/log/quiet all possible error cases?</p>
[ { "answer_id": 82508, "author": "Juanma", "author_id": 3730, "author_profile": "https://Stackoverflow.com/users/3730", "pm_score": 5, "selected": false, "text": "<p>You can add an event handler to AppDomain.UnhandledException event, and it'll be called when a exception is thrown and not ...
2008/09/17
[ "https://Stackoverflow.com/questions/82483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7442/" ]
> > **Possible Duplicate:** > > [.NET - What’s the best way to implement a “catch all exceptions handler”](https://stackoverflow.com/questions/219594/net-whats-the-best-way-to-implement-a-catch-all-exceptions-handler) > > > I have a .NET console app app that is crashing and displaying a message to the user. All of my code is in a `try{<code>} catch(Exception e){<stuff>}` block, but still errors are occasionally displayed. In a Win32 app, you can capture all possible exceptions/crashes by installing various exception handlers: ``` /* C++ exc handlers */ _set_se_translator SetUnhandledExceptionFilter _set_purecall_handler set_terminate set_unexpected _set_invalid_parameter_handler ``` What is the equivalent in the .NET world so I can handle/log/quiet all possible error cases?
Contrary to what some others have posted, there's nothing wrong catching all exceptions. The important thing is to handle them all appropriately. If you have a stack overflow or out of memory condition, the app should shut down for them. Also, keep in mind that OOM conditions can prevent your exception handler from running correctly. For example, if your exception handler displays a dialog with the exception message, if you're out of memory, there may not be enough left for the dialog display. Best to log it and shut down immediately. As others mentioned, there are the UnhandledException and ThreadException events that you can handle to collection exceptions that might otherwise get missed. Then simply throw an exception handler around your main loop (assuming a winforms app). Also, you should be aware that OutOfMemoryExceptions aren't always thrown for out of memory conditions. An OOM condition can trigger all sorts of exceptions, in your code, or in the framework, that don't necessarily have anything to do with the fact that the real underlying condition is out of memory. I've frequently seen InvalidOperationException or ArgumentException when the underlying cause is actually out of memory.
82,530
<p>I'm on laptop (Ubuntu) with a network that use HTTP proxy (only http connections allowed).<br> When I use svn up for url like 'http://.....' everything is cool (google chrome repository works perfect), but right now I need to svn up from server with 'svn://....' and I see connection refused.<br> I've set proxy configuration in /etc/subversion/servers but it doesn't help.<br> Anyone have opinion/solution?<br></p>
[ { "answer_id": 82547, "author": "Cetra", "author_id": 15087, "author_profile": "https://Stackoverflow.com/users/15087", "pm_score": 0, "selected": false, "text": "<p>when you use the svn:// URI it uses port 3690 and probably won't use http proxy</p>\n" }, { "answer_id": 82576, ...
2008/09/17
[ "https://Stackoverflow.com/questions/82530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15752/" ]
I'm on laptop (Ubuntu) with a network that use HTTP proxy (only http connections allowed). When I use svn up for url like 'http://.....' everything is cool (google chrome repository works perfect), but right now I need to svn up from server with 'svn://....' and I see connection refused. I've set proxy configuration in /etc/subversion/servers but it doesn't help. Anyone have opinion/solution?
In `/etc/subversion/servers` you are setting `http-proxy-host`, which has nothing to do with `svn://` which connects to a different server usually running on port 3690 started by `svnserve` command. If you have access to the server, you can setup `svn+ssh://` as [explained here.](http://svnbook.red-bean.com/en/1.0/ch06s03.html) **Update**: You could also try using [`connect-tunnel`](http://search.cpan.org/~book/Net-Proxy-0.12/script/connect-tunnel), which uses your HTTPS proxy server to tunnel connections: ``` connect-tunnel -P proxy.company.com:8080 -T 10234:svn.example.com:3690 ``` Then you would use ``` svn checkout svn://localhost:10234/path/to/trunk ```
82,550
<p>I have a template class that I serialize (call it C), for which I want to specify a version for boost serialization. As BOOST_CLASS_VERSION does not work for template classes. I tried this:</p> <pre><code>namespace boost { namespace serialization { template&lt; typename T, typename U &gt; struct version&lt; C&lt;T,U&gt; &gt; { typedef mpl::int_&lt;1&gt; type; typedef mpl::integral_c_tag tag; BOOST_STATIC_CONSTANT(unsigned int, value = version::type::value); }; } } </code></pre> <p>but it does not compile. Under VC8, a subsequent call to BOOST_CLASS_VERSION gives this error:</p> <p><code>error C2913: explicit specialization; 'boost::serialization::version' is not a specialization of a class template</code></p> <p>What is the correct way to do it?</p>
[ { "answer_id": 83616, "author": "James Hopkin", "author_id": 11828, "author_profile": "https://Stackoverflow.com/users/11828", "pm_score": 5, "selected": true, "text": "<pre><code>#include &lt;boost/serialization/version.hpp&gt;\n</code></pre>\n\n<p>:-)</p>\n" }, { "answer_id": 3...
2008/09/17
[ "https://Stackoverflow.com/questions/82550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14443/" ]
I have a template class that I serialize (call it C), for which I want to specify a version for boost serialization. As BOOST\_CLASS\_VERSION does not work for template classes. I tried this: ``` namespace boost { namespace serialization { template< typename T, typename U > struct version< C<T,U> > { typedef mpl::int_<1> type; typedef mpl::integral_c_tag tag; BOOST_STATIC_CONSTANT(unsigned int, value = version::type::value); }; } } ``` but it does not compile. Under VC8, a subsequent call to BOOST\_CLASS\_VERSION gives this error: `error C2913: explicit specialization; 'boost::serialization::version' is not a specialization of a class template` What is the correct way to do it?
``` #include <boost/serialization/version.hpp> ``` :-)
82,607
<p>I get DNS records from a Python program, using <a href="http://www.dnspython.org/" rel="nofollow noreferrer">DNS Python</a></p> <p>I can get various DNSSEC-related records:</p> <pre><code>&gt;&gt;&gt; import dns.resolver &gt;&gt;&gt; myresolver = dns.resolver.Resolver() &gt;&gt;&gt; myresolver.use_edns(1, 0, 1400) &gt;&gt;&gt; print myresolver.query('sources.org', 'DNSKEY') &lt;dns.resolver.Answer object at 0xb78ed78c&gt; &gt;&gt;&gt; print myresolver.query('ripe.net', 'NSEC') &lt;dns.resolver.Answer object at 0x8271c0c&gt; </code></pre> <p>But no RRSIG records:</p> <pre><code>&gt;&gt;&gt; print myresolver.query('sources.org', 'RRSIG') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 664, in query answer = Answer(qname, rdtype, rdclass, response) File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 121, in __init__ raise NoAnswer </code></pre> <p>I tried several signed domains like absolight.fr or ripe.net.</p> <p>Trying with dig, I see that there are indeed RRSIG records.</p> <p>Checking with tcpdump, I can see that DNS Python sends the correct query and receives correct replies (here, eight records):</p> <pre><code>16:09:39.342532 IP 192.134.4.69.53381 &gt; 192.134.4.162.53: 22330+ [1au] RRSIG? sources.org. (40) 16:09:39.343229 IP 192.134.4.162.53 &gt; 192.134.4.69.53381: 22330 8/5/6 RRSIG[|domain] </code></pre> <p>DNS Python 1.6.0 - Python 2.5.2 (r252:60911, Aug 8 2008, 09:22:44) [GCC 4.3.1] on linux2</p>
[ { "answer_id": 82868, "author": "Cetra", "author_id": 15087, "author_profile": "https://Stackoverflow.com/users/15087", "pm_score": 0, "selected": false, "text": "<p>If you try this, what happens?</p>\n\n<pre><code>print myresolver.query('sources.org', 'ANY', 'RRSIG')\n</code></pre>\n" ...
2008/09/17
[ "https://Stackoverflow.com/questions/82607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15625/" ]
I get DNS records from a Python program, using [DNS Python](http://www.dnspython.org/) I can get various DNSSEC-related records: ``` >>> import dns.resolver >>> myresolver = dns.resolver.Resolver() >>> myresolver.use_edns(1, 0, 1400) >>> print myresolver.query('sources.org', 'DNSKEY') <dns.resolver.Answer object at 0xb78ed78c> >>> print myresolver.query('ripe.net', 'NSEC') <dns.resolver.Answer object at 0x8271c0c> ``` But no RRSIG records: ``` >>> print myresolver.query('sources.org', 'RRSIG') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 664, in query answer = Answer(qname, rdtype, rdclass, response) File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 121, in __init__ raise NoAnswer ``` I tried several signed domains like absolight.fr or ripe.net. Trying with dig, I see that there are indeed RRSIG records. Checking with tcpdump, I can see that DNS Python sends the correct query and receives correct replies (here, eight records): ``` 16:09:39.342532 IP 192.134.4.69.53381 > 192.134.4.162.53: 22330+ [1au] RRSIG? sources.org. (40) 16:09:39.343229 IP 192.134.4.162.53 > 192.134.4.69.53381: 22330 8/5/6 RRSIG[|domain] ``` DNS Python 1.6.0 - Python 2.5.2 (r252:60911, Aug 8 2008, 09:22:44) [GCC 4.3.1] on linux2
You probably mean RRSIG ANY (otherwise, the order is wrong, the class needs to be after the type) ``` >>> print myresolver.query('sources.org', 'RRSIG', 'ANY') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 664, in query answer = Answer(qname, rdtype, rdclass, response) File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 121, in __init__ raise NoAnswer dns.resolver.NoAnswer ```
82,612
<p>How can I figure out, how many files needs to be recompiled <em>before</em> I start the build process.</p> <p>Sometimes I don't remember how many basic header files I changed so a Rebuild All would be better than a simple build. There seams to be no option for this, but IMHO it must be possible (f.e. XCode give me this information).</p> <p><strong>Update:</strong></p> <p>My problem is not, that Visual Studio doesn't know what to compile. I need to know how much it <em>will</em> compile so that I can decide if I can make a quick test with my new code or if I should write more code till I start the "expensive" build process. Or if my boss ask "When can I have the new build?" the best answer is not "It is done when it is done!".</p> <p>It's really helpful when the IDE can say <em>"compile 200 of 589 files"</em> instead of <em>"compile x,y, ..."</em></p>
[ { "answer_id": 82868, "author": "Cetra", "author_id": 15087, "author_profile": "https://Stackoverflow.com/users/15087", "pm_score": 0, "selected": false, "text": "<p>If you try this, what happens?</p>\n\n<pre><code>print myresolver.query('sources.org', 'ANY', 'RRSIG')\n</code></pre>\n" ...
2008/09/17
[ "https://Stackoverflow.com/questions/82612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15757/" ]
How can I figure out, how many files needs to be recompiled *before* I start the build process. Sometimes I don't remember how many basic header files I changed so a Rebuild All would be better than a simple build. There seams to be no option for this, but IMHO it must be possible (f.e. XCode give me this information). **Update:** My problem is not, that Visual Studio doesn't know what to compile. I need to know how much it *will* compile so that I can decide if I can make a quick test with my new code or if I should write more code till I start the "expensive" build process. Or if my boss ask "When can I have the new build?" the best answer is not "It is done when it is done!". It's really helpful when the IDE can say *"compile 200 of 589 files"* instead of *"compile x,y, ..."*
You probably mean RRSIG ANY (otherwise, the order is wrong, the class needs to be after the type) ``` >>> print myresolver.query('sources.org', 'RRSIG', 'ANY') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 664, in query answer = Answer(qname, rdtype, rdclass, response) File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 121, in __init__ raise NoAnswer dns.resolver.NoAnswer ```
82,661
<p>I want to clear the list of projects on the start page...how do I do this? I know I can track it down in the registry, but is there an approved route to go?</p>
[ { "answer_id": 82705, "author": "Charles Anderson", "author_id": 11677, "author_profile": "https://Stackoverflow.com/users/11677", "pm_score": 3, "selected": false, "text": "<p>If you try opening up a project that can no longer be found, Visual Studio will prompt you for permission to re...
2008/09/17
[ "https://Stackoverflow.com/questions/82661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15778/" ]
I want to clear the list of projects on the start page...how do I do this? I know I can track it down in the registry, but is there an approved route to go?
There is an MSDN article [here](http://msdn.microsoft.com/en-us/library/aa991991.aspx) which suggests that you just move the projects to a new directory. However, as you mentioned, the list of projects is kept in the registry under this key: ``` HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\<version>\ProjectMRUList ``` and the list of recent files is kept in this key: ``` HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\<version>\FILEMRUList ``` **Note For Visual Studio 2015:** The location has changed. You can check out [this answer](https://stackoverflow.com/a/33945037/62195) for details. Some people have automated clearing this registry key with their own tools: [Visual Studio Most Recent Files Utility](http://www.codeplex.com/vsrecentfiles) [Add-in for cleaning Visual Studio 2008 MRU Projects list](http://code.msdn.microsoft.com/CleanRecentListAddIn)
82,721
<p>In a SQL server database, I have a table which contains a TEXT field which is set to allow NULLs. I need to change this to not allow NULLs. I can do this no problem via Enterprise Manager, but when I try to run the following script, <strong>alter table dbo.[EventLog] Alter column [Message] text Not null</strong>, I get an error:</p> <p><em>Cannot alter column 'ErrorMessage' because it is 'text'.</em></p> <p>Reading SQL Books Online does indeed reveal you are not allow to do an ALTER COLUMN on TEXT fields. I really need to be able to do this via a script though, and not manually in Enterprise Manager. What are the options for doing this in script then?</p>
[ { "answer_id": 82748, "author": "Seb Rose", "author_id": 12405, "author_profile": "https://Stackoverflow.com/users/12405", "pm_score": 2, "selected": false, "text": "<p>Create a new field. Copy the data across. Drop the old field. Rename the new field.</p>\n" }, { "answer_id": 82...
2008/09/17
[ "https://Stackoverflow.com/questions/82721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7585/" ]
In a SQL server database, I have a table which contains a TEXT field which is set to allow NULLs. I need to change this to not allow NULLs. I can do this no problem via Enterprise Manager, but when I try to run the following script, **alter table dbo.[EventLog] Alter column [Message] text Not null**, I get an error: *Cannot alter column 'ErrorMessage' because it is 'text'.* Reading SQL Books Online does indeed reveal you are not allow to do an ALTER COLUMN on TEXT fields. I really need to be able to do this via a script though, and not manually in Enterprise Manager. What are the options for doing this in script then?
You can use Enterprise Manager to create your script. Right click on the table in EM and select Design. Uncheck the Allow Nulls column for the Text field. Instead of hitting the regular save icon (the floppy), click an icon that looks like a golden scroll with a tiny floppy or just do Table Designer > Generate Change Script from the menu. Save the script to a file so you can reuse it. Here is a sample script: ``` /* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/ BEGIN TRANSACTION SET QUOTED_IDENTIFIER ON SET ARITHABORT ON SET NUMERIC_ROUNDABORT OFF SET CONCAT_NULL_YIELDS_NULL ON SET ANSI_NULLS ON SET ANSI_PADDING ON SET ANSI_WARNINGS ON COMMIT BEGIN TRANSACTION GO CREATE TABLE dbo.Tmp_TestTable ( tableKey int NOT NULL, Description varchar(50) NOT NULL, TextData text NOT NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO IF EXISTS(SELECT * FROM dbo.TestTable) EXEC('INSERT INTO dbo.Tmp_TestTable (tableKey, Description, TextData) SELECT tableKey, Description, TextData FROM dbo.TestTable WITH (HOLDLOCK TABLOCKX)') GO DROP TABLE dbo.TestTable GO EXECUTE sp_rename N'dbo.Tmp_TestTable', N'TestTable', 'OBJECT' GO ALTER TABLE dbo.TestTable ADD CONSTRAINT PK_TestTable PRIMARY KEY CLUSTERED ( tableKey ) ON [PRIMARY] GO COMMIT ```
82,788
<p>I have an issue that is driving me a bit nuts: Using a UserProfileManager as an non-authorized user.</p> <p>The problem: The user does not have "Manage User Profiles" rights, but I still want to use the UserProfileManager. The idea of using SPSecurity.RunWithElevatedPrivileges does not seem to work, as the UserProfileManager authorizes against the SSP as it seems.</p> <pre><code> SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(inputWeb.Site.ID)) { ServerContext ctx = ServerContext.GetContext(site); UserProfileManager upm = new UserProfileManager(ctx,true); UserProfile u = upm.GetUserProfile(userLogin); DepartmentName = u["Department"].Value as string; } }); </code></pre> <p>This still fails on the "new UserProfileManager" line, with the "You must have manage user profiles administrator rights to use administrator mode" exception.</p> <p>As far as I userstood, RunWithElevatedPrivileges reverts to the AppPool Identity. WindowsIdentity.GetCurrent().Name returns "NT AUTHORITY\network service", and I have given that account Manage User Profiles rights - no luck.</p> <p>site.RootWeb.CurrentUser.LoginName returns SHAREPOINT\system for the site created within RunWithElevatedPrivileges, which is not a valid Windows Account ofc.</p> <p>Is there even a way to do that? I do not want to give all users "Manage User Profiles" rights, but I just want to get some data from the user profiles (Department, Country, Direct Reports). Any ideas?</p>
[ { "answer_id": 83102, "author": "senfo", "author_id": 10792, "author_profile": "https://Stackoverflow.com/users/10792", "pm_score": 3, "selected": true, "text": "<p>The permission that needs set is actually found in the Shared Service Provider.</p>\n\n<ol>\n<li>Navigate to Central Admin<...
2008/09/17
[ "https://Stackoverflow.com/questions/82788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
I have an issue that is driving me a bit nuts: Using a UserProfileManager as an non-authorized user. The problem: The user does not have "Manage User Profiles" rights, but I still want to use the UserProfileManager. The idea of using SPSecurity.RunWithElevatedPrivileges does not seem to work, as the UserProfileManager authorizes against the SSP as it seems. ``` SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(inputWeb.Site.ID)) { ServerContext ctx = ServerContext.GetContext(site); UserProfileManager upm = new UserProfileManager(ctx,true); UserProfile u = upm.GetUserProfile(userLogin); DepartmentName = u["Department"].Value as string; } }); ``` This still fails on the "new UserProfileManager" line, with the "You must have manage user profiles administrator rights to use administrator mode" exception. As far as I userstood, RunWithElevatedPrivileges reverts to the AppPool Identity. WindowsIdentity.GetCurrent().Name returns "NT AUTHORITY\network service", and I have given that account Manage User Profiles rights - no luck. site.RootWeb.CurrentUser.LoginName returns SHAREPOINT\system for the site created within RunWithElevatedPrivileges, which is not a valid Windows Account ofc. Is there even a way to do that? I do not want to give all users "Manage User Profiles" rights, but I just want to get some data from the user profiles (Department, Country, Direct Reports). Any ideas?
The permission that needs set is actually found in the Shared Service Provider. 1. Navigate to Central Admin 2. Navigate to the Shared Service Provider 3. Under **User Profiles and My Sites** navigate to Personalization services permissions . 4. If the account doesn't already exist, add the account for which your sites App Domain is running under. 5. Grant that user **Manage user profiles** permission. I notice that you're running the application pool under the Network Service account. I implemented an identical feature on my site; however, the application pool was hosted under a Windows account. I'm not sure why this would make a difference, however.
82,814
<p>The following code is causing an intermittent crash on a Vista machine.</p> <pre><code>using (SoundPlayer myPlayer = new SoundPlayer(Properties.Resources.BEEPPURE)) myPlayer.Play(); </code></pre> <p>I highly suspect it is this code because the program crashes mid-beep or just before the beep is played every time. I have top-level traps for all <code>ThreadExceptions</code>, <code>UnhandledExceptions</code> in my app domain, and a <code>try-catch</code> around <code>Application.Run</code>, none of which trap this crash.</p> <p>Any ideas?</p> <hr> <p>EDIT:</p> <p>The Event Viewer has the following information:</p> <blockquote> <p>Faulting application [xyz].exe, version 4.0.0.0, time stamp 0x48ce5a74, faulting module msvcrt.dll, version 7.0.6001.18000, time stamp 0x4791a727, exception code 0xc0000005, fault offset 0x00009b30, process id 0x%9, application start time 0x%10.</p> </blockquote> <p>Interestingly, the <code>HRESULT 0xc0000005</code> has the message: </p> <blockquote> <p>"Reading or writing to an inaccessible memory location." (STATUS_ACCESS_VIOLATION)</p> </blockquote>
[ { "answer_id": 82901, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 1, "selected": false, "text": "<p>You can use WinDBG and trap all first-chance exceptions. I'm sure you'll see something interesting. If so, you can use...
2008/09/17
[ "https://Stackoverflow.com/questions/82814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1490/" ]
The following code is causing an intermittent crash on a Vista machine. ``` using (SoundPlayer myPlayer = new SoundPlayer(Properties.Resources.BEEPPURE)) myPlayer.Play(); ``` I highly suspect it is this code because the program crashes mid-beep or just before the beep is played every time. I have top-level traps for all `ThreadExceptions`, `UnhandledExceptions` in my app domain, and a `try-catch` around `Application.Run`, none of which trap this crash. Any ideas? --- EDIT: The Event Viewer has the following information: > > Faulting application [xyz].exe, version 4.0.0.0, time stamp > 0x48ce5a74, faulting module msvcrt.dll, version 7.0.6001.18000, time > stamp 0x4791a727, exception code 0xc0000005, fault offset 0x00009b30, > process id 0x%9, application start time 0x%10. > > > Interestingly, the `HRESULT 0xc0000005` has the message: > > "Reading or writing to an inaccessible memory location." > (STATUS\_ACCESS\_VIOLATION) > > >
Actually, the above code (that is, new SoundPlayer(BEEPPURE)).Play(); was crashing for me. This article explains why, and provides an alternative to SoundPlayer that works flawlessly: <http://www.codeproject.com/KB/audio-video/soundplayerbug.aspx?msg=2862832#xx2862832xx>
82,831
<p>How do I check whether a file exists or not, without using the <a href="https://docs.python.org/3.6/reference/compound_stmts.html#try" rel="noreferrer"><code>try</code></a> statement?</p>
[ { "answer_id": 82836, "author": "Paul", "author_id": 215086, "author_profile": "https://Stackoverflow.com/users/215086", "pm_score": 10, "selected": false, "text": "<pre><code>import os\n\nif os.path.isfile(filepath):\n print(&quot;File exists&quot;)\n</code></pre>\n" }, { "ans...
2008/09/17
[ "https://Stackoverflow.com/questions/82831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15616/" ]
How do I check whether a file exists or not, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement?
If the reason you're checking is so you can do something like `if file_exists: open_it()`, it's safer to use a `try` around the attempt to open it. Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it. If you're not planning to open the file immediately, you can use [`os.path.isfile`](https://docs.python.org/library/os.path.html#os.path.isfile) > > Return `True` if path is an existing regular file. This follows symbolic links, so both [islink()](https://docs.python.org/library/os.path.html#os.path.islink) and [isfile()](https://docs.python.org/library/os.path.html#os.path.isfile) can be true for the same path. > > > ``` import os.path os.path.isfile(fname) ``` if you need to be sure it's a file. Starting with Python 3.4, the [`pathlib` module](https://docs.python.org/3/library/pathlib.html#pathlib.Path.is_file) offers an object-oriented approach (backported to `pathlib2` in Python 2.7): ``` from pathlib import Path my_file = Path("/path/to/file") if my_file.is_file(): # file exists ``` To check a directory, do: ``` if my_file.is_dir(): # directory exists ``` To check whether a `Path` object exists independently of whether is it a file or directory, use `exists()`: ``` if my_file.exists(): # path exists ``` You can also use `resolve(strict=True)` in a `try` block: ``` try: my_abs_path = my_file.resolve(strict=True) except FileNotFoundError: # doesn't exist else: # exists ```
82,838
<p>Below are two ways of reading in the commandline parameters. The first is the way that I'm accustom to seeing using the parameter in the main. The second I stumbled on when reviewing code. I noticed that the second assigns the first item in the array to the path and application but the first skips this. </p> <p>Is it just preference or is the second way the better way now?</p> <pre><code>Sub Main(ByVal args() As String) For i As Integer = 0 To args.Length - 1 Console.WriteLine("Arg: " &amp; i &amp; " is " &amp; args(i)) Next Console.ReadKey() End Sub </code></pre> <p><br><br></p> <pre><code>Sub Main() Dim args() As String = System.Environment.GetCommandLineArgs() For i As Integer = 0 To args.Length - 1 Console.WriteLine("Arg: " &amp; i &amp; " is " &amp; args(i)) Next Console.ReadKey() End Sub </code></pre> <p>I think the same can be done in C#, so it's not necessarily a vb.net question.</p>
[ { "answer_id": 82857, "author": "David Thibault", "author_id": 5903, "author_profile": "https://Stackoverflow.com/users/5903", "pm_score": 6, "selected": true, "text": "<p>Second way is better because it can be used outside the main(), so when you refactor it's one less thing to think ab...
2008/09/17
[ "https://Stackoverflow.com/questions/82838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2357/" ]
Below are two ways of reading in the commandline parameters. The first is the way that I'm accustom to seeing using the parameter in the main. The second I stumbled on when reviewing code. I noticed that the second assigns the first item in the array to the path and application but the first skips this. Is it just preference or is the second way the better way now? ``` Sub Main(ByVal args() As String) For i As Integer = 0 To args.Length - 1 Console.WriteLine("Arg: " & i & " is " & args(i)) Next Console.ReadKey() End Sub ``` ``` Sub Main() Dim args() As String = System.Environment.GetCommandLineArgs() For i As Integer = 0 To args.Length - 1 Console.WriteLine("Arg: " & i & " is " & args(i)) Next Console.ReadKey() End Sub ``` I think the same can be done in C#, so it's not necessarily a vb.net question.
Second way is better because it can be used outside the main(), so when you refactor it's one less thing to think about. Also I don't like the "magic" that puts the args in the method parameter for the first way.
82,847
<p>If I am in a function in the code behind, and I want to implement displaying a "Loading..." in the status bar the following makes sense, but as we know from WinForms is a NoNo:</p> <pre><code>StatusBarMessageText.Text = "Loading Configuration Settings..."; LoadSettingsGridData(); StatusBarMessageText.Text = "Done"; </code></pre> <p>What we all now from WinForms Chapter 1 class 101, is the form won't display changes to the user until after the Entire Function completes... meaning the "Loading" message will never be displayed to the user. The following code is needed.</p> <pre><code>Form1.SuspendLayout(); StatusBarMessageText.Text = "Loading Configuration Settings..."; Form1.ResumeLayout(); LoadSettingsGridData(); Form1.SuspendLayout(); StatusBarMessageText.Text = "Done"; Form1.ResumeLayout(); </code></pre> <p>What is the best practice for dealing with this fundamental issue in WPF?</p>
[ { "answer_id": 83216, "author": "Abe Heidebrecht", "author_id": 9268, "author_profile": "https://Stackoverflow.com/users/9268", "pm_score": -1, "selected": false, "text": "<p>The easiest way to get this to work is to add the LoadSettingsGridData to the dispatcher queue. If you set the o...
2008/09/17
[ "https://Stackoverflow.com/questions/82847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2744/" ]
If I am in a function in the code behind, and I want to implement displaying a "Loading..." in the status bar the following makes sense, but as we know from WinForms is a NoNo: ``` StatusBarMessageText.Text = "Loading Configuration Settings..."; LoadSettingsGridData(); StatusBarMessageText.Text = "Done"; ``` What we all now from WinForms Chapter 1 class 101, is the form won't display changes to the user until after the Entire Function completes... meaning the "Loading" message will never be displayed to the user. The following code is needed. ``` Form1.SuspendLayout(); StatusBarMessageText.Text = "Loading Configuration Settings..."; Form1.ResumeLayout(); LoadSettingsGridData(); Form1.SuspendLayout(); StatusBarMessageText.Text = "Done"; Form1.ResumeLayout(); ``` What is the best practice for dealing with this fundamental issue in WPF?
Best and simplest: ``` using(var d = Dispatcher.DisableProcessing()) { /* your work... Use dispacher.begininvoke... */ } ``` Or ``` IDisposable d; try { d = Dispatcher.DisableProcessing(); /* your work... Use dispacher.begininvoke... */ } finally { d.Dispose(); } ```
82,867
<p>I want to create a number of masked edit extenders from codebehind. Something like:</p> <pre><code>private MaskedEditExtender m_maskedEditExtender; protected override void OnLoad(EventArgs e) { base.OnLoad(e); m_maskedEditExtender = new MaskedEditExtender() { BehaviorID = "clientName" }; m_maskedEditExtender.Mask = "999999999"; this.Controls.Add(m_maskedEditExtender); } protected override void Render(HtmlTextWriter writer) { m_maskedEditExtender.RenderControl(writer); } </code></pre> <p>When I do this, I get a NullReferenceException on OnLoad of MaskedEditExtender. What is the correct way of doing that? Please note that putting the extender into a repeater-like control and using DataBind does not work for me.</p> <p><strong>Edit:</strong> I do not have an update panel. Turns out I also need to specify a target control on serverside.</p>
[ { "answer_id": 83085, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 1, "selected": false, "text": "<p>Your example is not providing a TargetControlID.</p>\n\n<p>Do you have an updatePanel on the page? I had problems d...
2008/09/17
[ "https://Stackoverflow.com/questions/82867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31505/" ]
I want to create a number of masked edit extenders from codebehind. Something like: ``` private MaskedEditExtender m_maskedEditExtender; protected override void OnLoad(EventArgs e) { base.OnLoad(e); m_maskedEditExtender = new MaskedEditExtender() { BehaviorID = "clientName" }; m_maskedEditExtender.Mask = "999999999"; this.Controls.Add(m_maskedEditExtender); } protected override void Render(HtmlTextWriter writer) { m_maskedEditExtender.RenderControl(writer); } ``` When I do this, I get a NullReferenceException on OnLoad of MaskedEditExtender. What is the correct way of doing that? Please note that putting the extender into a repeater-like control and using DataBind does not work for me. **Edit:** I do not have an update panel. Turns out I also need to specify a target control on serverside.
See [ASP.NET Page Life Cycle Overview](http://msdn.microsoft.com/en-us/library/ms178472.aspx) if this is in a Page subclass. If you scroll down to the event list, that page advises you to use the PreInit event to create any dynamic controls. It's necessary to do that early to ensure that ASP.NET cleanly loads ViewState at the right stage, among other things. If you are doing this in a web user control or custom control, though, override CreateChildControls and do this in there. Post a more complete code example if that doesn't help.
82,872
<p>I have a old website that generate its own RSS everytime a new post is created. Everything worked when I was on a server with PHP 4 but now that the host change to PHP 5, I always have a "bad formed XML". I was using xml_parser_create() and xml_parse(...) and fwrite(..) to save everything.</p> <p>Here is the example when saving (I read before save to append old RSS line of course).</p> <pre><code>function SaveXml() { if (!is_file($this-&gt;getFileName())) { //Création du fichier $file_handler = fopen($this-&gt;getFileName(),"w"); fwrite($file_handler,""); fclose($file_handler); }//Fin du if //Header xml version="1.0" encoding="utf-8" $strFileData = '&lt;?xml version="1.0" encoding="iso-8859-1" ?&gt;&lt;rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"&gt;&lt;channel&gt;&lt;title&gt;'.$this-&gt;getProjectName().'&lt;/title&gt;&lt;link&gt;http://www.mywebsite.com&lt;/link&gt;&lt;description&gt;My description&lt;/description&gt;&lt;lastBuildDate&gt;' . date("r"). '&lt;/lastBuildDate&gt;'; //Data reset($this-&gt;arrData); foreach($this-&gt;arrData as $i =&gt; $value) { $strFileData .= '&lt;item&gt;'; $strFileData .= '&lt;title&gt;'. $this-&gt;GetNews($i,0) . '&lt;/title&gt;'; $strFileData .= '&lt;pubDate&gt;'. $this-&gt;GetNews($i,1) . '&lt;/pubDate&gt;'; $strFileData .= '&lt;dc:creator&gt;'. $this-&gt;GetNews($i,2) . '&lt;/dc:creator&gt;'; $strFileData .= '&lt;description&gt;&lt;![CDATA['. $this-&gt;GetNews($i,3) . ']]&gt; &lt;/description&gt;'; $strFileData .= '&lt;link&gt;&lt;![CDATA['. $this-&gt;GetNews($i,4) . ']]&gt;&lt;/link&gt;'; $strFileData .= '&lt;guid&gt;'. $this-&gt;GetNews($i,4) . '&lt;/guid&gt;'; //$strFileData .= '&lt;category&gt;'. $this-&gt;GetNews($i,5) . '&lt;/category&gt;'; $strFileData .= '&lt;category&gt;Mycategory&lt;/category&gt;'; $strFileData .= '&lt;/item&gt;'; }//Fin du for i $strFileData .= '&lt;/channel&gt;&lt;/rss&gt;'; if (file_exists($this-&gt;getFileName()))//Détruit le fichier unlink($this-&gt;getFileName()); $file_handler = fopen($this-&gt;getFileName(),"w"); fwrite($file_handler,$strFileData); fclose($file_handler); }//Fin de SaveXml </code></pre> <p>My question is : how do you create and fill up your RSS in PHP?</p>
[ { "answer_id": 82894, "author": "Marc Gear", "author_id": 6563, "author_profile": "https://Stackoverflow.com/users/6563", "pm_score": 2, "selected": false, "text": "<p>I would use <a href=\"http://www.php.net/simplexml\" rel=\"nofollow noreferrer\">simpleXML</a> to create the required st...
2008/09/17
[ "https://Stackoverflow.com/questions/82872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
I have a old website that generate its own RSS everytime a new post is created. Everything worked when I was on a server with PHP 4 but now that the host change to PHP 5, I always have a "bad formed XML". I was using xml\_parser\_create() and xml\_parse(...) and fwrite(..) to save everything. Here is the example when saving (I read before save to append old RSS line of course). ``` function SaveXml() { if (!is_file($this->getFileName())) { //Création du fichier $file_handler = fopen($this->getFileName(),"w"); fwrite($file_handler,""); fclose($file_handler); }//Fin du if //Header xml version="1.0" encoding="utf-8" $strFileData = '<?xml version="1.0" encoding="iso-8859-1" ?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>'.$this->getProjectName().'</title><link>http://www.mywebsite.com</link><description>My description</description><lastBuildDate>' . date("r"). '</lastBuildDate>'; //Data reset($this->arrData); foreach($this->arrData as $i => $value) { $strFileData .= '<item>'; $strFileData .= '<title>'. $this->GetNews($i,0) . '</title>'; $strFileData .= '<pubDate>'. $this->GetNews($i,1) . '</pubDate>'; $strFileData .= '<dc:creator>'. $this->GetNews($i,2) . '</dc:creator>'; $strFileData .= '<description><![CDATA['. $this->GetNews($i,3) . ']]> </description>'; $strFileData .= '<link><![CDATA['. $this->GetNews($i,4) . ']]></link>'; $strFileData .= '<guid>'. $this->GetNews($i,4) . '</guid>'; //$strFileData .= '<category>'. $this->GetNews($i,5) . '</category>'; $strFileData .= '<category>Mycategory</category>'; $strFileData .= '</item>'; }//Fin du for i $strFileData .= '</channel></rss>'; if (file_exists($this->getFileName()))//Détruit le fichier unlink($this->getFileName()); $file_handler = fopen($this->getFileName(),"w"); fwrite($file_handler,$strFileData); fclose($file_handler); }//Fin de SaveXml ``` My question is : how do you create and fill up your RSS in PHP?
At swcombine.com we use [Feedcreator](http://feedcreator.org/). Use that one and your problem will be gone. :) Here is the PHP code to use it once installed: ``` function feed_simnews() { $objRSS = new UniversalFeedCreator(); $objRSS->title = 'My News'; $objRSS->link = 'http://link.to/news.php'; $objRSS->description = 'daily news from me'; $objRSS->xsl = 'http://link.to/feeds/feedxsl.xsl'; $objRSS->language = 'en'; $objRSS->copyright = 'Copyright: Mine!'; $objRSS->webmaster = 'webmaster@somewhere.com'; $objRSS->syndicationURL = 'http://link.to/news/simnews.php'; $objRSS->ttl = 180; $objImage = new FeedImage(); $objImage->title = 'my logo'; $objImage->url = 'http://link.to/feeds/logo.jpg'; $objImage->link = 'http://link.to'; $objImage->description = 'Feed provided by link.to. Click to visit.'; $objImage->width = 120; $objImage->height = 60; $objRSS->image = $objImage; //Function retrieving an array of your news from date start to last week $colNews = getYourNews(array('start_date' => 'Last week')); foreach($colNews as $p) { $objItem = new FeedItem(); $objItem->title = $p->title; $objItem->description = $p->body; $objItem->link = $p->link; $objItem->date = $p->date; $objItem->author = $p->author; $objItem->guid = $p->guid; $objRSS->addItem($objItem); } $objRSS->saveFeed('RSS2.0', 'http://link.to/feeds/news.xml', false); }; ``` Quite KISS. :)
82,875
<p>What SQL can be used to list the tables, and the rows within those tables in an SQLite database file - once I have attached it with the <code>ATTACH</code> command on the SQLite 3 command line tool?</p>
[ { "answer_id": 82889, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 9, "selected": false, "text": "<p>It appears you need to go through the <strong>sqlite_master</strong> table, like this:</p>\n\n<pre><code>SELECT * F...
2008/09/17
[ "https://Stackoverflow.com/questions/82875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/974/" ]
What SQL can be used to list the tables, and the rows within those tables in an SQLite database file - once I have attached it with the `ATTACH` command on the SQLite 3 command line tool?
The `.tables`, and `.schema` "helper" functions don't look into ATTACHed databases: they just query the `SQLITE_MASTER` table for the "main" database. Consequently, if you used ``` ATTACH some_file.db AS my_db; ``` then you need to do ``` SELECT name FROM my_db.sqlite_master WHERE type='table'; ``` Note that temporary tables don't show up with `.tables` either: you have to list `sqlite_temp_master` for that: ``` SELECT name FROM sqlite_temp_master WHERE type='table'; ```
82,881
<p>Lets say I have a Dictionary object:</p> <pre><code>Dictionary myDictionary&lt;int, SomeObject&gt; = new Dictionary&lt;string, SomeObject&gt;(); </code></pre> <p>Now I want to iterate through the dictionary in reverse order. I can't use a simple for loop because I don't know the keys of the dictionary. A <em>foreach</em> is easy:</p> <pre><code>foreach (SomeObject object in myDictionary.Values) { // Do stuff to object } </code></pre> <p>But how can I perform this in reverse?</p>
[ { "answer_id": 82897, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 5, "selected": false, "text": "<p>A dictionary or any other form of hashtable has no ordering. So what you are trying to do is pointless :)</p>\n" }, {...
2008/09/17
[ "https://Stackoverflow.com/questions/82881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2273/" ]
Lets say I have a Dictionary object: ``` Dictionary myDictionary<int, SomeObject> = new Dictionary<string, SomeObject>(); ``` Now I want to iterate through the dictionary in reverse order. I can't use a simple for loop because I don't know the keys of the dictionary. A *foreach* is easy: ``` foreach (SomeObject object in myDictionary.Values) { // Do stuff to object } ``` But how can I perform this in reverse?
I'd use a SortedList instead of a dictionary. You can still access it by Key, but you can access it by index as well. ``` SortedList sCol = new SortedList(); sCol.Add("bee", "Some extended string matching bee"); sCol.Add("ay", "value matching ay"); sCol.Add("cee", "Just a standard cee"); // Go through it backwards. for (int i = sCol.Count - 1; i >=0 ; i--) Console.WriteLine("sCol[" + i.ToString() + "] = " + sCol.GetByIndex(i)); // Reference By Key foreach (string i in sCol.Keys) Console.WriteLine("sCol[" + i + "] = " + sCol[i]); // Enumerate all values foreach (string i in sCol.Values) Console.WriteLine(i); ``` It's worth noting that a sorted list stores key/value pairs sorted by key only.
82,908
<p>I have several RequiredFieldValidators in an ASP.NET 1.1 web application that are firing on the client side when I press the Cancel button, which has the CausesValidation attribute set to "False". How can I get this to stop? </p> <p>I do not believe that Validation Groups are supported in 1.1.</p> <p>Here's a code sample: </p> <pre><code>&lt;asp:TextBox id="UsernameTextBox" runat="server"&gt;&lt;/asp:TextBox&gt; &lt;br /&gt; &lt;asp:RequiredFieldValidator ID="UsernameTextBoxRequiredfieldvalidator" ControlToValidate="UsernameTextBox" runat="server" ErrorMessage="This field is required."&gt;&lt;/asp:RequiredFieldValidator&gt; &lt;asp:RegularExpressionValidator ID="UsernameTextBoxRegExValidator" runat="server" ControlToValidate="UsernameTextBox" Display="Dynamic" ErrorMessage="Please specify a valid username (6 to 32 alphanumeric characters)." ValidationExpression="[0-9,a-z,A-Z, ]{6,32}"&gt;&lt;/asp:RegularExpressionValidator&gt; &lt;asp:Button CssClass="btn" id="addUserButton" runat="server" Text="Add User"&gt;&lt;/asp:Button&gt; &lt;asp:Button CssClass="btn" id="cancelButton" runat="server" Text="Cancel" CausesValidation="False"&gt;&lt;/asp:Button&gt; </code></pre> <p><strong>Update:</strong> There was some dynamic page generating going on in the code behind that must have been messing it up, because when I cleaned that up it started working.</p>
[ { "answer_id": 82923, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 0, "selected": false, "text": "<p>Are they in separate validation groups (the button and validator controls)?</p>\n\n<p>You're not manually calling t...
2008/09/17
[ "https://Stackoverflow.com/questions/82908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15815/" ]
I have several RequiredFieldValidators in an ASP.NET 1.1 web application that are firing on the client side when I press the Cancel button, which has the CausesValidation attribute set to "False". How can I get this to stop? I do not believe that Validation Groups are supported in 1.1. Here's a code sample: ``` <asp:TextBox id="UsernameTextBox" runat="server"></asp:TextBox> <br /> <asp:RequiredFieldValidator ID="UsernameTextBoxRequiredfieldvalidator" ControlToValidate="UsernameTextBox" runat="server" ErrorMessage="This field is required."></asp:RequiredFieldValidator> <asp:RegularExpressionValidator ID="UsernameTextBoxRegExValidator" runat="server" ControlToValidate="UsernameTextBox" Display="Dynamic" ErrorMessage="Please specify a valid username (6 to 32 alphanumeric characters)." ValidationExpression="[0-9,a-z,A-Z, ]{6,32}"></asp:RegularExpressionValidator> <asp:Button CssClass="btn" id="addUserButton" runat="server" Text="Add User"></asp:Button> <asp:Button CssClass="btn" id="cancelButton" runat="server" Text="Cancel" CausesValidation="False"></asp:Button> ``` **Update:** There was some dynamic page generating going on in the code behind that must have been messing it up, because when I cleaned that up it started working.
Validation Groups were not added to ASP.NET until version 2.0. This is a 1.1 question. Double check your setting and make sure you are not overwriting it in the code behind.
82,914
<p>I don't think this is possible just using the color setting in SpriteBatch, so I'm trying to work out a simple shader that would take every pixel and make it white, while respecting the alpha value of the pixel.</p> <p>The answer Joel Martinez gave looks right, but how do I incorporate that when I draw the sprite with SpriteBatch?</p>
[ { "answer_id": 83004, "author": "Neoaikon", "author_id": 15837, "author_profile": "https://Stackoverflow.com/users/15837", "pm_score": 0, "selected": false, "text": "<p>I haven't wrote my own pixel shaders, mostly modified samples from the net, what you would do is you would increase the...
2008/09/17
[ "https://Stackoverflow.com/questions/82914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11911/" ]
I don't think this is possible just using the color setting in SpriteBatch, so I'm trying to work out a simple shader that would take every pixel and make it white, while respecting the alpha value of the pixel. The answer Joel Martinez gave looks right, but how do I incorporate that when I draw the sprite with SpriteBatch?
I think this is what you're looking for ``` sampler2D baseMap; struct PS_INPUT { float2 Texcoord : TEXCOORD0; }; float4 ps_main( PS_INPUT Input ) : COLOR0 { float4 color = tex2D( baseMap, Input.Texcoord ); return float4(1.0f, 1.0f, 1.0f, color.w); } ``` It's very simple, it just takes the sampled color from the texture, and then returns an all white color using the texture's alpha value.