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": 80885, "author": "Raithlin", "author_id": 6528, "author_profile": "https://Stackoverflow.com/users/6528", "pm_score": 3, "selected": false, "text": "<p>Visual Studio 2008 defaults this to F12, but you can set it in Tools | Options | Environment | Keyboard, and change Edit.GoToDefinition - however, I'm not sure how you can get it to CTRL+mouseclick.</p>\n" }, { "answer_id": 80889, "author": "Catalin DICU", "author_id": 13030, "author_profile": "https://Stackoverflow.com/users/13030", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.jetbrains.com/resharper/\" rel=\"nofollow noreferrer\">Resharper</a> does that but it's not free.\nHighly recommended plugin though, most experienced .NET developers use it.</p>\n" }, { "answer_id": 80935, "author": "badp", "author_id": 13992, "author_profile": "https://Stackoverflow.com/users/13992", "pm_score": 4, "selected": true, "text": "<p>You could create an Autohotkey script that does that. When you ctrl-click a word, send a doubleclick then a F12.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n" }, { "answer_id": 2633651, "author": "Tianhao Qiu", "author_id": 315969, "author_profile": "https://Stackoverflow.com/users/315969", "pm_score": 2, "selected": false, "text": "<p>Just a quick note that the following AutoHotkey script works for me in Visual C++ 2010 Express.</p>\n\n<pre><code>SetTitleMatchMode 2\n#IfWinActive, Microsoft Visual C++ 2010 Express\n^LButton::Send {click}{f12}\n</code></pre>\n\n<p>I also changed the shortcuts for View.NavigateForward and View.NavigateBackward to Alt+Right/Left Arrow since I am used to Eclipse.</p>\n" }, { "answer_id": 3051588, "author": "splintor", "author_id": 46635, "author_profile": "https://Stackoverflow.com/users/46635", "pm_score": 3, "selected": false, "text": "<p>Not for Visual Studio 2008, but if you upgrade to Visual Studio 2010, you can use the free \n<a href=\"http://visualstudiogallery.msdn.microsoft.com/en-us/d0d33361-18e2-46c0-8ff2-4adea1e34fef\" rel=\"noreferrer\">Visual Studio 2010 Pro Power Tools</a> from Microsoft to achieve this.</p>\n" }, { "answer_id": 7895889, "author": "doogie", "author_id": 915228, "author_profile": "https://Stackoverflow.com/users/915228", "pm_score": 2, "selected": false, "text": "<p>Yes, both Resharper (a must have!) and Productivity Power Tools have this feature. </p>\n\n<p>Interesting quirk, though. </p>\n\n<p>If you just go with the defaults on both tools (if you install both tools) you can experience a frequent double-jump problem (jump to definition from where you first click and then jump again from what your cursor is above upon getting to that first definition) until you turn off one of the Ctrl-Click features of these add-ons.</p>\n" } ]
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-different-databases\" rel=\"nofollow noreferrer\"><code>self.establish_connection</code></a>.</p>\n" }, { "answer_id": 81207, "author": "Jean", "author_id": 7898, "author_profile": "https://Stackoverflow.com/users/7898", "pm_score": 3, "selected": false, "text": "<p>You can programmatically establish a connection using a call like this </p>\n\n<pre><code>ActiveRecord::Base.establish_connection(\n :adapter =&gt; \"mysql\",\n :host =&gt; \"localhost\",\n :username =&gt; \"myuser\",\n :password =&gt; \"mypass\",\n :database =&gt; \"somedatabase\"\n)\n</code></pre>\n\n<p>As you see you can replace the somedatabase by a <code>database_model.database_name</code> value. The same is true with the adapter and all.</p>\n\n<p>See <a href=\"http://api.rubyonrails.com/classes/ActiveRecord/Base.html#M001397\" rel=\"nofollow noreferrer\"><code>ActiveRecord::Base.establish_connection</code> documentation</a> for more information.</p>\n\n<p>Then you can use: </p>\n\n<pre><code>ActiveRecord::Base.find_by_sql(\"select * \") \n</code></pre>\n\n<p>to execute your SQL query. </p>\n\n<p>See <a href=\"http://api.rubyonrails.com/classes/ActiveRecord/Base.html#M001302\" rel=\"nofollow noreferrer\"><code>ActiveRecord::Base.find_by_sql</code> documentation</a> for more information.</p>\n\n<p><a href=\"https://stackoverflow.com/users/12037/mr-matt\">Mr Matt</a> was right if incomplete.</p>\n\n<p>More information, which is outdated but still useful for the design approach, can be found <a href=\"http://wiki.rubyonrails.org/rails/pages/HowtoUseMultipleDatabases\" rel=\"nofollow noreferrer\">here</a> and remember to reconnect to the normal database when you are done.</p>\n" }, { "answer_id": 3737505, "author": "brokenbeatnik", "author_id": 90709, "author_profile": "https://Stackoverflow.com/users/90709", "pm_score": 4, "selected": true, "text": "<p>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:</p>\n\n<pre><code> def get_custom_connection(identifier, host, port, dbname, dbuser, password)\n eval(\"Custom_#{identifier} = Class::new(ActiveRecord::Base)\")\n eval(\"Custom_#{identifier}.establish_connection(:adapter=&gt;'mysql', :host=&gt;'#{host}', :port=&gt;#{port}, :database=&gt;'#{dbname}', \" +\n \":username=&gt;'#{dbuser}', :password=&gt;'#{password}')\") \n return eval(\"Custom_#{identifier}.connection\")\n end\n</code></pre>\n\n<p>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.</p>\n" } ]
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're loading from disk, but you will still need the Event-listener. \nThere's a good example of how to set this up (Complete with IOErrorEvent handling) in the <a href=\"http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Sound.html#load()\" rel=\"nofollow noreferrer\">livedocs</a>.</p>\n" }, { "answer_id": 83236, "author": "Antti", "author_id": 6037, "author_profile": "https://Stackoverflow.com/users/6037", "pm_score": 4, "selected": true, "text": "<p><a href=\"http://livedocs.adobe.com/flex/3/langref/flash/errors/IOError.html\" rel=\"noreferrer\">IOError</a> = target file cannot be found (or for some other reason cannot be read). Check your file's path.</p>\n\n<p>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:</p>\n\n<pre>var sound:Sound = new Sound();\nsound.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);\nsound.load(new URLRequest(\"directory/file.mp3\"));\n\nfunction ioErrorHandler(event:IOErrorEvent):void {\n trace(\"IO error occurred\");\n}\n</pre>\n" }, { "answer_id": 86120, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 1, "selected": false, "text": "<p>try...catch only applies for errors that are thrown when that function is called. Any kind of method that involves loading stuff from the network, disk, etc will be asynchronous, that is it doesn't execute right when you call it, but instead it happens sometime shortly after you call it. In that case you DO need the addEventListener in order to catch any errors or events or to know when it's finished loading. </p>\n" } ]
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\n<p>Unixes only allow a set number of links to directories - \"..\" from within all its children and \".\" from within itself. Anything else is potentially a recipe for a very confused directory tree. This is/was apparently a design decision by Ken Thompson.</p>\n\n<p>(Having said that, apparently Apple's Time Machine does do this :) )</p>\n" }, { "answer_id": 81163, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Yes it's supported by the kernel and the filesystem, but since it's not intended for general usage it's not exposed to the shell.</p>\n\n<p>You could probably work out which APIs Time Machine uses and wrap them in a commandline tool, but it'd be better to take the hint and steer well-clear.</p>\n" }, { "answer_id": 805001, "author": "username", "author_id": 4939, "author_profile": "https://Stackoverflow.com/users/4939", "pm_score": 6, "selected": true, "text": "<p>You can't do it directly in BASH then. However... I found an article here that discusses how to do it indirectly: <a href=\"http://www.mactech.com/articles/mactech/Vol.23/23.11/ExploringLeopardwithDTrace/index.html\" rel=\"noreferrer\">http://www.mactech.com/articles/mactech/Vol.23/23.11/ExploringLeopardwithDTrace/index.html</a> by compiling a simple little C program:</p>\n\n<pre><code>#include &lt;unistd.h&gt;\n#include &lt;stdio.h&gt;\n\nint main(int argc, char *argv[])\n{\n if (argc != 3) return 1;\n\n int ret = link(argv[1], argv[2]);\n\n if (ret != 0) perror(\"link\");\n\n return ret;\n}\n</code></pre>\n\n<p>...and build in Terminal.app with:</p>\n\n<pre><code>$ gcc -o hlink hlink.c -Wall\n</code></pre>\n" }, { "answer_id": 1565096, "author": "Jesper Rønn-Jensen", "author_id": 109305, "author_profile": "https://Stackoverflow.com/users/109305", "pm_score": 2, "selected": false, "text": "<p>My case was that I found out that from a windows virtual machine, I cannot follow symlinks. (i wanted to test some HTML pages in Internet Explorer). And my directory structure had symlinks for CSS and images folders.</p>\n\n<p>My workaround to solve the problem was a different approach than the other answers implied. I used <code>rsync</code> to create a copy of the folder. Rsync can resolve the symlinks and copy the linked files in stead.</p>\n\n<p>This solved my problem without using hard links to directories. And it's actually an easy solution if you're just working on a small set of files.</p>\n\n<pre><code>rsync -av --copy-dirlinks --delete ../htmlguide ~/src/\n</code></pre>\n" }, { "answer_id": 2038065, "author": "Rich", "author_id": 247592, "author_profile": "https://Stackoverflow.com/users/247592", "pm_score": 4, "selected": false, "text": "<p>Piffle. On 10.5, it tells you in the man page for <strong>ln</strong>:</p>\n\n<pre><code> -d, -F, --directory\n allow the superuser to attempt to hard link directories (note:\n will probably fail due to system restrictions, even for the\n superuser)\n</code></pre>\n\n<p>So yes:</p>\n\n<pre><code> sudo ln -d existing_dir new_hard_link\n</code></pre>\n\n<p>Give it your password, and <strong>you're not done yet</strong>. You didn't document it, did you? You <strong>must</strong> document hard linked directories; even if it's a single user machine.</p>\n\n<p>Deleting is a different story: if you go about it the usual way to delete directories, you'll delete the contents. So you <strong>must</strong> \"unlink\" the directory:</p>\n\n<pre><code> unlink new_hard_link\n</code></pre>\n\n<p>There. Hope you don't wreck your filesystem!</p>\n" }, { "answer_id": 3938981, "author": "Gannet", "author_id": 802862, "author_profile": "https://Stackoverflow.com/users/802862", "pm_score": 1, "selected": false, "text": "<p>From the article linked to, you'll get that error if you try to create the hard link in the same directory as the original. You have to create it somewhere else.</p>\n" }, { "answer_id": 4707231, "author": "Bob", "author_id": 577700, "author_profile": "https://Stackoverflow.com/users/577700", "pm_score": 6, "selected": false, "text": "<p>I agree that hard-linking folders/directories can cause problems if not careful, but they have a very definite advantage - Time Machine is a perfect example. Without them it simply would not be practical as the duplication of redundant versions of files would very quickly consume even the largest of disks.</p>\n<p>Snow Leopard can create hard links to directories as long as you follow Amit Singh's six rules:</p>\n<ol>\n<li>The file system must be journaled HFS+.</li>\n<li>The parent directories of the source and destination must be different.</li>\n<li>The source’s parent must not be the root directory.</li>\n<li>The destination must not be in the root directory.</li>\n<li>The destination must not be a descendent of the source.</li>\n<li>The destination must not have any ancestor that’s a directory hard link.</li>\n</ol>\n<p>So it's not correct at all that Snow Leopard has lost the ability to create hard links to\nfolders.</p>\n<p>I just verified that link/unlink do work on Snow Leopard - as long as you follow the six\nrules. I just tried it and it works fine on my Snow Leopard 10.6.6 system - tried it on the boot volume and on a separate USB external volume and it worked fine in both cases.</p>\n<p>Here is the &quot;hunlink.c&quot; program:</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;unistd.h&gt;\nint\nmain(int argc, char *argv[])\n{\n if (argc != 2)\n return 1;\n int ret = unlink(argv[1]);\n if (ret != 0)\n perror(&quot;unlink&quot;);\n return ret;\n}\n\ngcc -o hunlink hunlink.c\n</code></pre>\n<p>So, be careful if you try it - remember to follow the rules and use hlink to create these hard links and use hunlink to remove the hard link afterwards. And don't forget to document\nwhat you've done for later on or for someone else who might need to know this.</p>\n<p>One other &quot;gotcha&quot; that I just learned about these &quot;hard links&quot; to folders. When you create them there is really a lot that happens &quot;behind the curtain&quot; of Mac OS X. One really important issue is that the folder you create the link to is really moved to a super-magical super-hidden folder called /.HFS+ Private Directory Data%000d/dir_xxx where xxx is the inode number of the &quot;source_folder&quot; - remember the format of the command is</p>\n<pre><code>hlink source_folder target_folder\n</code></pre>\n<p>So because of this, you have to be careful of not having any files open in the &quot;source_folder&quot; because if you do, they just got moved to the super-magical folder and you will likely have a problem if you try and save any changes to those files that were open in the &quot;source_folder&quot;. This happened to me a couple of times until it dawned on me what was happening and the solution is pretty simple. I noticed that you couldn't do a &quot;ls -la&quot; command any longer without getting funny errors for all the folders/directories that were in the original &quot;source_folder&quot; but you could do a &quot;ls&quot; command and all looked well.</p>\n<p>If you run &quot;Verify disk&quot; in the &quot;Disk Utility&quot; program, you will notice that it probably complains and gives a &quot;Volume bitmap needs minor repair for orphaned blocks&quot; which is what just happened with the creation of the super-magical folder and the movement of the &quot;source_folder&quot; to it.</p>\n<p>If you do find yourself in this situation with &quot;orphaned blocks&quot;, first save the changed files to some other temporary location not in the volume containing the &quot;source_folder&quot; tree, then use &quot;Disk Utility&quot; to unmount and remount the volume that contains the &quot;source_folder&quot; or just restart the computer. Then copy the files you saved to the temporary locations back to their original locations and you should be back in business. This is what worked for me, so can't guarantee this will work for you too. So it might be a good idea to try this out on a volume you have a good backup of just in case.</p>\n<p>It seems so very weird that all this overhead occurs just for the simple task of creating a hard link to a folder. Does anyone have any idea why Mac OS X goes to all this effort for this hard link creation to folders? Does it have something to do with the fact that this is a &quot;journaled&quot; file system?</p>\n<p>I discovered the info about the super-magical, super-hidden location by reading Amit Singh's explanation of his &quot;hfsdebug&quot; utility. If you want more details see his web site at <a href=\"https://web.archive.org/web/20200910033812/https://osxbook.com/blog/2008/11/09/hfsdebug-40-and-new-hfs-features/\" rel=\"nofollow noreferrer\">Amit Singh's hfsdebug utility</a>. It's a very interesting piece of software and will tell you lots of details about HFS+ file systems. It's free and I encourage you to download it and try it out. It's no longer supported but it still works on both Snow Leopard and Leopard - basically any HFS+ supported system. You can't really do any harm with it as it's a &quot;read-only&quot; tool - so it's great to use to look at some details of the filesystem.</p>\n<p>One more issue about these &quot;hard links to folders&quot; - once you create one and the super-magical super-secret-hidden folder gets created, it's there for good. Even if you unlink the folder that caused it to be created in the first place, this magic folder stays around. Not sure why, but it definitely does. You can use &quot;hfsdebug&quot; to find this out if you wish to try it out. You can also use &quot;hfsdebug&quot; to find out how many of these &quot;hard links to folders&quot; exist on a drive. For these details refer to Amit's article on the &quot;hfsdebug&quot; utility.</p>\n<p>He also has another newer utility that's supported but costs. It's called fileXray and costs $79 for one person on any number of computers in the same household for a personal non-business type license. It has an extensive 173-page User Guide that you can download to see what it can do before you purchase. Unfortunately there is no trial version, so read the manual and check out the web site for more details to see if it can help you out of a jam. Learn all the details about it at their web site - see <a href=\"https://web.archive.org/web/20200103162305/https://filexray.com/\" rel=\"nofollow noreferrer\">fileXray web site</a> for more info.</p>\n<p>There are a couple of issues you should be aware of when using these hard links to folders. If the volume that they are created on is mounted to a remote client, there can be significant problems, depending on how they are mounted. If you use AFP to mount the volume to a remote client, there are big problems as any folder that currently has a hard link to it or has ever had one but later removed, will be unable to be used as all the lower level folders (but not files) will be inaccessible from either the Finder or a Terminal window. If you try to do a simple &quot;ls -lR&quot; command, it will fail and give you &quot;ls: xxx: No such file or directory&quot; error messages for all lower level folders. If you use a Finder window to traverse the directory tree of the remote volume, the folders that are in the folder that had or has a hard link to it will simply disappear without any error when you first click on the folder name.</p>\n<p>These problems don't appear to occur (except for the error message) if you use NFS to mount the remote client (and assuming you had a NFS server on the system that has the volume as a local HFS+ filesystem). Details on how to use NFS to mount volumes are not provided here. I used a nice program from Dr. Marcel Bresink called &quot;NFS Manager&quot; to help with the NFS mounts on the server and client. You can get it from his web site - just search for &quot;Bresink NFS Manager&quot; in your favorite search engine, but he has a free trial version so you can try before you buy. It's not that big a deal if you want to learn how to do the NFS mounts, but the &quot;NFS Manager&quot; makes it pretty easy to set things up and to tweak all the different settings to help optimize it. He has several other neat Mac OS X utilities too that are very reasonably priced - one called &quot;Hardware Monitor&quot; that lets you monitor and graph all kinds of things like power usage, temperature of CPU, speed of fans and many many other variables for both the local and remote Mac systems over extended periods of time (from minutes to days). Definitely worth checking out if you are into handy utilities.</p>\n<p>One thing I did notice is that NFS file transfers were about 20% slower than doing them via AFP, but your &quot;mileage may vary&quot;, so no guarantees one way or the other, but I would rather have something that works even if I have to pay a 20% performance hit as compared to having nothing work at all.</p>\n<p>Apple is aware of the problems with hard links and remote AFP filesystems, and they refer to it as an &quot;implentation limitation&quot; of the AFP client - I prefer to call it what it really appears to me to be - A BUG!!! I can only hope the next release of Mac OS X fixes the problem, as I really like having the ability to use hard links to folders when it makes sense.</p>\n<p>These notes are my own personal opinion and I don't make any warranty about their correctness so use them at your own risk. Have a good backup before you play around with these &quot;hard links to folders&quot; just in case something unforeseen happens. But I hope you have fun if you do decide to look a bit more into this interesting aspect of Mac OS X.</p>\n" }, { "answer_id": 14842414, "author": "Kit Sunde", "author_id": 29347, "author_profile": "https://Stackoverflow.com/users/29347", "pm_score": 0, "selected": false, "text": "<p>Another solution is to use bindfs <a href=\"https://code.google.com/p/bindfs/\" rel=\"nofollow\">https://code.google.com/p/bindfs/</a> which is installable via port:</p>\n\n<pre><code>sudo port install bindfs\nsudo bindfs ~/source_dir ~/target_dir\n</code></pre>\n" }, { "answer_id": 20601652, "author": "Nuray Altin", "author_id": 577674, "author_profile": "https://Stackoverflow.com/users/577674", "pm_score": -1, "selected": false, "text": "<p>in case there is no sub folder, you can try</p>\n\n<p><strong>ln folder_path/*<em></strong>.</em><strong>* target_folder</strong></p>\n\n<p>it worked for me on OSX 10.9</p>\n" }, { "answer_id": 36540025, "author": "zainengineer", "author_id": 3232611, "author_profile": "https://Stackoverflow.com/users/3232611", "pm_score": 1, "selected": false, "text": "<p>In Linux you can use bind mount to simulate hard linking directories. Not sure about OSX</p>\n\n<pre><code>sudo mount --bind /some/existing_real_contents /else/dummy_but_existing_directory\nsudo umount /else/dummy_but_existing_directory\n</code></pre>\n" }, { "answer_id": 37742750, "author": "Simon East", "author_id": 195835, "author_profile": "https://Stackoverflow.com/users/195835", "pm_score": 4, "selected": false, "text": "<p><em>Cross-posting <a href=\"https://stackoverflow.com/a/5118678/195835\">this great tool</a> which neatly solves the problem, originally posted by <a href=\"https://stackoverflow.com/users/634331/sam\">Sam</a>:</em></p>\n\n<hr>\n\n<p>To install Hardlink, ensure you've installed <a href=\"http://brew.sh/\" rel=\"noreferrer\">homebrew</a>, then run:</p>\n\n<pre><code>brew install hardlink-osx\n</code></pre>\n\n<p>Once installed, create a hard link with:</p>\n\n<pre><code>hln [source] [destination]\n</code></pre>\n\n<p>I also noticed that <code>unlink</code> command does not work on snow leopard, so I added an option to unlink:</p>\n\n<pre><code>hln -u destination\n</code></pre>\n\n<hr>\n\n<p>Code is available on Github for those who are interested: <a href=\"https://github.com/selkhateeb/hardlink\" rel=\"noreferrer\">https://github.com/selkhateeb/hardlink</a></p>\n" }, { "answer_id": 39472511, "author": "techiejohn", "author_id": 4805400, "author_profile": "https://Stackoverflow.com/users/4805400", "pm_score": 1, "selected": false, "text": "<p>This can also be done with built-in Perl (from Terminal) without compiling anything. My specific use case is for Google Drive (which doesn't support symbolic links), so the examples below reflect the use case.</p>\n\n<p>To link your \"Documents\" folder to Google Drive so it's synced:</p>\n\n<pre><code>perl -e 'link \"/Users/me/Documents\", \"/Users/me/Google Drive/Documents\"'\n</code></pre>\n\n<p>To remove the link to your \"Documents\" folder from Google Drive:</p>\n\n<pre><code>sudo perl -U -e 'unlink \"/Users/me/Google Drive/Documents\"'\n</code></pre>\n\n<p>You need \"root\" to unlink (see \"unlink\" perldoc).</p>\n" }, { "answer_id": 39891753, "author": "ccpizza", "author_id": 191246, "author_profile": "https://Stackoverflow.com/users/191246", "pm_score": 3, "selected": false, "text": "<p>The OSX version of <code>ln</code> cannot do it, but, as mentioned in the other answer by <a href=\"https://stackoverflow.com/a/2038065/191246\">rich</a>, it is possible with the GNU version of <code>ln</code> which is available in <a href=\"http://brew.sh\" rel=\"nofollow noreferrer\">homebrew</a> as <code>gln</code> as part of the <a href=\"http://brewformulas.org/Coreutil\" rel=\"nofollow noreferrer\">coreutils</a> formula. <code>man gln</code> lists the <code>-d</code> option with the OSX-specific warning provided in <a href=\"https://stackoverflow.com/a/2038065/191246\">rich</a>'s answer. In other words, it does not work in all cases. What exactly determines whether it works or not does not seem to be documented anywhere.</p>\n\n<p>As a prerequisite, install <code>coreutils</code>:</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code> brew install coreutils\n</code></pre>\n\n<p>Now you can do:</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code> sudo gln -d /original_folder /mirror_folder\n</code></pre>\n\n<p><strong>IMPORTANT</strong>: To remove the hard link you <strong><em>must</em></strong> use <code>gunlink</code>:</p>\n\n<pre><code> sudo gunlink /mirror_folder\n</code></pre>\n\n<blockquote>\n <p>❗️❗️❗️ <strong>Using <code>rm</code> or Finder will also delete the original folder.</strong></p>\n</blockquote>\n\n<p>FYI: The <a href=\"http://brewformulas.org/Coreutil\" rel=\"nofollow noreferrer\">coreutils</a> homebrew formula provides the GNU-compatible versions of generic unix tools. Use <code>brew list coreutils</code> to see the full list.</p>\n" }, { "answer_id": 52754343, "author": "ariel", "author_id": 242076, "author_profile": "https://Stackoverflow.com/users/242076", "pm_score": 2, "selected": false, "text": "<p>As of 2018 no longer possible. APFS (introduced in MacOS High Sierra 10.13) is not compatible with directory hardlinks. See <a href=\"https://github.com/selkhateeb/hardlink/issues/31\" rel=\"nofollow noreferrer\">https://github.com/selkhateeb/hardlink/issues/31</a></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.</p>\n" }, { "answer_id": 81961, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>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.</p>\n" }, { "answer_id": 81979, "author": "Lee Gathercole", "author_id": 15204, "author_profile": "https://Stackoverflow.com/users/15204", "pm_score": 1, "selected": false, "text": "<p>This might be a step too far, but have you considered using WCF and the callback element of WCF?</p>\n\n<p>Callback effectively turns the what was client into a server. To be honest, I don't know a great deal about callback and have only experimented. Perhaps worth a 10 minute google though.</p>\n" }, { "answer_id": 201201, "author": "csgero", "author_id": 21764, "author_profile": "https://Stackoverflow.com/users/21764", "pm_score": 0, "selected": false, "text": "<p>As you are talking about COM and remote computers, I suspect you'll have to do some DCOM security configuration.</p>\n" } ]
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.Text.RegularExpressions using balanced matching. See more here: <a href=\"http://blogs.msdn.com/bclteam/archive/2005/03/15/396452.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/bclteam/archive/2005/03/15/396452.aspx</a> </p>\n\n<p>If you're using .NET you can probably implement what you need with a callback. \nIf not, you may have to roll your own little javascript parser.</p>\n\n<p>Then again, if you can afford to hit the server you can use the full parser. :)</p>\n\n<p>What do you need this for, anyway? If it is for anything other than a preview I highly recommend doing the processing server-side.</p>\n" }, { "answer_id": 81123, "author": "vava", "author_id": 6258, "author_profile": "https://Stackoverflow.com/users/6258", "pm_score": 0, "selected": false, "text": "<p>Yes, you will have to loop. Alternatively since your tags looks so much like HTML ones you could replace <code>[b]</code> for <code>&lt;b&gt;</code> and <code>[/b]</code> for <code>&lt;/b&gt;</code> separately. (.){1,}? is the same as (.*?) - that is, any symbols, least possible sequence length.</p>\n\n<p>Updated: Thanks to MrP, (.){1,}? is (.)+?, my bad.</p>\n" }, { "answer_id": 81142, "author": "Richard Szalay", "author_id": 3603, "author_profile": "https://Stackoverflow.com/users/3603", "pm_score": 0, "selected": false, "text": "<p>You are right about the inner pattern being troublesome.</p>\n\n<pre><code>((.){1,}?)\n</code></pre>\n\n<p>That is doing a captured match at least once and then the whole thing is captured. Every character inside your tag will be captured as a group.</p>\n\n<p>You are also capturing your closing element name when you don't need it and are using <code>{1}</code> when that is implied. Below is a cleanup up version:</p>\n\n<pre><code>/\\[(b|u|i|s|center|code)](.+?)\\[\\/\\1]/ig\n</code></pre>\n\n<p>Not sure about the other problem.</p>\n" }, { "answer_id": 81393, "author": "Marijn", "author_id": 12038, "author_profile": "https://Stackoverflow.com/users/12038", "pm_score": 0, "selected": false, "text": "<p>You could just repeatedly apply the regexp until it no longer matches. That would do odd things like \"[b][b]foo[/b][/b]\" => \"&lt;b>[b]foo&lt;/b>[/b]\" => \"&lt;b>&lt;b>foo&lt;/b>&lt;/b>\", but as far as I can see the end result will still be a sensible string with matching (though not necessarily properly nested) tags.</p>\n\n<p>Or if you want to do it 'right', just write a simple recursive descent parser. Though people might expect \"[b]foo[u]bar[/b]baz[/u]\" to work, which is tricky to recognise with a parser.</p>\n" }, { "answer_id": 81418, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 0, "selected": false, "text": "<p>The reason the nested block doesn't get replaced is because the match, for [b], places the position after [/b]. Thus, everything that ((.){1,}?) matches is then ignored.</p>\n\n<p>It is possible to write a recursive parser in server-side -- Perl uses <a href=\"http://perldoc.perl.org/functions/qr.html\" rel=\"nofollow noreferrer\">qr//</a> and Ruby probably has something similar.</p>\n\n<p>Though, you don't necessarily need true recursive. You can use a relatively simple loop to handle the string equivalently:</p>\n\n<pre><code>var s = '[b]hello[/b] [u]world[/u] [b]foo [u]to the[/u] bar[/b]';\nvar exptags = /\\[(b|u|i|s|center|code){1}]((.){1,}?)\\[\\/(\\1){1}]/ig;\n\nwhile (s.match(exptags)) {\n s = s.replace(exptags, \"&lt;$1&gt;$2&lt;/$1&gt;\");\n}\n\ndocument.writeln('&lt;div&gt;' + s + '&lt;/div&gt;'); // after\n</code></pre>\n\n<p>In this case, it'll make 2 passes:</p>\n\n<pre><code>0: [b]hello[/b] [u]world[/u] [b]foo [u]to the[/u] bar[/b]\n1: &lt;b&gt;hello&lt;/b&gt; &lt;u&gt;world&lt;/u&gt; &lt;b&gt;foo [u]to the[/u] bar&lt;/b&gt;\n2: &lt;b&gt;hello&lt;/b&gt; &lt;u&gt;world&lt;/u&gt; &lt;b&gt;foo &lt;u&gt;to the&lt;/u&gt; bar&lt;/b&gt;\n</code></pre>\n\n<hr>\n\n<p>Also, a few suggestions for cleaning up the RegEx:</p>\n\n<pre><code>var exptags = /\\[(b|u|i|s|center|code)\\](.+?)\\[\\/(\\1)\\]/ig;\n</code></pre>\n\n<ul>\n<li>{1} is assumed when no other count specifiers exist</li>\n<li>{1,} can be shortened to +</li>\n</ul>\n" }, { "answer_id": 81573, "author": "Joe Hildebrand", "author_id": 8388, "author_profile": "https://Stackoverflow.com/users/8388", "pm_score": 0, "selected": false, "text": "<p>Agree with Richard Szalay, but his regex didn't get quoted right:</p>\n\n<pre><code>var exptags = /\\[(b|u|i|s|center|code)](.*)\\[\\/\\1]/ig;\n</code></pre>\n\n<p>is cleaner. Note that I also change <code>.+?</code> to <code>.*</code>. There are two problems with <code>.+?</code>:</p>\n\n<ol>\n<li>you won't match [u][/u], since there isn't at least one character between them (+)</li>\n<li>a non-greedy match won't deal as nicely with the same tag nested inside itself (?)</li>\n</ol>\n" }, { "answer_id": 82990, "author": "freespace", "author_id": 8297, "author_profile": "https://Stackoverflow.com/users/8297", "pm_score": 0, "selected": false, "text": "<p>How about:</p>\n\n<pre><code>tagreg=/\\[(.?)?(b|u|i|s|center|code)\\]/gi;\n\"[b][i]helloworld[/i][/b]\".replace(tagreg, \"&lt;$1$2&gt;\");\n\"[b]helloworld[/b]\".replace(tagreg, \"&lt;$1$2&gt;\");\n</code></pre>\n\n<p>For me the above produces:</p>\n\n<pre><code>&lt;b&gt;&lt;i&gt;helloworld&lt;/i&gt;&lt;/b&gt;\n&lt;b&gt;helloworld&lt;/b&gt;\n</code></pre>\n\n<p>This appears to do what you want, and has the advantage of needing only a single pass.</p>\n\n<p>Disclaimer: I don't code often in JS, so if I made any mistakes please feel free to point them out :-)</p>\n" }, { "answer_id": 83441, "author": "A Nony Mouse", "author_id": 7182, "author_profile": "https://Stackoverflow.com/users/7182", "pm_score": 2, "selected": false, "text": "<p>The easiest solution would be to to replace all the tags, whether they are closed or not and let <code>.innerHTML</code> work out if they are matched or not it will much more resilient that way..</p>\n\n<pre><code>var tagreg = /\\[(\\/?)(b|u|i|s|center|code)]/ig\ndiv.innerHTML=\"[b][i]helloworld[/b]\".replace(tagreg, \"&lt;$1$2&gt;\") //no closing i\n//div.inerHTML==\"&lt;b&gt;&lt;i&gt;helloworld&lt;/i&gt;&lt;/b&gt;\"\n</code></pre>\n" } ]
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 or those registered by other modules in the application.</p>\n" }, { "answer_id": 81087, "author": "Sylvain Defresne", "author_id": 5353, "author_profile": "https://Stackoverflow.com/users/5353", "pm_score": 4, "selected": true, "text": "<p>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 <code>atexit</code> module.</p>\n\n<p>Something like that :</p>\n\n<pre><code>import sys\nimport atexit\n\ndef clear_atexit_excepthook(exctype, value, traceback):\n atexit._exithandlers[:] = []\n sys.__excepthook__(exctype, value, traceback)\n\ndef helloworld():\n print \"Hello world!\"\n\nsys.excepthook = clear_atexit_excepthook\natexit.register(helloworld)\n\nraise Exception(\"Good bye cruel world!\")\n</code></pre>\n\n<p>Beware that it may behave incorrectly if the exception is raised from an <code>atexit</code> registered function (but then the behaviour would have been strange even if this hook was not used).</p>\n" }, { "answer_id": 81107, "author": "Ber", "author_id": 11527, "author_profile": "https://Stackoverflow.com/users/11527", "pm_score": 0, "selected": false, "text": "<p>In addition to calling os._exit() to avoid the registered exit handler you also need to catch the unhandled exception:</p>\n\n<pre><code>import atexit\nimport os\n\ndef helloworld():\n print \"Hello World!\"\n\natexit.register(helloworld) \n\ntry:\n raise Exception(\"Good bye cruel world!\")\n\nexcept Exception, e:\n print 'caught unhandled exception', str(e)\n\n os._exit(1)\n</code></pre>\n" } ]
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 name.</p>\n\n<p>So if you have the files x.txt, x171go and x171stop, the following will happen:</p>\n\n<pre><code>Press keys: Command line is:\nx x\n&lt;ESC&gt;\\ x\n1 x1\n&lt;ESC&gt;\\ x171\ng&lt;ESC&gt;\\ x171go\n</code></pre>\n" }, { "answer_id": 86599, "author": "Brian Deterling", "author_id": 14619, "author_profile": "https://Stackoverflow.com/users/14619", "pm_score": 2, "selected": false, "text": "<p>Extending the other answers: &lt;ESC&gt;* will list all matching files on the command line. Then you can use the standard vi editing commands to remove the ones you don't care about. So to add to the above table:</p>\n\n<pre><code>&lt;ESC&gt;&lt;shift-8&gt; x.txt x171 x171go\n</code></pre>\n\n<p>Then use backspace to go get rid of the last two, or hit &lt;ESC&gt; again and use the h or b to go backwards and dw to delete the ones you don't want.</p>\n" } ]
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>\n\n<p>Yes, only methods can be declared virtual.</p>\n" }, { "answer_id": 81064, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 2, "selected": false, "text": "<p>You would use abstract if you do not want to define any implementation in the base class and want to force it to be defined in any derived classes. Define it as a virtual if you want to provide a default implementatio that can be overriden by derived classes.</p>\n\n<p>Yes, only methods can be virtual.</p>\n" }, { "answer_id": 81090, "author": "Seb Rose", "author_id": 12405, "author_profile": "https://Stackoverflow.com/users/12405", "pm_score": 0, "selected": false, "text": "<p>Abstract means that you can't provide a default implementation. This in turn means that all subclasses must provide an implementation of the abstract method in order to be instantiable (concrete).</p>\n\n<p>I'm not sure what you mean by 'limitations', so can't answer that point.</p>\n\n<p>Properties can be declared virtual, but you can conceptually think of them as methods too.</p>\n" }, { "answer_id": 81093, "author": "Richard Szalay", "author_id": 3603, "author_profile": "https://Stackoverflow.com/users/3603", "pm_score": 2, "selected": false, "text": "<p>A member should be declared virtual if there is a base implementation, but there is a possibility of that functionality being overridden in a child class. Virtual can also be used instead of abstract to allow a method implementation to be optional (ie. the base implementation is an empty method)</p>\n\n<p>There is no limitation when setting a member as virtual, but virtual members are slower than non-virtual methods.</p>\n\n<p>Both methods and properties can be marked as virtual.</p>\n" }, { "answer_id": 81167, "author": "Sakin", "author_id": 12818, "author_profile": "https://Stackoverflow.com/users/12818", "pm_score": 0, "selected": false, "text": "<p>First of all, I will answer you second question. Only methods can be declared virtual.\nYou would choose virtual instead of abstract when you want some default functionality in your base class, but you want to leave the option of overriding this functionality by classes that inherit from your base class.\nFor examples:</p>\n\n<p>If you are implementing the <strong>Shape</strong> class, you would probably have a method called <strong>getArea()</strong> that returns the area of your shape. In this case, there's no default behavior for the getArea() method in the Shape class, so you would implement it as <strong>abstract</strong>. Implementing a method as abstract will prevent you to instantiate a <strong>Shape</strong> object.</p>\n\n<p>On the other hand, if you implement the class <strong>Dog</strong>, you may want to implement the method <strong>Bark()</strong> in this case, you may want to implement a default barking sound and put it in the <strong>Dog</strong> class, while some inherited classes, like the class <strong>Chiwawa</strong> may want to override this method and implement a specific barking sound. In this case, the method bark will be implemented as <strong>virtual</strong> and you will be able to instantiate Dogs as well as Chiwawas.</p>\n" }, { "answer_id": 81171, "author": "Kokuma", "author_id": 12088, "author_profile": "https://Stackoverflow.com/users/12088", "pm_score": 4, "selected": true, "text": "<p>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.</p>\n\n<p>A virtual method or property must have a body, i.e. you must provide an implementation (even if the body is empty).</p>\n\n<p>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.</p>\n\n<p>Exemple :</p>\n\n<pre><code>using System;\nusing C=System.Console;\n\nnamespace Foo\n{\n public class Bar\n {\n public static void Main(string[] args)\n {\n myImplementationOfTest miot = new myImplementationOfTest();\n miot.myVirtualMethod();\n miot.myOtherVirtualMethod();\n miot.myProperty = 42;\n miot.myAbstractMethod();\n }\n }\n\n public abstract class test\n {\n public abstract int myProperty\n {\n get;\n set;\n }\n\n public abstract void myAbstractMethod();\n\n public virtual void myVirtualMethod()\n {\n C.WriteLine(\"foo\");\n }\n\n public virtual void myOtherVirtualMethod()\n {\n }\n }\n\n public class myImplementationOfTest : test\n {\n private int _foo;\n public override int myProperty\n {\n get { return _foo; }\n set { _foo = value; }\n }\n\n public override void myAbstractMethod()\n {\n C.WriteLine(myProperty);\n }\n\n public override void myOtherVirtualMethod()\n {\n C.WriteLine(\"bar\");\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 81239, "author": "Benjol", "author_id": 11410, "author_profile": "https://Stackoverflow.com/users/11410", "pm_score": 1, "selected": false, "text": "<p>There is a gotcha here to be aware of with Windows Forms.</p>\n\n<p>If you want a Control/UserControl from which you can inherit, even if you have no logic in the base class, you don't want it abstract, because otherwise you won't be able to use the Designer in the derived classes:\n<a href=\"http://www.urbanpotato.net/default.aspx/document/2001\" rel=\"nofollow noreferrer\">http://www.urbanpotato.net/default.aspx/document/2001</a></p>\n" }, { "answer_id": 81935, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 0, "selected": false, "text": "<p>You question is more related to style than technicalities. I think that this book\n<a href=\"https://rads.stackoverflow.com/amzn/click/com/0321246756\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">http://www.amazon.com/Framework-Design-Guidelines-Conventions-Development/dp/0321246756</a>\nhas great discussion around your question and lots of others.</p>\n" }, { "answer_id": 91235, "author": "Chris Canal", "author_id": 5802, "author_profile": "https://Stackoverflow.com/users/5802", "pm_score": 0, "selected": false, "text": "<p>I personally mark most methods and properties virtual. I use proxies and lazy loading alot, so I don't want to have to worry about changing things at a later date.</p>\n" } ]
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-checking is kind of lost. I highly doubt any other browsers are using the Chrome userAgent string, so if your question is 'is this browser Chrome', you should just look at that. (By the way, window.ActiveXObject does not guarantee IE, there are plug-ins for other browsers that provide this object. Which kind of illustrates the point I was trying to make.)</p>\n" }, { "answer_id": 81179, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 1, "selected": false, "text": "<p>So, if you accept Marijn's point and <em>are</em> interested in testing the user agent string via javascript:</p>\n\n<p><code>var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') &gt; -1;</code></p>\n\n<p>(Credit to: <a href=\"http://davidwalsh.name/detecting-google-chrome-javascript\" rel=\"nofollow noreferrer\">http://davidwalsh.name/detecting-google-chrome-javascript</a> )</p>\n\n<hr>\n\n<p>Here's a really nice analysis/breakdown of the chromes user agent string: <a href=\"http://www.simonwhatley.co.uk/whats-in-google-chromes-user-agent-string\" rel=\"nofollow noreferrer\">http://www.simonwhatley.co.uk/whats-in-google-chromes-user-agent-string</a></p>\n" }, { "answer_id": 84699, "author": "pcorcoran", "author_id": 15992, "author_profile": "https://Stackoverflow.com/users/15992", "pm_score": 6, "selected": true, "text": "<pre><code>isChrome = function() {\n return Boolean(window.chrome);\n}\n</code></pre>\n" }, { "answer_id": 84756, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You shouldn't be detecting Chrome specifically. If anything, you should be detecting WebKit, since as far as page rendering is concerned, Chrome should behave exactly like other WebKit browsers (Safari, Epiphany).</p>\n\n<p>If you need not only to detect WebKit, but also find out exactly what version is being used, see this link: <a href=\"http://trac.webkit.org/wiki/DetectingWebKit\" rel=\"nofollow noreferrer\">http://trac.webkit.org/wiki/DetectingWebKit</a></p>\n\n<p>But again, as other people said above, you shouldn't detect browsers, you should detect features. See this ADC article for more on this: <a href=\"http://developer.apple.com/internet/webcontent/objectdetection.html\" rel=\"nofollow noreferrer\">http://developer.apple.com/internet/webcontent/objectdetection.html</a></p>\n" }, { "answer_id": 582486, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>One reason you might need to know the browser is Chrome is because it 'is' so damn standards compliant. I have already run into problems with old JavaScript code which I thought was standards compliant (by FF or Opera standards - which are pretty good), but Chrome was even more picky. It forced me to rewriting some code, but at times it might be easier to use the if(isChrome) { blah...blah ) trick to get it running. Chrome seems to work very well (I'm for standard compliance), but sometimes you just need to know what the user is running in grave detail.</p>\n\n<p>Also, Chrome is very fast. Problem is, some JavaScript code unintentionally depends on the slowness of other browsers to work properly, ie: page loading, iframe loading, placement of stylesheet links and javascript links in page head, etc. These can cause new problems with when functions are really available to interact with page elements. So for now, you really might need to know...</p>\n" }, { "answer_id": 582823, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>For all the standards nazis... sometimes you might want to use bleeding \"standard technologies\" which aren't just yet standard but they will be... Such as css3 features.</p>\n\n<p>Which is the reason why I found this page.</p>\n\n<p>For some reason, Safari runs a combo of border-radius with box-shadow just fine, but chrome doesn't render the combination correctly. So it would be nice to find a way to detect chrome even though it is webkit to disable the combination.</p>\n\n<p>I've ran into hundreds of reasons to detect a specific browser/version which usually ends up in scrapping an idea for a cool feature because what I want to do is not supported by the big evil...</p>\n\n<p>But sometimes, some features are just too cool to not use them, even if they aren't standardized yet.</p>\n" }, { "answer_id": 686616, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I use this code to make bookmarks for each browser (or display a message for webkit)</p>\n\n<pre>\nif (window.sidebar) { \n// Mozilla Firefox Bookmark\nwindow.sidebar.addPanel(title, url,\"\");\n} else if( window.external ) { // IE Favorite\n if(window.ActiveXObject) {\n //ie\n window.external.AddFavorite( url, title);\n } else {\n //chrome\n alert('Press ctrl+D to bookmark (Command+D for macs) after you click Ok');\n }\n} else if(window.opera && window.print) { \n// Opera\n return true; }\n else { //safri\n alert('Press ctrl+D to bookmark (Command+D for macs) after you click Ok'); }\n\n</pre>\n" }, { "answer_id": 2855010, "author": "Jan Turoň", "author_id": 343721, "author_profile": "https://Stackoverflow.com/users/343721", "pm_score": 3, "selected": false, "text": "<p><sub><strong>This answer is very outdated</strong>, but it was very relevant back then in the stone age.</sub></p>\n\n<p>I think feature detect is more usefull than navigator.userAgent parsing, as I googled Opera ambiguosity <a href=\"http://www.javascriptkit.com/javatutors/navigator.shtml\" rel=\"nofollow noreferrer\" title=\"here\">here</a>. Nobody can know if IE16 will parse the /MSIE 16.0;/ regexp - but we can be quite sure, there will be the document.all support. In real life, the features are usually synonyms for the browsers, like: <em>\"No XMLHttpRequest? It is the f....d IE6!\"</em>\nNo nonIE browser supports document.all, but some browsers like Maxthon can scramble the userAgent. (Of course script can define document.all in Firefox for some reason, but it is easilly controllable.) Therefore I suggest this solution.</p>\n\n<p><strong>Edit</strong> <a href=\"http://www.javascriptkit.com/javatutors/objdetect3.shtml\" rel=\"nofollow noreferrer\" title=\"Here\">Here</a> I found complete resources.</p>\n\n<p><strong>Edit 2</strong> I have tested that document.all is also supported by Opera!</p>\n\n<pre><code>var is = {\n ff: window.globalStorage,\n ie: document.all &amp;&amp; !window.opera,\n ie6: !window.XMLHttpRequest,\n ie7: document.all &amp;&amp; window.XMLHttpRequest &amp;&amp; !XDomainRequest &amp;&amp; !window.opera,\n ie8: document.documentMode==8,\n opera: Boolean(window.opera),\n chrome: Boolean(window.chrome),\n safari: window.getComputedStyle &amp;&amp; !window.globalStorage &amp;&amp; !window.opera\n}\n</code></pre>\n\n<p>Using is simple:</p>\n\n<pre><code>if(is.ie6) { ... }\n</code></pre>\n" }, { "answer_id": 2855192, "author": "lunixbochs", "author_id": 293352, "author_profile": "https://Stackoverflow.com/users/293352", "pm_score": 1, "selected": false, "text": "<p>I often use behavior/capability detection. Directly check whether the browser supports functionality before working around it, instead of working around it based on what might be the browser's name (user-agent).</p>\n\n<p>A problem with browser-specific workarounds, is you don't know if the bug has been fixed or if the feature is supported now. When you do capability detection, you <em>know</em> the browser does or doesn't support it directly, and you're not just being browser-ist.</p>\n\n<p><a href=\"http://diveintohtml5.ep.io/everything.html\" rel=\"nofollow noreferrer\">http://diveintohtml5.ep.io/everything.html</a></p>\n" }, { "answer_id": 3197366, "author": "Kean", "author_id": 385799, "author_profile": "https://Stackoverflow.com/users/385799", "pm_score": -1, "selected": false, "text": "<p>isIE: !!(!window.addEventListener &amp;&amp; window.ActiveXObject),</p>\n\n<p>isIE6: typeof document.createElement('DIV').style.maxHeight == \"undefined\",</p>\n\n<p>isIE7: !!(!window.addEventListener &amp;&amp; window.XMLHttpRequest &amp;&amp; !document.querySelectorAll),</p>\n\n<p>isIE8: !!(!window.addEventListener &amp;&amp; document.querySelectorAll &amp;&amp; document.documentMode == 8),</p>\n\n<p>isGecko: navigator.product == 'Gecko',</p>\n\n<p>isOpera: !!window.opera,</p>\n\n<p>isChrome: !!window.chrome,</p>\n\n<p>isWebkit: !!(!window.opera &amp;&amp; !navigator.taintEnable &amp;&amp; document.evaluate &amp;&amp; navigator.product != 'Gecko'),</p>\n" }, { "answer_id": 50942571, "author": "ugur akkurt", "author_id": 7496956, "author_profile": "https://Stackoverflow.com/users/7496956", "pm_score": 0, "selected": false, "text": "<p>There might be false positives since opera also has <code>window.chrome</code> object. As a nice solution I use;</p>\n\n<pre><code>var isOpera = !!window.opera || !!window.opr;// Opera 8.0+\n\nvar isChrome = !!window.chrome &amp;&amp; !isOpera;\n</code></pre>\n\n<p>This solution almost always works. \nHowever one thing I discovered is that, <code>isChrome</code> returns <code>false</code> in iPad Chrome version 52.0 as <code>window.chrome</code> returns <code>false</code>. </p>\n" } ]
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/CSLLKeyboardHook.aspx</a></p>\n\n<p>If you're not using .net 3.5.</p>\n" }, { "answer_id": 193421, "author": "Andy", "author_id": 3857, "author_profile": "https://Stackoverflow.com/users/3857", "pm_score": 3, "selected": false, "text": "<p>I would handle this by using P/Invoke to call RegisterHotKey() for each hotkey, and then use NativeForm (assuming you are using WinForms) to be notified of the WM_HOTKEY message. This should keep most of your hotkey code in one place.</p>\n" }, { "answer_id": 2611761, "author": "Ohad Schneider", "author_id": 67824, "author_profile": "https://Stackoverflow.com/users/67824", "pm_score": 5, "selected": false, "text": "<p>The nicest solution I've found is <a href=\"http://bloggablea.wordpress.com/2007/05/01/global-hotkeys-with-net/\" rel=\"noreferrer\">http://bloggablea.wordpress.com/2007/05/01/global-hotkeys-with-net/</a></p>\n\n<pre><code>Hotkey hk = new Hotkey();\n\nhk.KeyCode = Keys.1;\nhk.Windows = true;\nhk.Pressed += delegate { Console.WriteLine(\"Windows+1 pressed!\"); };\n\nhk.Register(myForm); \n</code></pre>\n\n<p>Note how you can set different lambdas to different hotkeys</p>\n" } ]
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 observer. When you start typing into the text field, the observer sends the search string and the controller returns a list of objects (maximum of 10).</p>\n\n<p>The objects are then sent to render via a partial which fills out the dynamic autocomplete search results. The partial actually populates link_to_remote lines that post back to the controller again. The link_to_remote sends the id of the user selection and then some RJS cleans up the search, fills in the name in the text field, and then places the selected id into a hidden form field.</p>\n\n<p>Phew... I couldn't find a plugin to do this at the time, so I rolled my own, I hope all that makes sense.</p>\n" }, { "answer_id": 81370, "author": "TALlama", "author_id": 5657, "author_profile": "https://Stackoverflow.com/users/5657", "pm_score": 1, "selected": true, "text": "<p>I've got a hackneyed fix for the junk spaces from the image. I added a <code>:after_update_element =&gt; \"trimSelectedItem\"</code> to the options hash of the <code>model_auto_completer</code> (that's the first hash of the three given). My <code>trimSelectedItem</code> then finds the appropriate sub-element and uses the contents of that for the element value:</p>\n\n<pre><code>function trimSelectedItem(element, value, hiddenField, modelID) {\n var span = value.down('span.display-text')\n console.log(span)\n var text = span.innerText || span.textContent\n console.log(text)\n element.value = text\n}\n</code></pre>\n\n<p>However, this then runs afoul of the <code>:allow_free_text</code> 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 <code>:allow_free_text =&gt; true</code> into the options hash (again, the first hash). I'd really rather it remained on, though.</p>\n\n<p>So my current call to create the autocompleter is:</p>\n\n<pre><code>&lt;%= model_auto_completer(\n \"line_items_info[][name]\", \"\", \n \"line_items_info[][id]\", \"\",\n {:url =&gt; formatted_products_path(:js),\n :after_update_element =&gt; \"trimSelectedItem\",\n :allow_free_text =&gt; true},\n {:class =&gt; 'product-selector'},\n {:method =&gt; 'GET', :param_name =&gt; 'q'}) %&gt;\n</code></pre>\n\n<p>And the products/index.js.erb is:</p>\n\n<pre><code> &lt;ul class='products'&gt;\n &lt;%- for product in @products -%&gt;\n &lt;li id=\"&lt;%= dom_id(product) %&gt;\"&gt;\n &lt;%= image_tag image_product_path(product), :alt =&gt; \"\" %&gt;\n &lt;span class='display-text'&gt;&lt;%=h product.name %&gt;&lt;/span&gt;\n &lt;/li&gt;\n &lt;%- end -%&gt;\n &lt;/ul&gt;\n</code></pre>\n" } ]
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 files.</p>\n" }, { "answer_id": 81249, "author": "LohanJ", "author_id": 11286, "author_profile": "https://Stackoverflow.com/users/11286", "pm_score": 0, "selected": false, "text": "<p>Have a look at <a href=\"http://www.mozilla.org/projects/xpcom/\" rel=\"nofollow noreferrer\">XPCOM</a>, there might be something that you can use if Firefox 3 is used by a client.</p>\n" }, { "answer_id": 81332, "author": "Victor", "author_id": 14514, "author_profile": "https://Stackoverflow.com/users/14514", "pm_score": 0, "selected": false, "text": "<p>This is an example that could work for you if what you need is not exactly the path, but a reference to the file working offline.</p>\n\n<p><a href=\"http://www.ab-d.fr/date/2008-07-12/\" rel=\"nofollow noreferrer\">http://www.ab-d.fr/date/2008-07-12/</a></p>\n\n<p>It is in french, but the code is javascript :)</p>\n\n<p>This are the references the article points to:\n<a href=\"http://developer.mozilla.org/en/nsIDOMFile\" rel=\"nofollow noreferrer\">http://developer.mozilla.org/en/nsIDOMFile</a>\n<a href=\"http://developer.mozilla.org/en/nsIDOMFileList\" rel=\"nofollow noreferrer\">http://developer.mozilla.org/en/nsIDOMFileList</a></p>\n" }, { "answer_id": 181526, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "<p>Actually, just before FF3 was out, I did some experiments, and FF2 sends only the filename, like did Opera 9.0. Only IE sends the full path. The behavior makes sense, because the server doesn't have to know where the user stores the file on his computer, it is irrelevant to the upload process. Unless you are writing an intranet application and get the file by direct network access!</p>\n\n<p>What have changed (and that's the real point of the bug item you point to) is that FF3 no longer let access to the file path from JavaScript. And won't let type/paste a path there, which is more annoying for me: I have a shell extension which copies the path of a file from Windows Explorer to the clipboard and I used it a lot in such form. I solved the issue by using the DragDropUpload extension. But this becomes off-topic, I fear.</p>\n\n<p>I wonder what your Web forms are doing to stop working with this new behavior.</p>\n\n<p>[EDIT] After reading the page linked by Mike, I see indeed intranet uses of the path (identify a user for example) and local uses (show preview of an image, local management of files). User Jam-es seems to provide a workaround with nsIDOMFile (not tried yet).</p>\n" }, { "answer_id": 1169691, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This is an alternate solution/fix... In FF3, You can retrieve file's full path in a textbox instead of file browse box. And that too... By drag/dropping the file! </p>\n\n<p>You can drag drop your file into a text box in your html page. and it will display the file's complete path. This data can transferred to your server easily or manipulate them.</p>\n\n<p>All you have to do is to use the extension DragDropUpload</p>\n\n<p><a href=\"http://www.teslacore.it/wiki/index.php?title=DragDropUpload\" rel=\"nofollow noreferrer\">http://www.teslacore.it/wiki/index.php?title=DragDropUpload</a></p>\n\n<p>This extension will helps you in drag dropping files into your File Browse (Input file) box. But still you wont able to get the file full path, If you try to retrieve.</p>\n\n<p>So, I tweaked this extension a little. In the way I can drag drop a file on to any \"Text Input\" box and get the file full path. And thus I can able to get the file full path in FF3 Firefox 3.</p>\n" }, { "answer_id": 1308506, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>One extremely ugly way to resolve this is have the user manually type the directory into a text box, and add this back to the front of the file value in the JavaScript.</p>\n\n<p>Messy... but it depends on the level of user you are working with, and gets around the security issue.</p>\n\n<pre><code>&lt;form&gt;\n &lt;input type=\"text\" id=\"file_path\" value=\"C:/\" /&gt;\n &lt;input type=\"file\" id=\"file_name\" /&gt;\n &lt;input type=\"button\" onclick=\"ajax_restore();\" value=\"Restore Database\" /&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>JavaScript</p>\n\n<pre><code>var str = document.getElementById('file_path').value;\nvar str = str + document.getElementById('file_name').value;\n</code></pre>\n" }, { "answer_id": 1995751, "author": "houba", "author_id": 242775, "author_profile": "https://Stackoverflow.com/users/242775", "pm_score": 3, "selected": false, "text": "<p>For preview in Firefox works this - attachment is object of attachment element in first example:</p>\n\n<pre><code> if (attachment.files)\n previewImage.src = attachment.files.item(0).getAsDataURL();\n else\n previewImage.src = attachment.value;\n</code></pre>\n" }, { "answer_id": 4381889, "author": "Jay", "author_id": 534269, "author_profile": "https://Stackoverflow.com/users/534269", "pm_score": 2, "selected": false, "text": "<p>We can't get complete file path in FF3. The below might be useful for File component customization.</p>\n\n<pre><code>&lt;script&gt;\n\nfunction setFileName()\n{\n var file1=document.forms[0].firstAttachmentFileName.value; \n\n initFileUploads('firstFile1','fileinputs1',file1);\n }\nfunction initFileUploads(fileName,fileinputs,fileValue) {\n var fakeFileUpload = document.createElement('div');\n fakeFileUpload.className = 'fakefile';\n var filename = document.createElement('input');\n filename.type='text';\n filename.value=fileValue;\n filename.id=fileName;\n filename.title='Title';\n fakeFileUpload.appendChild(filename);\n var image = document.createElement('input');\n image.type='button';\n image.value='Browse File';\n image.size=5100;\n image.style.border=0;\n fakeFileUpload.appendChild(image);\n var x = document.getElementsByTagName('input');\n for (var i=0; i&amp;lt;x.length;i++) {\n if (x[i].type != 'file') continue;\n if (x[i].parentNode.className != fileinputs) continue;\n x[i].className = 'file hidden';\n var clone = fakeFileUpload.cloneNode(true);\n x[i].parentNode.appendChild(clone);\n x[i].relatedElement = clone.getElementsByTagName('input')[0];\n x[i].onchange= function () {\n this.relatedElement.value = this.value;\n }}\n if(document.forms[0].firstFile != null &amp;&amp; document.getElementById('firstFile1') != null)\n {\n document.getElementById('firstFile1').value= document.forms[0].firstFile.value;\n document.forms[0].firstAttachmentFileName.title=document.forms[0].firstFile.value;\n }\n}\n\nfunction submitFile()\n{\nalert( document.forms[0].firstAttachmentFileName.value);\n}\n&lt;/script&gt;\n&lt;style&gt;div.fileinputs1 {position: relative;}div.fileinputs2 {position: relative;}\ndiv.fakefile {position: absolute;top: 0px;left: 0px;z-index: 1;}\ninput.file {position: relative;text-align: right;-moz-opacity:0 ;filter:alpha(opacity: 0);\n opacity: 0;z-index: 2;}&lt;/style&gt;\n\n&lt;html&gt;\n&lt;body onLoad =\"setFileName();\"&gt;\n&lt;form&gt;\n&lt;div class=\"fileinputs1\"&gt;\n&lt;INPUT TYPE=file NAME=\"firstAttachmentFileName\" styleClass=\"file\" /&gt;\n&lt;/div&gt;\n&lt;INPUT type=\"button\" value=\"submit\" onclick=\"submitFile();\" /&gt;\n&lt;/form&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" } ]
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.</code> it offers a little popup of all the availble method names. So I think when you type <code>X().</code> it's creating an instance of <code>X</code> in the background and doing a <code>dir</code> or similar to find out the attributes of the object.</p>\n\n<p>So the constructor is only being run <em>once for each object</em> but to give you the interactivity it's creating objects silently in the background without telling you about it.</p>\n" }, { "answer_id": 81751, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "<p>Two small additional points.</p>\n\n<p>First, <code>self.__class__.l.append(1)</code> isn't really sensible.</p>\n\n<p>Just say <code>self.l.append(1)</code>. Python searches the instance before it searches the class for the reference.</p>\n\n<p>More importantly, class-level variables are rarely useful. Class-level constants are sometimes sensible, but even then, they're hard to justify. </p>\n\n<p>In C++ and Java, class-level ('<code>static</code>') variables seem handy, but don't do much of value. They're hard to teach to n00bz -- often wasting lots of classroom time on minutia -- and they aren't very practical. If you want to know all instances of an X that was created, it's probably better to create an XFactory class that doesn't rely on class variables.</p>\n\n<pre><code>class XFactory( object ):\n def __init__( self ):\n self.listOfX= []\n def makeX( self, *args, **kw ):\n newX= X(*args,**kw)\n self.listOfX.append(newX)\n return newX\n</code></pre>\n\n<p>No class-level variable anomalies. And, it doesn't conflate the X's with the collection of X's. In the long run, I find it confusing when a class is both some thing and also some collection of things.</p>\n\n<p>Simpler is better than Complex.</p>\n" }, { "answer_id": 84248, "author": "Bill Barksdale", "author_id": 16113, "author_profile": "https://Stackoverflow.com/users/16113", "pm_score": 2, "selected": false, "text": "<p>Dave Webb is correct, and you can see this by adding a print statement:</p>\n\n<pre><code>&gt;&gt;&gt; class X:\n... l = []\n... def __init__(self):\n... print 'inited'\n... self.__class__.l.append(1)\n... \n</code></pre>\n\n<p>Then as soon as you type the period in <code>X().</code> it prints <code>inited</code> prior to offering you the completion popup.</p>\n" } ]
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 has sat around for a day, I'll give it a shot. It seems from looking at:</p>\n\n<p><a href=\"http://wiki.eclipse.org/TM_and_RSE_FAQ#How_can_I_do_Remote_Debugging_with_CDT.3F\" rel=\"nofollow noreferrer\">http://wiki.eclipse.org/TM_and_RSE_FAQ#How_can_I_do_Remote_Debugging_with_CDT.3F</a></p>\n\n<p>...that even if the CDT has changed since that wiki page was made, you should still be able to change the debug command to:</p>\n\n<p>ssh remotehost gdb</p>\n\n<p>instead of using TM which uses gdbserver. This will probably be slightly slower than the TM remote debugging since that actually uses a local gdb, but on the other hand this way you won't have to NFS or SMB mount your source code to make it available to the local debugger (and if you're on a LAN it probably won't matter anyhow).</p>\n\n<p>There's also a reference TCF implementation for linux, which you may or may not have any luck recompiling for AIX, but it allows for remote debugging if gdbserver is otherwise not available:</p>\n\n<p><a href=\"http://wiki.eclipse.org/DSDP/TM/TCF_FAQ\" rel=\"nofollow noreferrer\">http://wiki.eclipse.org/DSDP/TM/TCF_FAQ</a></p>\n" }, { "answer_id": 323483, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>tried also to remotly debug an aix-appl with windows eclipse-cdt-gdb.\nGot blocked at the end with unix/windows path-problems. Maybe my result can help u a little further - maybe you already got it work. I'm interested in your comment. asked on eclipse news portal- following the answer of martin oberhuber (thanks again) tried dsp dd (also blocked with path problem) and set an request in eclipse bugzilla.</p>\n\n<p>here the link to news: \n<a href=\"http://www.eclipse.org/newsportal/article.php?id=406&amp;group=eclipse.dsdp.tm\" rel=\"nofollow noreferrer\">http://www.eclipse.org/newsportal/article.php?id=406&amp;group=eclipse.dsdp.tm</a>\nHere my bugzilla:\n<a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=252758\" rel=\"nofollow noreferrer\">https://bugs.eclipse.org/bugs/show_bug.cgi?id=252758</a></p>\n\n<p>At the moment we still debug localy with xldb but I am trying ddd-gdb at the moment. At least locally gdb is running.</p>\n" }, { "answer_id": 363441, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>finally I got gdb run remotly anyhow now. At the Bug-symbol on the taskbar I took Debug Configurations - GDB Hardware Debugging.</p>\n\n<p>In Main C/C++ Applications I set the full path on the Samba share of the executable (<code>X:\\abin\\vlmi9506</code>). I also set a linked folder on <code>X:\\abin</code> 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: </p>\n\n<pre><code>plink.exe prevoax1 -l suttera -pw XXXXX -i /proj/user/dev/suttera/vl/9506/test/vlmi9506ddd.run 20155 dev o m\n</code></pre>\n\n<p>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:</p>\n\n<pre><code>gdb -nw -i mi -cd=$LVarPathExec $LVarPathExec/vlmi9506\n</code></pre>\n\n<p>Then IBM just gives gdb 6.0 for AIX. I found version 6.8 in the net at <a href=\"http://www.perzl.org/aix/index.php?n=Main.Gdb\" rel=\"noreferrer\">http://www.perzl.org/aix/index.php?n=Main.Gdb</a>. Our Admin installed it.</p>\n\n<p>I can now step through the program and watch variables. I even can write gdb-commands directly in the console-view. yabadabadooooooo</p>\n\n<p>Hope that helps to others as well. Can not tell, what was really the winner-action.\nBut each answer gives more new questions. Now I got 3 of them.</p>\n\n<ol>\n<li>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?</li>\n<li>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?</li>\n<li>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?</li>\n</ol>\n" } ]
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.myDropDownList.Items.Add(\"\");</p>\n\n<p>As my first list item, and proceed accordingly.</p>\n" }, { "answer_id": 81297, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 2, "selected": false, "text": "<p>The selectedIndex can only be -1 when the control is first initalised and there is no items within the collection.</p>\n\n<p>It's not possible to have no item selected in a web drop down list as you would on a WinForm.</p>\n\n<p>I find it's best to have:\nthis.myDropDownList.Items.Add(new ListItem(\"Please select...\", \"\"));</p>\n\n<p>This way I convey to the user that they need to select an item, and you can check SelectedIndex == 0 to validate</p>\n" }, { "answer_id": 81351, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I am reading the following:\n<a href=\"http://msdn.microsoft.com/en-us/library/a5kfekd2.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/a5kfekd2.aspx</a></p>\n\n<p>It says:\nTo get the index value of the selected item, read the value of the SelectedIndex property. The index is zero-based. If nothing has been selected, the value of the property is -1. </p>\n\n<p>In the same time, at <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist.selectedindex(VS.80).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist.selectedindex(VS.80).aspx</a> we see:</p>\n\n<p>Use the SelectedIndex property to programmatically specify or determine the index of the selected item from the DropDownList control. An item is always selected in the DropDownList control. You cannot clear the selection from every item in the list at the same time.</p>\n\n<p>Perhaps -1 is valid just for getting and not for setting the index? If so, I will use your 'patch'.</p>\n" }, { "answer_id": 81379, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "<p>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...</p>\n\n<pre><code>myDropDownList.DataSource = DataAccess.GetDropDownItems(); // Psuedo Code\nmyDropDownList.DataTextField = \"Value\";\nmyDropDownList.DataValueField = \"Id\";\nmyDropDownList.DataBind();\n\nmyDropDownList.Items.Insert(0, new ListItem(\"Please select\", \"\"));\n</code></pre>\n\n<p>Will add the 'Please select' drop down item to the top.</p>\n\n<p>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.</p>\n" }, { "answer_id": 201012, "author": "Alexander Prokofyev", "author_id": 11256, "author_profile": "https://Stackoverflow.com/users/11256", "pm_score": 3, "selected": false, "text": "<p>It's possible to set <em>selectedIndex</em> property of <em>DropDownList</em> to -1 (i. e. clear selection) using client-side script:</p>\n\n<pre><code>&lt;form id=\"form1\" runat=\"server\"&gt;\n &lt;asp:DropDownList ID=\"DropDownList1\" runat=\"server\"&gt;\n &lt;asp:ListItem Value=\"A\"&gt;&lt;/asp:ListItem&gt;\n &lt;asp:ListItem Value=\"B\"&gt;&lt;/asp:ListItem&gt;\n &lt;asp:ListItem Value=\"C\"&gt;&lt;/asp:ListItem&gt;\n &lt;/asp:DropDownList&gt;\n &lt;button id=\"СlearButton\"&gt;Clear&lt;/button&gt;\n&lt;/form&gt;\n\n&lt;script src=\"jquery-1.2.6.js\" type=\"text/javascript\"&gt;&lt;/script&gt;\n&lt;script type=\"text/javascript\"&gt;\n $(document).ready(function()\n {\n $(\"#СlearButton\").click(function()\n {\n $(\"#DropDownList1\").attr(\"selectedIndex\", -1); // pay attention to property casing\n })\n\n $(\"#ClearButton\").click();\n })\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 11666108, "author": "Vimal Patel", "author_id": 1488039, "author_profile": "https://Stackoverflow.com/users/1488039", "pm_score": 0, "selected": false, "text": "<p>Please try below syntax:</p>\n\n<pre><code>DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(\"Select\"))\n</code></pre>\n\n<p>or</p>\n\n<pre><code>DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText(\"SelectText\"))\n</code></pre>\n\n<p>or </p>\n\n<pre><code>DropDownList1.Items.FindByText(\"Select\").selected =true\n</code></pre>\n\n<p>For more info :\n<a href=\"http://vimalpatelsai.blogspot.in/2012/07/dropdownlistselectedindex-1-problem.html\" rel=\"nofollow\">http://vimalpatelsai.blogspot.in/2012/07/dropdownlistselectedindex-1-problem.html</a></p>\n" }, { "answer_id": 13221668, "author": "Lemaire Stewart", "author_id": 1798517, "author_profile": "https://Stackoverflow.com/users/1798517", "pm_score": 2, "selected": false, "text": "<ol>\n<li>Create your DropDown list and specify an initial ListItem</li>\n<li>Set <code>AppendDataBoundItems</code> to <code>true</code> so that new items get appended.<br></li>\n</ol>\n\n<blockquote>\n<pre><code>&lt;asp:DropDownList ID=\"YourID\" DataSourceID=\"DSID\" AppendDataBoundItems=\"true\"&gt; \n&lt;asp:ListItem Text=\"All\" Value=\"%\"&gt;&lt;/asp:ListItem&gt; \n&lt;/asp:DropDownList&gt;\n</code></pre>\n</blockquote>\n" } ]
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></pre>\n\n<p>The Bytes Per Cluster is the equivalent of the allocation unit. </p>\n" }, { "answer_id": 3561054, "author": "steven", "author_id": 430037, "author_profile": "https://Stackoverflow.com/users/430037", "pm_score": 6, "selected": false, "text": "<p>Use <code>diskpart.exe</code>.</p>\n\n<p>Once you are in diskpart <code>select volume &lt;VolumeNumber&gt;</code> then type <code>filesystems</code>.</p>\n\n<p>It should tell you the file system type and the allocation unit size. It will also tell you the supported sizes etc. Previously mentioned <code>fsutil</code> does work, but answer isn't as clear and I couldn't find a syntax to get the same information for a junction point.</p>\n" }, { "answer_id": 13600516, "author": "eadmaster", "author_id": 791229, "author_profile": "https://Stackoverflow.com/users/791229", "pm_score": 1, "selected": false, "text": "<p>from the commandline:</p>\n\n<p>chkdsk l: (wait for the scan to finish)</p>\n\n<p>sizdir32 <a href=\"http://www.ltr-data.se/opencode.html/\" rel=\"nofollow\">http://www.ltr-data.se/opencode.html/</a></p>\n" }, { "answer_id": 13905409, "author": "robertcollier4", "author_id": 1781201, "author_profile": "https://Stackoverflow.com/users/1781201", "pm_score": 2, "selected": false, "text": "<p>According to <a href=\"http://technet.microsoft.com/en-us/library/cc722475.aspx\" rel=\"nofollow\">Microsoft</a>, the allocation unit size \"Specifies the cluster size for the file system\" - so it is the value shown for \"Bytes Per Cluster\" as shown in:</p>\n\n<pre><code>fsutil fsinfo ntfsinfo C:\n</code></pre>\n" }, { "answer_id": 17445933, "author": "Kunal Mudliyar", "author_id": 2546175, "author_profile": "https://Stackoverflow.com/users/2546175", "pm_score": -1, "selected": false, "text": "<p>start > run > MSINFO32 </p>\n\n<p>goto components </p>\n\n<p>goto storage</p>\n\n<p>goto disk</p>\n\n<p>on the right look for Bytes/Sector</p>\n" }, { "answer_id": 18663186, "author": "J Y", "author_id": 2755186, "author_profile": "https://Stackoverflow.com/users/2755186", "pm_score": 4, "selected": false, "text": "<p>Another way to find it quickly via the GUI on any windows system:</p>\n\n<ol>\n<li><p>create a text file, type a word or two (or random text) in it, and save it.</p></li>\n<li><p>Right-click on the file to show Properties.</p></li>\n<li><p>\"Size on disk\" = allocation unit.</p></li>\n</ol>\n" }, { "answer_id": 23573215, "author": "Markus", "author_id": 1332129, "author_profile": "https://Stackoverflow.com/users/1332129", "pm_score": 2, "selected": false, "text": "<p>You can use SysInternals <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb897424.aspx\" rel=\"nofollow noreferrer\">NTFSInfo</a> by Mark Russinovich from the command line and it converts fsutil fsinfo ntfsinfo into more readable information, especially MFT Table info.</p>\n" }, { "answer_id": 35299012, "author": "Aman Arora", "author_id": 5904669, "author_profile": "https://Stackoverflow.com/users/5904669", "pm_score": 3, "selected": false, "text": "<p>The value for BYTES PER CLUSTER - 65536 = 64K</p>\n\n<pre><code>C:\\temp&gt;fsutil fsinfo drives\n\nDrives: C:\\ D:\\ E:\\ F:\\ G:\\ I:\\ J:\\ N:\\ O:\\ P:\\ S:\\\n\nC:\\temp&gt;fsutil fsinfo ntfsInfo N:\nNTFS Volume Serial Number : 0xfe5a90935a9049f3\nNTFS Version : 3.1\nLFS Version : 2.0\nNumber Sectors : 0x00000002e15befff\nTotal Clusters : 0x000000005c2b7dff\nFree Clusters : 0x000000005c2a15f0\nTotal Reserved : 0x0000000000000000\nBytes Per Sector : 512\nBytes Per Physical Sector : 512\nBytes Per Cluster : 4096\nBytes Per FileRecord Segment : 1024\nClusters Per FileRecord Segment : 0\nMft Valid Data Length : 0x0000000000040000\nMft Start Lcn : 0x00000000000c0000\nMft2 Start Lcn : 0x0000000000000002\nMft Zone Start : 0x00000000000c0000\nMft Zone End : 0x00000000000cc820\nResource Manager Identifier : 560F51B2-CEFA-11E5-80C9-98BE94F91273\n\nC:\\temp&gt;fsutil fsinfo ntfsInfo N:\nNTFS Volume Serial Number : 0x36acd4b1acd46d3d\nNTFS Version : 3.1\nLFS Version : 2.0\nNumber Sectors : 0x00000002e15befff\nTotal Clusters : 0x0000000005c2b7df\nFree Clusters : 0x0000000005c2ac28\nTotal Reserved : 0x0000000000000000\nBytes Per Sector : 512\nBytes Per Physical Sector : 512\nBytes Per Cluster : 65536\nBytes Per FileRecord Segment : 1024\nClusters Per FileRecord Segment : 0\nMft Valid Data Length : 0x0000000000010000\nMft Start Lcn : 0x000000000000c000\nMft2 Start Lcn : 0x0000000000000001\nMft Zone Start : 0x000000000000c000\nMft Zone End : 0x000000000000cca0\nResource Manager Identifier : 560F51C3-CEFA-11E5-80C9-98BE94F91273\n</code></pre>\n" }, { "answer_id": 40792648, "author": "LinusSch", "author_id": 5545874, "author_profile": "https://Stackoverflow.com/users/5545874", "pm_score": 2, "selected": false, "text": "<p>The simple GUI way, as provided by J Y in a previous answer:</p>\n\n<ol>\n<li>Create a small file (not empty)</li>\n<li>Right-click, choose Properties</li>\n<li>Check \"Size on disk\" (in tab General), double-check that your file size is less than half that so that it is certainly using a single allocation unit.</li>\n</ol>\n\n<p>This works well and reminds you of the significance of allocation unit size. But it does have a caveat: as seen in comments to previous answer, Windows will sometimes show \"Size on disk\" as 0 for a very small file. In my testing, NTFS filesystems with allocation unit size 4096 bytes required the file to be 800 bytes to consistently avoid this issue. On FAT32 file systems this issue seems nonexistent, even a single byte file will work - just not empty.</p>\n" }, { "answer_id": 49454825, "author": "SQLing4ever", "author_id": 8507689, "author_profile": "https://Stackoverflow.com/users/8507689", "pm_score": 5, "selected": false, "text": "<p>I know this is an old thread, but there's a newer way then having to use fsutil or diskpart.</p>\n\n<p>Run this powershell command.</p>\n\n<p><code>Get-Volume | Format-List AllocationUnitSize, FileSystemLabel</code></p>\n" }, { "answer_id": 62155278, "author": "Topsy K", "author_id": 13666428, "author_profile": "https://Stackoverflow.com/users/13666428", "pm_score": 3, "selected": false, "text": "<p>Easiest way, confirmed on 2012r2.</p>\n\n<ol>\n<li>Go to \"This PC\"</li>\n<li>Right click on the Disk</li>\n<li>Click on Format</li>\n</ol>\n\n<p>Under drop down \"allocation unit size\" will be the value of what the Allocation of the Unit size disk already is.</p>\n" }, { "answer_id": 68730990, "author": "Khalil Al-rahman Yossefi", "author_id": 5827730, "author_profile": "https://Stackoverflow.com/users/5827730", "pm_score": 2, "selected": false, "text": "<p>In a <code>CMD</code> (as adminstrator), first run <code>diskpart</code>. In the opened program, enter <code>list disk</code>. It'll list all connected disks.\n<a href=\"https://i.stack.imgur.com/b22Qm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/b22Qm.png\" alt=\"list disk\" /></a></p>\n<p>Select the right disk based on its size. If it is flash memory, usually it'd be the last item in the list. In my case, I select the <code>Disk 2</code> using this command: <code>select disk 2</code>.</p>\n<p>After selecting your disk, list the partitions using <code>list partion</code> command. You'll get a list like the one in the image below.\n<a href=\"https://i.stack.imgur.com/4uTsr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4uTsr.png\" alt=\"list partition\" /></a></p>\n<p>Now, it is time to select the right partition, based on its size. In my case, I select Partition 1 using this command: <code>select partition 1</code>.</p>\n<p>Finally, you can run the <code>filesystem</code> command to get the <code>Allocation Unit Size</code>.\n<a href=\"https://i.stack.imgur.com/0265T.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0265T.png\" alt=\"Allocation Unit Size\" /></a></p>\n<p>Note: This procedure works on both <strong>NTFS</strong> and <strong>FAT32</strong>.</p>\n" } ]
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 break the links already on the site.</p>\n" }, { "answer_id": 81250, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 2, "selected": false, "text": "<p>From <a href=\"http://www.javascriptkit.com/howto/htaccess14.shtml\" rel=\"nofollow noreferrer\">this site</a>: (put this in your .htaccess file)</p>\n\n<pre><code>RewriteEngine on\nRewriteCond %{HTTP_REFERER} ^http://((www\\.)?dizzler\\.com [NC]\nRewriteRule .* - [F]\n</code></pre>\n" }, { "answer_id": 81269, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>You could use something like</p>\n\n<pre><code>SetEnvIfNoCase Referer dizzler.com spammer=yes\n\nOrder allow,deny\nallow from all\ndeny from env=spammer\n</code></pre>\n\n<p>Source: <a href=\"http://codex.wordpress.org/Combating_Comment_Spam/Denying_Access\" rel=\"nofollow noreferrer\">http://codex.wordpress.org/Combating_Comment_Spam/Denying_Access</a></p>\n" }, { "answer_id": 81290, "author": "matt lohkamp", "author_id": 14026, "author_profile": "https://Stackoverflow.com/users/14026", "pm_score": 3, "selected": true, "text": "<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.</p>\n\n<p>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 : <a href=\"http://www.evolt.org/article/Using_Apache_to_stop_bad_robots/18/15126/\" rel=\"nofollow noreferrer\">Using Apache to stop bad robots</a> [evolt.org]</p>\n\n<p>If you want an easy way to stop dizzler in particular using the .htaccess, you should be able to pop it open and add:</p>\n\n<pre><code>&lt;Directory /directoryName/subDirectory&gt;\nOrder Allow,Deny\nAllow from all\nDeny from 66.232.150.219\n&lt;/Directory&gt;\n</code></pre>\n" } ]
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>Build a second application whose only job is to open a help file. You can pass the help file name as a command line argument.</p>\n\n<p>You can easily check from your main application whether this help application is running. This will give you full control, as you can decide whether you want to</p>\n\n<ul>\n<li>Send a message to close the help application before opening the secondary help</li>\n<li>Allow more than one instance of the help application to allow different help files to be open at the same time</li>\n<li>Allow the help to remain open after your application closes, or whether you want to send a message to it to close it</li>\n</ul>\n\n<p>You can also check whether an instance of the help application already has the requested help file open and decide whether you want to allow it to be opened a second time, or simply bring the existing instance to the foreground.</p>\n\n<p><em>As stated, this is a workaround - if it turns out to be your only option let me know if you need code examples. Otherwise I'll keep this post clean (and save myself time in the short term) and not clutter it with unnecessary source</em></p>\n" }, { "answer_id": 88869, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 1, "selected": false, "text": "<p>I just tested that and <strong>it works, as expected,</strong> with the kind of code you tried.<br>\nCompiled in D2007/XP, ran in both XP and Vista without problem.</p>\n\n<pre><code>procedure TForm1.Button1Click(Sender: TObject);\nbegin\n Application.HelpFile:= 'depends.chm';\n Application.HelpContext(0);\n HelpFile:='GExperts.chm';\n Application.HelpContext(0);\nend;\n</code></pre>\n\n<p>Both help files open and are alive and well....</p>\n\n<p>Q1: Have you checked the validity of your help files?<br>\nQ2: Where did you place your code?</p>\n" }, { "answer_id": 89010, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Tried. Just works.</p>\n" }, { "answer_id": 90501, "author": "user5888", "author_id": 5888, "author_profile": "https://Stackoverflow.com/users/5888", "pm_score": 3, "selected": false, "text": "<p>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.</p>\n\n<p>To open Help File 1, the following code will work:</p>\n\n<pre><code>procedure TForm1.Button1Click(Sender: TObject);\nbegin\n Application.HelpFile := 'Help File 1.chm';\n Application.HelpContext(0);\nend;\n</code></pre>\n\n<p>To open Help File 2, the following code will work:</p>\n\n<pre><code>procedure TForm1.Button1Click(Sender: TObject);\nbegin\n Application.HelpFile := 'Help File 2.chm';\n Application.HelpContext(0);\nend;\n</code></pre>\n\n<p>But to open both files at the same time, the following code will cause <strong>both help windows to hang</strong>.</p>\n\n<pre><code>procedure TForm1.Button1Click(Sender: TObject);\nbegin\n Application.HelpFile := 'Help File 1.chm';\n Application.HelpContext(0);\n\n Application.HelpFile := 'Help File 2.chm';\n Application.HelpContext(0);\nend;\n</code></pre>\n\n<p><strong>SOLUTION:</strong></p>\n\n<p>The problem is caused by the fact that there are <strong>spaces in the help file names</strong>.</p>\n\n<p>Removing the spaces from the file names will fix the problem.</p>\n\n<p>The following code will work fine:</p>\n\n<pre><code>procedure TForm1.Button1Click(Sender: TObject);\nbegin\n Application.HelpFile := 'HelpFile1.chm';\n Application.HelpContext(0);\n\n Application.HelpFile := 'HelpFile2.chm';\n Application.HelpContext(0);\nend;\n</code></pre>\n" } ]
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 the assembly plugin do what you want, or potentially the shade plugin, and in some cases a combination.</p>\n\n<p>With the assembly plugin you put a manifest file in your project with any necessary settings, although the defaults are usually quite good. Building is then done with</p>\n\n<pre><code>mvn assembly:assembly\n</code></pre>\n\n<p>Or if you have more special things to deal with, one of the other goals. All JAR files to include, are picked up by Maven's dependency resolver. If you use the shade plugin, it is typically part of the install goal, and in one particular project I'm doing now I do</p>\n\n<pre><code>mvn install\nmvn assembly:single\n</code></pre>\n\n<p>The <code>assembly:single</code> goal is to work around lifetime issues, in this case in a <a href=\"http://en.wikipedia.org/wiki/Spring_Framework\" rel=\"nofollow noreferrer\">Spring</a> application.</p>\n" }, { "answer_id": 81277, "author": "PaulF", "author_id": 12041, "author_profile": "https://Stackoverflow.com/users/12041", "pm_score": -1, "selected": false, "text": "<p>Sounds like <a href=\"http://ant.apache.org/\" rel=\"nofollow noreferrer\">Apache Ant</a> is what you're looking for.</p>\n" }, { "answer_id": 81282, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>There is a tool called <a href=\"http://sourceforge.net/projects/autojar/\" rel=\"nofollow noreferrer\">autojar</a> which will scan your bytecode and compile a .jar file with the classes it finds, including referenced (imported) classes.</p>\n\n<p>Doesn't always work with something like Spring, though, where you specify the classnames in configuration and it gets loaded by the framework.</p>\n" }, { "answer_id": 81336, "author": "Stephen Denne", "author_id": 11721, "author_profile": "https://Stackoverflow.com/users/11721", "pm_score": 6, "selected": true, "text": "<p>Eclipse 3.4 JDT's Runnable JAR export wizard.</p>\n\n<p>In Eclipse 3.5, this has been extended. Now you can chose how you want to treat your referenced JAR files.</p>\n" }, { "answer_id": 81482, "author": "Ashley Mercer", "author_id": 13065, "author_profile": "https://Stackoverflow.com/users/13065", "pm_score": 5, "selected": false, "text": "<p>Having tried a few different solutions, I found <a href=\"http://one-jar.sourceforge.net/\" rel=\"noreferrer\">One-JAR</a> the easiest to work with, and have managed to make do exactly that: produce a single, executable JAR which contains everything I need.</p>\n\n<p>One-JAR uses a custom class-loader which can navigate nested resources. Look at the .bat file in the download, it looks like org.codelutin.jrst.JRST in the jrst-0.8.1.jar is the main class, so your manifest should look like this:</p>\n\n<pre><code>Main-Class: com.simontuffs.onejar.Boot\nOne-Jar-Main-Class: org.codelutin.jrst.JRST\n</code></pre>\n\n<p>The really cool thing is that One-JAR will handle passing on command-line arguments for you. The classpath is handled by the custom class loader, assuming all the resources you need are bundled into the single JAR.</p>\n\n<p>The easiest way to use One-JAR is with ant; there's a custom \"one-jar\" ant task which works as follows (assuming your manifest is called \"rst.mf\"):</p>\n\n<pre><code>&lt;target name=\"jar-rst\"&gt;\n &lt;one-jar destfile=\"rst.jar\" manifest=\"rst.mf\"&gt;\n &lt;main jar=\"jrst-0.8.1.jar\" /&gt;\n &lt;lib&gt;\n &lt;fileset dir=\"${pathToJars}\"&gt;\n &lt;include name=\"batik-util-1.6-1.jar\" /&gt;\n &lt;include name=\"icu4j-2.6.1.jar\" /&gt;\n &lt;include name=\"commons-collections-3.1.jar\" /&gt;\n &lt;!-- Snip --&gt;\n &lt;/fileset&gt;\n &lt;/lib&gt;\n &lt;/one-jar&gt;\n&lt;/target&gt;\n</code></pre>\n" }, { "answer_id": 81509, "author": "jrudolph", "author_id": 7647, "author_profile": "https://Stackoverflow.com/users/7647", "pm_score": 3, "selected": false, "text": "<p>There is <a href=\"http://proguard.sourceforge.net/\" rel=\"nofollow noreferrer\">ProGuard</a> which does not only pack your JAR files into one, but it can also optimize, cleanup or obfuscate your class files, making the resulting JAR file much smaller than the sum of all JAR files before.</p>\n\n<p>I actually tried ProGuard with the JRST tool, and it is as you reported. I tried to track the problem down and found it to relate to <a href=\"http://bugs.icu-project.org/trac/ticket/3209\" rel=\"nofollow noreferrer\">a bug</a> in the ICU4J library referenced by jrst. The problem is, that the used ICU version is far outdated right now. So I replaced the <code>icu.jar</code> file with ICU4J version 3.2. Now ProGuard finds a bunch of other errors/warnings about incosistencies with the libraries of JRST.</p>\n\n<p>My guess is that ProGuard works as expected, but the libraries of jrst are just not consistent. I don't know if you can do much more than talk with its developers since they should check and update the dependencies of the project.</p>\n" }, { "answer_id": 81519, "author": "Philip Helger", "author_id": 15254, "author_profile": "https://Stackoverflow.com/users/15254", "pm_score": 2, "selected": false, "text": "<p>Or using the Maven assembly plugin (mvn assembly:assembly)</p>\n" }, { "answer_id": 115805, "author": "Steve g", "author_id": 12092, "author_profile": "https://Stackoverflow.com/users/12092", "pm_score": 3, "selected": false, "text": "<p>You can use <a href=\"http://code.google.com/p/jarjar/\" rel=\"nofollow noreferrer\">JarJar</a> which will use package shadowing to make sure your JAR file doesn't conflict with others.</p>\n" }, { "answer_id": 185116, "author": "akuhn", "author_id": 24468, "author_profile": "https://Stackoverflow.com/users/24468", "pm_score": 6, "selected": false, "text": "<p>Ant's <code>zipfileset</code> does the job</p>\n\n<pre><code>&lt;jar id=\"files\" jarfile=\"all.jar\"&gt;\n &lt;zipfileset src=\"first.jar\" includes=\"**/*.java **/*.class\"/&gt;\n &lt;zipfileset src=\"second.jar\" includes=\"**/*.java **/*.class\"/&gt;\n&lt;/jar&gt;\n</code></pre>\n" }, { "answer_id": 3270607, "author": "simontuffs", "author_id": 394525, "author_profile": "https://Stackoverflow.com/users/394525", "pm_score": 3, "selected": false, "text": "<p>One-JAR 0.97 has just been released at <a href=\"http://one-jar.sourceforge.net\" rel=\"nofollow noreferrer\">http://one-jar.sourceforge.net</a>, and it has been extended wih support for frameworks such as <a href=\"http://en.wikipedia.org/wiki/Spring_Framework\" rel=\"nofollow noreferrer\">Spring</a> and <a href=\"http://en.wikipedia.org/wiki/Google_Guice\" rel=\"nofollow noreferrer\">Guice</a>, which may present trouble to other approaches. It also handles classloader-inversion -- where some JAR files are external to the One-JAR (for example, <a href=\"http://en.wikipedia.org/wiki/Java_Database_Connectivity\" rel=\"nofollow noreferrer\">JDBC</a> drivers which may not be shipped bundled).</p>\n\n<p>One-JAR is command-line, with <a href=\"http://en.wikipedia.org/wiki/Apache_Ant\" rel=\"nofollow noreferrer\">Ant</a> and <a href=\"http://en.wikipedia.org/wiki/Apache_Maven\" rel=\"nofollow noreferrer\">Maven</a> 2 plugins. It's also simple to build just using the \"jar\" tool.</p>\n\n<p>I can also recommend the Eclipse Jar Exporter (Runnable) on which Ference Hechler wrote: he did a great job in coming up with a simple approach to wrapping a set of JAR files. He and I worked on One-JAR, but the Jar Exporter is based on a different codebase.</p>\n" }, { "answer_id": 5652720, "author": "象嘉道", "author_id": 571828, "author_profile": "https://Stackoverflow.com/users/571828", "pm_score": 3, "selected": false, "text": "<p>(based on Andrian's):</p>\n\n<pre><code>&lt;jar id=\"files\" jarfile=\"all.jar\"&gt;\n &lt;zipgroupfileset dir=\"${library.dir}\" includes=\"*.jar\" excludes=\"test-helper.jar\"/&gt;\n &lt;zipfileset src=\"first.jar\" includes=\"**/*.java **/*.class\"/&gt;\n &lt;zipfileset src=\"second.jar\" includes=\"**/*.java **/*.class\"/&gt;\n &lt;fileset dir=\".\"&gt;\n &lt;include name=\"LICENSE\"/&gt;\n &lt;include name=\"NOTICE\"/&gt;\n &lt;/fileset&gt;\n&lt;/jar&gt;\n</code></pre>\n" }, { "answer_id": 24189504, "author": "hoang", "author_id": 2027716, "author_profile": "https://Stackoverflow.com/users/2027716", "pm_score": 0, "selected": false, "text": "<p>You should use maven shading plugin to do that. I often use maven to build standalone jar file and it's so powerful</p>\n\n<p>See more:</p>\n\n<p><a href=\"http://maven.apache.org/plugins/maven-shade-plugin/examples/includes-excludes.html\" rel=\"nofollow\">http://maven.apache.org/plugins/maven-shade-plugin/examples/includes-excludes.html</a></p>\n" }, { "answer_id": 30698416, "author": "Nadir", "author_id": 1641763, "author_profile": "https://Stackoverflow.com/users/1641763", "pm_score": 2, "selected": false, "text": "<p>I think that the tool you need here is <strong>JarSplice</strong>: <a href=\"http://ninjacave.com/jarsplice\" rel=\"nofollow\">http://ninjacave.com/jarsplice</a></p>\n\n<p>It does <strong>not</strong> require Ant or Maven, has its own GUI, it is straightforward to use and do exactly what you asked --> <strong><em>It Merges the content of several jar files into a single one</em></strong> (please note it still need to add its own classloader).</p>\n" } ]
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. There is a way to do this and keep performance if the number of fields is manageable. You make an extra column MyFieldLower. You use a trigger to keep the field filled with a lower case of MyField. </p>\n\n<p>Then the query is:\n WHERE MyFieldLower = LOWER(@MySearch)</p>\n\n<p>This will use indexing.</p>\n" }, { "answer_id": 3090940, "author": "Bipin Daga", "author_id": 372873, "author_profile": "https://Stackoverflow.com/users/372873", "pm_score": 3, "selected": true, "text": "<p>Try creating a <code>functional index</code>, like </p>\n\n<pre><code>Create Index INDX_MY_SEARCH on TABLE_NAME(LOWER(@MySearch)\n</code></pre>\n" }, { "answer_id": 8236651, "author": "kamsky", "author_id": 1061007, "author_profile": "https://Stackoverflow.com/users/1061007", "pm_score": 2, "selected": false, "text": "<p>Add additional upper or lower case column in your select statement. Example:</p>\n\n<pre><code>select col1, upper(col1) upp_col1 from table1 order by upp_col1\n</code></pre>\n" } ]
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 retaining the capability to access an enclosing MyClass object, your problem will be solved. You can then implement a 'getListener' method within MyClass that returns the embedded MyInnerClass that you will use to actually listen to events.</p>\n" }, { "answer_id": 81590, "author": "sirrocco", "author_id": 5246, "author_profile": "https://Stackoverflow.com/users/5246", "pm_score": 2, "selected": true, "text": "<p>Actually I wiredup the event the wrong way :|</p>\n\n<p>I had</p>\n\n<pre><code>EventManager.RegisterClassHandler ( typeof ( MyClass )......\n</code></pre>\n\n<p>Instead of</p>\n\n<pre><code>EventManager.RegisterClassHandler ( typeof ( TheClassThatOwnedTheEvent )\n</code></pre>\n\n<p>So .. my bad.</p>\n" } ]
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>in the codebehind (c#):</p>\n\n<pre><code>string contentType = FileUpload1.PostedFile.ContentType\n</code></pre>\n" }, { "answer_id": 1238450, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>The above code will not give correct content type if file is renamed and uploaded.</p>\n\n<p>Please use this code for that</p>\n\n<pre><code>using System.Runtime.InteropServices;\n\n[DllImport(\"urlmon.dll\", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)]\nstatic extern int FindMimeFromData(IntPtr pBC,\n [MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,\n [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1, SizeParamIndex = 3)] byte[] pBuffer,\n int cbSize,\n [MarshalAs(UnmanagedType.LPWStr)] string pwzMimeProposed,\n int dwMimeFlags, out IntPtr ppwzMimeOut, int dwReserved);\n\npublic static string getMimeFromFile(HttpPostedFile file)\n{\n IntPtr mimeout;\n\n int MaxContent = (int)file.ContentLength;\n if (MaxContent &gt; 4096) MaxContent = 4096;\n\n byte[] buf = new byte[MaxContent];\n file.InputStream.Read(buf, 0, MaxContent);\n int result = FindMimeFromData(IntPtr.Zero, file.FileName, buf, MaxContent, null, 0, out mimeout, 0);\n\n if (result != 0)\n {\n Marshal.FreeCoTaskMem(mimeout);\n return \"\";\n }\n\n string mime = Marshal.PtrToStringUni(mimeout);\n Marshal.FreeCoTaskMem(mimeout);\n\n return mime.ToLower();\n}\n</code></pre>\n" }, { "answer_id": 1814291, "author": "Richard Szalay", "author_id": 3603, "author_profile": "https://Stackoverflow.com/users/3603", "pm_score": 3, "selected": false, "text": "<p>While aneesh is correct in saying that the content type of the HTTP request may not be correct, I don't think that the marshalling for the unmanaged call is worth it. If you need to fall back to extension-to-mimetype mappings, just \"borrow\" the code from System.Web.MimeMapping.cctor (use Reflector). This dictionary approach is more than sufficient and doesn't require the native call.</p>\n" }, { "answer_id": 72055878, "author": "Morten Brudvik", "author_id": 847570, "author_profile": "https://Stackoverflow.com/users/847570", "pm_score": 0, "selected": false, "text": "<p>Get MIME type from a file in ASP.NET Core</p>\n<pre><code>public string GetMimeType(string filePath)\n{\n var provider = new FileExtensionContentTypeProvider();\n\n if (!provider.TryGetContentType(filePath, out var contentType))\n contentType = &quot;application/octet-stream&quot;; // fallback: unknown binary type\n \n return contentType;\n}\n</code></pre>\n" } ]
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>in the codebehind (c#):</p>\n\n<pre><code>string contentType = FileUpload1.PostedFile.ContentType\n</code></pre>\n" }, { "answer_id": 1238450, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>The above code will not give correct content type if file is renamed and uploaded.</p>\n\n<p>Please use this code for that</p>\n\n<pre><code>using System.Runtime.InteropServices;\n\n[DllImport(\"urlmon.dll\", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)]\nstatic extern int FindMimeFromData(IntPtr pBC,\n [MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,\n [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1, SizeParamIndex = 3)] byte[] pBuffer,\n int cbSize,\n [MarshalAs(UnmanagedType.LPWStr)] string pwzMimeProposed,\n int dwMimeFlags, out IntPtr ppwzMimeOut, int dwReserved);\n\npublic static string getMimeFromFile(HttpPostedFile file)\n{\n IntPtr mimeout;\n\n int MaxContent = (int)file.ContentLength;\n if (MaxContent &gt; 4096) MaxContent = 4096;\n\n byte[] buf = new byte[MaxContent];\n file.InputStream.Read(buf, 0, MaxContent);\n int result = FindMimeFromData(IntPtr.Zero, file.FileName, buf, MaxContent, null, 0, out mimeout, 0);\n\n if (result != 0)\n {\n Marshal.FreeCoTaskMem(mimeout);\n return \"\";\n }\n\n string mime = Marshal.PtrToStringUni(mimeout);\n Marshal.FreeCoTaskMem(mimeout);\n\n return mime.ToLower();\n}\n</code></pre>\n" }, { "answer_id": 1814291, "author": "Richard Szalay", "author_id": 3603, "author_profile": "https://Stackoverflow.com/users/3603", "pm_score": 3, "selected": false, "text": "<p>While aneesh is correct in saying that the content type of the HTTP request may not be correct, I don't think that the marshalling for the unmanaged call is worth it. If you need to fall back to extension-to-mimetype mappings, just \"borrow\" the code from System.Web.MimeMapping.cctor (use Reflector). This dictionary approach is more than sufficient and doesn't require the native call.</p>\n" }, { "answer_id": 72055878, "author": "Morten Brudvik", "author_id": 847570, "author_profile": "https://Stackoverflow.com/users/847570", "pm_score": 0, "selected": false, "text": "<p>Get MIME type from a file in ASP.NET Core</p>\n<pre><code>public string GetMimeType(string filePath)\n{\n var provider = new FileExtensionContentTypeProvider();\n\n if (!provider.TryGetContentType(filePath, out var contentType))\n contentType = &quot;application/octet-stream&quot;; // fallback: unknown binary type\n \n return contentType;\n}\n</code></pre>\n" } ]
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 evaluates to result of the assignment, which is 1/true in this case), and thus,</p>\n\n<pre><code>sizeof( f.x = 1)\n</code></pre>\n\n<p>is asking for the size of true in terms of how many chars it would take to store it?</p>\n\n<p>I should also add that the Wikipedia article on <a href=\"http://en.wikipedia.org/wiki/Sizeof\" rel=\"nofollow noreferrer\">sizeof</a> is nice. In particular, they say \"sizeof is a compile-time operator that returns the size, in multiples of the size of char, of the variable or parenthesized type-specifier that it precedes.\"</p>\n\n<p>The article also explains that sizeof works on expressions.</p>\n" }, { "answer_id": 81407, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>sizeof( f.x = 1)\n</code></pre>\n\n<p>returns 1 as its answer. The sizeof(1) is presumably the size of an integer on the platform you are compiling on, probably either 4 or 8 bytes.</p>\n" }, { "answer_id": 81409, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>No, you must be thinking of the == operator, which yields a \"boolean\" expression of type int in C and indeed bool in C++.</p>\n\n<p>I think the expression will convert the value 1 to the correspondin bitfield type and assign it to the bitfield. The result should also be a bitfield type because there are no hidden promotions or conversions that I can see.</p>\n\n<p>Thus we are effectively getting access to the bitfield type.</p>\n\n<p>No compiler diagnostic is required because \"f.x = 1\" isn't an lvalue, i.e. it does not designate the bitfield directly. It's just a value of type \"unsigned :1\".</p>\n\n<p>I'm specifically using \"f.x = 1\" because \"sizeof f.x\" takes the size of a bitfield lvalue, which is clearly not allowed.</p>\n" }, { "answer_id": 81411, "author": "CL.", "author_id": 11654, "author_profile": "https://Stackoverflow.com/users/11654", "pm_score": 1, "selected": false, "text": "<p>Trying to get the size of a bitfield isn't legal, as you have seen. (<code>sizeof</code> returns the size in bytes, which wouldn't make much sense for a bitfield.)</p>\n\n<p><code>sizeof(f.x = 1)</code> will return the size of the type of the expression. Since C doesn't have a real \"bitfield type\", the expression (here: an assignment expression) usually gets the type of the bit field's base type, in your example <code>unsigned int</code>, but it is possible for a compiler to use a smaller type internally (in this case probably <code>unsigned char</code> because it's big enough for one bit).</p>\n" }, { "answer_id": 81413, "author": "mana", "author_id": 12016, "author_profile": "https://Stackoverflow.com/users/12016", "pm_score": 0, "selected": false, "text": "<p>The </p>\n\n<pre><code>(f.x = 1)\n</code></pre>\n\n<p><strong>is not an expression, it is an assignment</strong> and thus returns the assigned value. In this case, the size of that value depends on the variable, it has been assigned to. </p>\n\n<pre><code>unsigned x:1\n</code></pre>\n\n<p>has 1 Bit and its sizeof returns 1 byte (8 bit alignment)</p>\n\n<p>If you would use </p>\n\n<pre><code>unsigned x:12\n</code></pre>\n\n<p>then the sizeof(f.x = 1) would return 2 byte (again because of the 8 bit alignment)</p>\n" }, { "answer_id": 81424, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>The sizeof(1) is presumably the size of an integer on the platform you are compiling on, probably either 4 or 8 bytes.</p>\n</blockquote>\n\n<p>Note that I'm NOT taking sizeof(1), which is effectively sizeof(int). Look close, I'm taking sizeof(f.x = 1), which should effectively be sizeof(bitfield_type).</p>\n\n<p>I'd like to see a reference to something that tells me whether the construct is legal. As an added bonus, it would be nice if it told me what sort of result is expected.</p>\n\n<p>gcc certainly disagrees with the assertion that sizeof(bitfield_type) should be the same as sizeof(int), but only on some platforms.</p>\n" }, { "answer_id": 81438, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Trying to get the size of a bitfield isn't legal, as you have seen. (sizeof returns the size in bytes, which wouldn't make much sense for a bitfield.)</p>\n</blockquote>\n\n<p>So are you stating that the behavior is undefined, i.e. it has the same degree of legality as \"*(int *)0 = 0;\", and compilers can choose to fail to handle this sensibly?</p>\n\n<p>That's what I'm trying to find out. Do you assume that it's undefined by omission, or is there something that explicitly declares it as illegal?</p>\n" }, { "answer_id": 81500, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>is not an expression, it is an assignment and thus returns the assigned value. In this case, the size of that value depends on the variable, it has been assigned to. </p>\n</blockquote>\n\n<p>First, it <strong>IS</strong> an expression containing the assignment operator.</p>\n\n<p>Second, I'm quite aware of what's happening in my example :)</p>\n\n<blockquote>\n <p>then the sizeof(f.x = 1) would return 2 byte (again because of the 8 bit alignment)</p>\n</blockquote>\n\n<p>Where did you get this? Is this what happens on a particular compiler that you have tried, or are these semantics stated in the standard? Because I haven't found any such statements. I want to know whether the construct is guaranteed to work at all.</p>\n" }, { "answer_id": 81577, "author": "mana", "author_id": 12016, "author_profile": "https://Stackoverflow.com/users/12016", "pm_score": 0, "selected": false, "text": "<p>in this second example, if you would define your struct as a</p>\n\n<pre><code>struct foo { unsigned x:12} f;\n</code></pre>\n\n<p>and then write a value like 1 into f.x - it uses 2 Bytes because of the alignment. If you do an assignment like</p>\n\n<pre><code>f.x = 1;\n</code></pre>\n\n<p>and this returns the assigned value. This is quite similar to </p>\n\n<pre><code>int a, b, c;\na = b = c = 1;\n</code></pre>\n\n<p>where the asignment is evaluated from right to left. c = 1 assigns 1 to the variable c and this asignment returns the assigned value and assigns it to b (and so forth) until 1 is assigned to a</p>\n\n<p>it is equal to</p>\n\n<pre><code>a = ( b = ( c = 1 ) )\n</code></pre>\n\n<p>in your case, the sizeof gets the size of your asignment, wich is <strong>NOT</strong> a bitfield, but the variable assigned to it.</p>\n\n<pre><code>sizeof ( f.x = 1)\n</code></pre>\n\n<p>does not return the bitfields size, but the variable assigment which is a 12 bit representation of the 1 (in my case) and therefore sizeof() returns 2 byte (because of the 8bit aligment)</p>\n" }, { "answer_id": 81622, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Look, I understand full well what I'm doing with the assignment trick.</p>\n\n<p>You are telling me that the size of a bitfield type is rounded up to the cloest byte count, which is one option I listed in the initial question. But you didn't back it up with references.</p>\n\n<p>In particular, I have tried various compilers which give me sizeof(int) instead of sizeof(char) EVEN if I apply this to a bitfield with only has a single bit.</p>\n\n<p>I wouldn't even mind if multiple compilers randomly get to choose their own interpretation of this construct. Certainly bitfield storage allocation is quite implementation-defined.</p>\n\n<p>However, I really do want to know whether the construct is <strong>GUARANTEED</strong> to work and yield <strong>SOME</strong> value.</p>\n" }, { "answer_id": 83343, "author": "CL.", "author_id": 11654, "author_profile": "https://Stackoverflow.com/users/11654", "pm_score": 2, "selected": false, "text": "<p>The C99 Standard (<a href=\"http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf\" rel=\"nofollow noreferrer\">PDF of latest draft</a>) says in section 6.5.3.4 about <code>sizeof</code> constraints:</p>\n\n<blockquote>\n <p>The <code>sizeof</code> operator shall not be applied to an expression that has function type or an\n incomplete type, to the parenthesized name of such a type, or to an expression that\n designates a bit-field member.</p>\n</blockquote>\n\n<p>This means that applying <code>sizeof</code> to an <em>assignment expression</em> is allowed.</p>\n\n<p>6.5.16.3 says:</p>\n\n<blockquote>\n <p>The type of an assignment expression is the type of the left operand ...</p>\n</blockquote>\n\n<p>6.3.1.1.2 says regarding integer promotions:</p>\n\n<blockquote>\n <p>The following may be used in an expression wherever an int or unsigned int may be used:</p>\n \n <ul>\n <li>...</li>\n <li>A bit-field of type <code>_Bool</code>, <code>int</code>, <code>signed int</code>, or <code>unsigned int</code>.</li>\n </ul>\n \n <p>If an int can represent all values of the original type,\n the value is converted to an <code>int</code>;\n otherwise, it is converted to an <code>unsigned int</code>.</p>\n</blockquote>\n\n<p>So, your test program should output the size of an <code>int</code>, i.e.,\n<code>sizeof(int)</code>.</p>\n\n<p>Is there any compiler that does not to this?</p>\n" }, { "answer_id": 84202, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>CL, I've seen your citations before, and agree they're totally relevant, but even after having read them I wasn't sure whether the code is defined.</p>\n\n<blockquote>\n <p>6.3.1.1.2 says regarding integer promotions:</p>\n</blockquote>\n\n<p>Yes, but integer promotion rules only apply if a promotion is in fact carried out. I do not think that my example requires a promotion. Likewise if you do</p>\n\n<pre><code>char ch;\nsizeof ch;\n</code></pre>\n\n<p>... then ch also isn't promoted.</p>\n\n<p>I think we are dealing directly with the bitfield type here.</p>\n\n<p>I've also seen gcc output 1 while many other compilers (and even other gcc versions) don't. This doesn't convince me that the code is <strong>illegal</strong> because the size could just as well be implementation-defined enough to make the result inconsistent across multiple compilers.</p>\n\n<p>However, I'm confused as to whether the code may be undefined because nothing in the standard seems to state how the sizeof bitfield case is handled.</p>\n" }, { "answer_id": 84361, "author": "CL.", "author_id": 11654, "author_profile": "https://Stackoverflow.com/users/11654", "pm_score": 3, "selected": true, "text": "<p>You are right, integer promotions aren't applied to the operand of <code>sizeof</code>:</p>\n\n<blockquote>\n <p>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.</p>\n</blockquote>\n\n<p>The real question is whether bitfields have their own types.</p>\n\n<p>Joseph Myers told me:</p>\n\n<blockquote>\n <p>The conclusion\n from C90 DRs was that bit-fields have their own types, and from C99 DRs \n was to leave whether they have their own types implementation-defined, and \n GCC follows the C90 DRs and so the assignment has type int:1 and is not \n promoted as an operand of sizeof.</p>\n</blockquote>\n\n<p>This was discussed in <a href=\"http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_315.htm\" rel=\"nofollow noreferrer\">Defect Report #315</a>.</p>\n\n<p>To summarize: your code is legal but implementation-defined.</p>\n" } ]
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 with trying to get it to interoperate with WCF and a Java client earlier this year and it was an obsolute KNIGHTMARE.</p>\n\n<p>WCF on the other hand is practically sane and the documentation on areas like this is pretty good. Is that an option for you?</p>\n" }, { "answer_id": 92102, "author": "Carl-Johan", "author_id": 15406, "author_profile": "https://Stackoverflow.com/users/15406", "pm_score": 1, "selected": false, "text": "<p>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.</p>\n\n<p>These lines was in the website web.config but not in my other projekt</p>\n\n<pre><code> &lt;soapServerProtocolFactory type=\"Microsoft.Web.Services3.WseProtocolFactory, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" /&gt;\n &lt;soapExtensionImporterTypes&gt;\n &lt;add type=\"Microsoft.Web.Services3.Description.WseExtensionImporter, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" /&gt;\n &lt;/soapExtensionImporterTypes&gt;\n</code></pre>\n\n<p>After I added those lines i got the expected error.</p>\n" } ]
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</blockquote>\n\n<p>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.</p>\n\n<p>I usually stick to throwing exceptions, since they clearly communicate something went wrong and <em>all</em> webservice toolkits have a good way of handling them.</p>\n\n<p>In your sample I would throw an UnauthorizedAccessException with the message \"Account Locked\".</p>\n\n<p><em>Clarification:</em> The .NET wcf services translate exceptions to FaultContracts by default, but you can change this behaviour. <a href=\"http://msdn.microsoft.com/en-us/library/ms733721.aspx\" rel=\"noreferrer\">MSDN:Specifying and Handling Faults in Contracts and Services</a></p>\n" }, { "answer_id": 81374, "author": "ZombieSheep", "author_id": 377, "author_profile": "https://Stackoverflow.com/users/377", "pm_score": 0, "selected": false, "text": "<p>I would seriously consider using the FaultContract and FaultException objects to get around this. This will allow you to pass meaningful error messages back to the client, but only when a fault condition occurs.</p>\n\n<p>Unfortunately, I'm in a training course at the moment, so can't write up a full answer, but as luck would have it I'm learning about exception management in WCF applications. I'll post back tonight with more information. (Sorry it's a feeble answer)</p>\n" }, { "answer_id": 12576782, "author": "Despertar", "author_id": 1160036, "author_profile": "https://Stackoverflow.com/users/1160036", "pm_score": 3, "selected": false, "text": "<p>If you think about calling the service like calling any other method, it may help put things into perspective. Imagine if every method you called returned a status, and you it was up to you to check whether it was true or false. It would get quite tedious. </p>\n\n<pre><code>result = CallMethod();\nif (!result.Success) handleError();\n\nresult = CallAnotherMethod();\nif (!result.Success) handleError();\n\nresult = NotAgain();\nif (!result.Success) handleError();\n</code></pre>\n\n<p>This is one of the strong points of a structured error handling system, is that you can separate your actual logic from your error handling. You don't have to keep checking, you know it was a success if no exception was thrown. </p>\n\n<pre><code>try \n{\n CallMethod();\n CallAnotherMethod();\n NotAgain();\n}\ncatch (Exception e)\n{\n handleError();\n}\n</code></pre>\n\n<p>At the same time, by returning a result you're putting more responsibility on the client. You may well know to check for errors in the result object, but John Doe comes in and just starts calling away to your service, oblivious that anything is wrong because an exception is not thrown. This is another great strength of exceptions is that they give us a good slap in the face when something is wrong and needs to be taken care of.</p>\n" } ]
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]\n[Row(new ThisRepository())]\n[Row(new ThatRepository())]\nPublic void GetFoo_NotNull_Test(IFooRepository repository)\n{\n var results = repository.GetFoo();\n Assert.IsNotNull(results);\n}\n</code></pre>\n" }, { "answer_id": 81395, "author": "RickL", "author_id": 7261, "author_profile": "https://Stackoverflow.com/users/7261", "pm_score": 1, "selected": false, "text": "<p>If you have your 3 copy and pasted test methods, you should be able to refactor (extract method) it to get rid of the duplication.</p>\n\n<p>i.e. this is what I had in mind:</p>\n\n<pre><code>private IRepository GetRepository(RepositoryType repositoryType)\n{\n switch (repositoryType)\n { \n case RepositoryType.Sql:\n // return a SQL repository\n case RepositoryType.Mock:\n // return a mock repository\n // etc\n }\n}\n\nprivate void TestGetFooNotNull(RepositoryType repositoryType)\n{\n IFooRepository repository = GetRepository(repositoryType);\n var results = repository.GetFoo();\n Assert.IsNotNull(results);\n}\n\n[TestMethod]\npublic void GetFoo_NotNull_Sql()\n{\n this.TestGetFooNotNull(RepositoryType.Sql);\n}\n\n[TestMethod]\npublic void GetFoo_NotNull_File()\n{\n this.TestGetFooNotNull(RepositoryType.File);\n}\n\n[TestMethod]\npublic void GetFoo_NotNull_Mock()\n{\n this.TestGetFooNotNull(RepositoryType.Mock);\n}\n</code></pre>\n" }, { "answer_id": 81475, "author": "belugabob", "author_id": 13397, "author_profile": "https://Stackoverflow.com/users/13397", "pm_score": 3, "selected": true, "text": "<p>Create an abstract class that contains concrete versions of the tests and an abstract GetRepository method which returns IFooRepository.\nCreate three classes that derive from the abstract class, each of which implements GetRepository in a way that returns the appropriate IFooRepository implementation.\nAdd all three classes to your test suite, and you're ready to go.</p>\n\n<p>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!)</p>\n" }, { "answer_id": 81810, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 0, "selected": false, "text": "<pre><code>[TestMethod]\npublic void GetFoo_NotNull_Test_ForFile()\n{ \n GetFoo_NotNull(new FileRepository().GetRepository());\n}\n\n[TestMethod]\npublic void GetFoo_NotNull_Test_ForSql()\n{ \n GetFoo_NotNull(new SqlRepository().GetRepository());\n}\n\n\nprivate void GetFoo_NotNull(IFooRepository repository)\n{\n var results = repository. GetFoo(); \n Assert.IsNotNull(results);\n}\n</code></pre>\n" }, { "answer_id": 82513, "author": "Anthony", "author_id": 5599, "author_profile": "https://Stackoverflow.com/users/5599", "pm_score": 0, "selected": false, "text": "<p>To Sum up, there are three ways to go:</p>\n\n<p>1) Make the tests one liners that call down to common methods (answer by Rick, also Hallgrim)</p>\n\n<p>2) Use MBUnit's RowTest feature to automate this (answer by Jon Limjap). I would also use an enum here, e.g.</p>\n\n<pre><code>[RowTest]\n[Row(RepositoryType.Sql)]\n[Row(RepositoryType.Mock)]\npublic void TestGetFooNotNull(RepositoryType repositoryType)\n{\n IFooRepository repository = GetRepository(repositoryType);\n var results = repository.GetFoo();\n Assert.IsNotNull(results);\n}\n</code></pre>\n\n<p>3) Use a base class, answer by belugabob<br>\nI have made a sample based on this idea</p>\n\n<pre><code>public abstract class TestBase\n{\n protected int foo = 0;\n\n [TestMethod]\n public void TestUnderTen()\n {\n Assert.IsTrue(foo &lt; 10);\n }\n\n [TestMethod]\n public void TestOver2()\n {\n Assert.IsTrue(foo &gt; 2);\n }\n}\n\n[TestClass]\npublic class TestA: TestBase\n{\n public TestA()\n {\n foo = 4;\n }\n}\n\n[TestClass]\npublic class TestB: TestBase\n{\n public TestB()\n {\n foo = 6;\n }\n}\n</code></pre>\n\n<p>This produces four passing tests in two test classes.<br>\nUpsides of 3 are:<br>\n1) Least extra code, least maintenance <br>\n2) Least typing to plug in a new repository if need be - it would be done in one place, unlike the others.</p>\n\n<p>Downsides are:<br>\n1) Less flexibility to not run a test against a provider if need be<br>\n2) Harder to read.<br></p>\n" } ]
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\">defaultCharset()</a></p>\n\n<blockquote>\n <p>The default charset is determined\n during virtual-machine startup and\n typically depends upon the locale and\n charset of the underlying operating\n system.</p>\n</blockquote>\n\n<p>In most OSes you can set the charset using a environment variable.</p>\n" }, { "answer_id": 81366, "author": "Mat Mannion", "author_id": 6282, "author_profile": "https://Stackoverflow.com/users/6282", "pm_score": 4, "selected": true, "text": "<p>You need to change the locale before launching the JVM; see:</p>\n\n<p><a href=\"http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=6f932817e77b249681417c21bfaf?bug_id=4163515\" rel=\"noreferrer\">Java, bug ID 4163515</a></p>\n\n<p>Some places seem to imply you can do this by setting the file.encoding variable when launching the JVM, such as </p>\n\n<pre><code>java -Dfile.encoding=UTF-8 ...\n</code></pre>\n\n<p>...but I haven't tried this myself. The safest way is to set an environment variable in the operating system.</p>\n" }, { "answer_id": 12761690, "author": "iileandro", "author_id": 1051999, "author_profile": "https://Stackoverflow.com/users/1051999", "pm_score": 1, "selected": false, "text": "<p>I think you want this: System.setProperty(\"file.encoding\", \"UTF-8\");</p>\n\n<p>It solved some problems, but I still have another ones. The chars \"í\" and \"Í\" doesn't convert correctly if the SO is ISO-8859-1. Just with the JVM option on startup, I get it solved. Now just my Java Console in the NetBeans IDE is crashing charset when showing special chars.</p>\n" } ]
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 what you're asking <em>unless</em> you can do it with something like <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/atomic/AtomicLong.html\" rel=\"nofollow noreferrer\">AtomicLong</a>. I can give that a go in a minute and update. BTW, <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/Hashtable.html\" rel=\"nofollow noreferrer\">Hashtable</a> <em>is</em> a part of the <a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/collections/index.html\" rel=\"nofollow noreferrer\">Collections Framework</a>.</p>\n" }, { "answer_id": 81417, "author": "tovare", "author_id": 12677, "author_profile": "https://Stackoverflow.com/users/12677", "pm_score": 2, "selected": false, "text": "<p>There are a couple of approaches:</p>\n\n<ol>\n<li><p>Use a Bag alorithm like the sets contained in Google Collections.</p></li>\n<li><p>Create mutable container which you can use in the Map:</p></li>\n</ol>\n\n<pre>\n<code>\n class My{\n String word;\n int count;\n }\n</code>\n</pre>\n\n<p>And use put(\"word\", new My(\"Word\") ); Then you can check if it exists and increment when adding.</p>\n\n<p>Avoid rolling your own solution using lists, because if you get innerloop searching and sorting, your performance will stink. The first HashMap solution is actually quite fast, but a proper like that found in Google Collections is probably better.</p>\n\n<p>Counting words using Google Collections, looks something like this:</p>\n\n<pre>\n<code>\n\n HashMultiset s = new HashMultiset();\n s.add(\"word\");\n s.add(\"word\");\n System.out.println(\"\"+s.count(\"word\") );\n\n</code>\n</pre>\n\n<p>Using the HashMultiset is quite elegent, because a bag-algorithm is just what you need when counting words.</p>\n" }, { "answer_id": 81522, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 5, "selected": false, "text": "<p>As a follow-up to my own comment: Trove looks like the way to go. If, for whatever reason, you wanted to stick with the standard JDK, <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ConcurrentMap.html\" rel=\"noreferrer\">ConcurrentMap</a> and <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/atomic/AtomicLong.html\" rel=\"noreferrer\">AtomicLong</a> can make the code a <em>tiny</em> bit nicer, though YMMV.</p>\n<pre><code> final ConcurrentMap&lt;String, AtomicLong&gt; map = new ConcurrentHashMap&lt;String, AtomicLong&gt;();\n map.putIfAbsent(&quot;foo&quot;, new AtomicLong(0));\n map.get(&quot;foo&quot;).incrementAndGet();\n</code></pre>\n<p>will leave <code>1</code> as the value in the map for <code>foo</code>. Realistically, increased friendliness to threading is all that this approach has to recommend it.</p>\n" }, { "answer_id": 81550, "author": "Philip Helger", "author_id": 15254, "author_profile": "https://Stackoverflow.com/users/15254", "pm_score": 4, "selected": false, "text": "<p>Another way would be creating a mutable integer:</p>\n\n<pre><code>class MutableInt {\n int value = 0;\n public void inc () { ++value; }\n public int get () { return value; }\n}\n...\nMap&lt;String,MutableInt&gt; map = new HashMap&lt;String,MutableInt&gt; ();\nMutableInt value = map.get (key);\nif (value == null) {\n value = new MutableInt ();\n map.put (key, value);\n} else {\n value.inc ();\n}\n</code></pre>\n\n<p>of course this implies creating an additional object but the overhead in comparison to creating an Integer (even with Integer.valueOf) should not be so much.</p>\n" }, { "answer_id": 81722, "author": "Glever", "author_id": 15504, "author_profile": "https://Stackoverflow.com/users/15504", "pm_score": 3, "selected": false, "text": "<p>Instead of calling containsKey() it is faster just to call map.get and check if the returned value is null or not.</p>\n\n<pre><code> Integer count = map.get(word);\n if(count == null){\n count = 0;\n }\n map.put(word, count + 1);\n</code></pre>\n" }, { "answer_id": 81765, "author": "Aleksandar Dimitrov", "author_id": 11797, "author_profile": "https://Stackoverflow.com/users/11797", "pm_score": 5, "selected": false, "text": "<p>You should be aware of the fact that your original attempt </p>\n\n<pre>int count = map.containsKey(word) ? map.get(word) : 0;</pre>\n\n<p>contains two potentially expensive operations on a map, namely <code>containsKey</code> and <code>get</code>. The former performs an operation potentially pretty similar to the latter, so you're doing the same work <em>twice</em>!</p>\n\n<p>If you look at the API for Map, <code>get</code> operations usually return <code>null</code> when the map does not contain the requested element.</p>\n\n<p>Note that this will make a solution like</p>\n\n<pre>map.put( key, map.get(key) + 1 );</pre>\n\n<p>dangerous, since it might yield <code>NullPointerException</code>s. You should check for a <code>null</code> first.\n<p><p>\n<b>Also note</b>, and this is very important, that <code>HashMap</code>s <em>can</em> contain <code>nulls</code> by definition. So not every returned <code>null</code> says \"there is no such element\". In this respect, <code>containsKey</code> behaves <em>differently</em> from <code>get</code> in actually telling you <em>whether</em> there is such an element. Refer to the API for details.\n<p><p>\nFor your case, however, you might not want to distinguish between a stored <code>null</code> and \"noSuchElement\". If you don't want to permit <code>null</code>s you might prefer a <code>Hashtable</code>. Using a wrapper library as was already proposed in other answers might be a better solution to manual treatment, depending on the complexity of your application.</p>\n\n<p>To complete the answer (and I forgot to put that in at first, thanks to the edit function!), the best way of doing it natively, is to <code>get</code> into a <code>final</code> variable, check for <code>null</code> and <code>put</code> it back in with a <code>1</code>. The variable should be <code>final</code> because it's immutable anyway. The compiler might not need this hint, but its clearer that way.</p>\n\n<pre>\nfinal HashMap map = generateRandomHashMap();\nfinal Object key = fetchSomeKey();\nfinal Integer i = map.get(key);\nif (i != null) {\n map.put(i + 1);\n} else {\n // do something\n}\n</pre>\n\n<p>If you do not want to rely on autoboxing, you should say something like <code>map.put(new Integer(1 + i.getValue()));</code> instead.</p>\n" }, { "answer_id": 81771, "author": "jb.", "author_id": 7918, "author_profile": "https://Stackoverflow.com/users/7918", "pm_score": 1, "selected": false, "text": "<p>I'd use Apache Collections Lazy Map (to initialize values to 0) and use MutableIntegers from Apache Lang as values in that map. </p>\n\n<p>Biggest cost is having to serach the map twice in your method. In mine you have to do it just once. Just get the value (it will get initialized if absent) and increment it.</p>\n" }, { "answer_id": 82423, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Are you sure that this is a bottleneck? Have you done any performance analysis?</p>\n\n<p>Try using the NetBeans profiler (its free and built into NB 6.1) to look at hotspots.</p>\n\n<p>Finally, a JVM upgrade (say from 1.5->1.6) is often a cheap performance booster. Even an upgrade in build number can provide good performance boosts. If you are running on Windows and this is a server class application, use -server on the command line to use the Server Hotspot JVM. On Linux and Solaris machines this is autodetected.</p>\n" }, { "answer_id": 85007, "author": "volley", "author_id": 13905, "author_profile": "https://Stackoverflow.com/users/13905", "pm_score": 3, "selected": false, "text": "<p>Memory rotation may be an issue here, since every boxing of an int larger than or equal to 128 causes an object allocation (see Integer.valueOf(int)). Although the garbage collector very efficiently deals with short-lived objects, performance will suffer to some degree.</p>\n\n<p>If you know that the number of increments made will largely outnumber the number of keys (=words in this case), consider using an int holder instead. Phax already presented code for this. Here it is again, with two changes (holder class made static and initial value set to 1):</p>\n\n<pre><code>static class MutableInt {\n int value = 1;\n void inc() { ++value; }\n int get() { return value; }\n}\n...\nMap&lt;String,MutableInt&gt; map = new HashMap&lt;String,MutableInt&gt;();\nMutableInt value = map.get(key);\nif (value == null) {\n value = new MutableInt();\n map.put(key, value);\n} else {\n value.inc();\n}\n</code></pre>\n\n<p>If you need extreme performance, look for a Map implementation which is directly tailored towards primitive value types. jrudolph mentioned <a href=\"http://trove4j.sourceforge.net\" rel=\"noreferrer\">GNU Trove</a>.</p>\n\n<p>By the way, a good search term for this subject is \"histogram\".</p>\n" }, { "answer_id": 85342, "author": "Chris Nokleberg", "author_id": 8902, "author_profile": "https://Stackoverflow.com/users/8902", "pm_score": 5, "selected": false, "text": "<p>It's always a good idea to look at the <a href=\"http://code.google.com/p/google-collections/\" rel=\"noreferrer\">Google Collections Library</a> for this kind of thing. In this case a <a href=\"http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multiset.html\" rel=\"noreferrer\">Multiset</a> will do the trick:</p>\n\n<pre><code>Multiset bag = Multisets.newHashMultiset();\nString word = \"foo\";\nbag.add(word);\nbag.add(word);\nSystem.out.println(bag.count(word)); // Prints 2\n</code></pre>\n\n<p>There are Map-like methods for iterating over keys/entries, etc. Internally the implementation currently uses a <code>HashMap&lt;E, AtomicInteger&gt;</code>, so you will not incur boxing costs.</p>\n" }, { "answer_id": 107987, "author": "gregory", "author_id": 10204, "author_profile": "https://Stackoverflow.com/users/10204", "pm_score": 10, "selected": true, "text": "<h2>Some test results</h2>\n\n<p>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:</p>\n\n<ul>\n<li>the \"ContainsKey\" method that I presented in <a href=\"https://stackoverflow.com/questions/81346/most-efficient-way-to-increment-a-map-value-in-java\">the question</a></li>\n<li>the \"TestForNull\" method suggested by Aleksandar Dimitrov</li>\n<li>the \"AtomicLong\" method suggested by Hank Gay</li>\n<li>the \"Trove\" method suggested by jrudolph</li>\n<li>the \"MutableInt\" method suggested by phax.myopenid.com</li>\n</ul>\n\n<h2>Method</h2>\n\n<p>Here's what I did...</p>\n\n<ol>\n<li>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.</li>\n<li>timed the loop of 10 iterations but <em>not the I/O operation</em> and recorded the total time taken (in clock seconds) essentially using <a href=\"http://books.google.com/books?id=t85jM-ZwTX0C&amp;printsec=frontcover&amp;dq=java+cookbook&amp;sig=ACfU3U1lAe1vnbVUwdIcWeTpaxZi1xVUXQ#PPA734,M1\" rel=\"noreferrer\">Ian Darwin's method in the Java Cookbook</a>.</li>\n<li>performed all five tests in series, and then did this another three times.</li>\n<li>averaged the four results for each method.</li>\n</ol>\n\n<h2>Results</h2>\n\n<p>I'll present the results first and the code below for those who are interested.</p>\n\n<p>The <strong>ContainsKey</strong> method was, as expected, the slowest, so I'll give the speed of each method in comparison to the speed of that method.</p>\n\n<ul>\n<li><strong>ContainsKey:</strong> 30.654 seconds (baseline)</li>\n<li><strong>AtomicLong:</strong> 29.780 seconds (1.03 times as fast)</li>\n<li><strong>TestForNull:</strong> 28.804 seconds (1.06 times as fast)</li>\n<li><strong>Trove:</strong> 26.313 seconds (1.16 times as fast)</li>\n<li><strong>MutableInt:</strong> 25.747 seconds (1.19 times as fast)</li>\n</ul>\n\n<h2>Conclusions</h2>\n\n<p>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 <code>final</code> variables, but the difference was negligible.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<h2>The code</h2>\n\n<p>Here is the crucial code from each method.</p>\n\n<h3>ContainsKey</h3>\n\n<pre><code>import java.util.HashMap;\nimport java.util.Map;\n...\nMap&lt;String, Integer&gt; freq = new HashMap&lt;String, Integer&gt;();\n...\nint count = freq.containsKey(word) ? freq.get(word) : 0;\nfreq.put(word, count + 1);\n</code></pre>\n\n<h3>TestForNull</h3>\n\n<pre><code>import java.util.HashMap;\nimport java.util.Map;\n...\nMap&lt;String, Integer&gt; freq = new HashMap&lt;String, Integer&gt;();\n...\nInteger count = freq.get(word);\nif (count == null) {\n freq.put(word, 1);\n}\nelse {\n freq.put(word, count + 1);\n}\n</code></pre>\n\n<h3>AtomicLong</h3>\n\n<pre><code>import java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\nimport java.util.concurrent.atomic.AtomicLong;\n...\nfinal ConcurrentMap&lt;String, AtomicLong&gt; map = \n new ConcurrentHashMap&lt;String, AtomicLong&gt;();\n...\nmap.putIfAbsent(word, new AtomicLong(0));\nmap.get(word).incrementAndGet();\n</code></pre>\n\n<h3>Trove</h3>\n\n<pre><code>import gnu.trove.TObjectIntHashMap;\n...\nTObjectIntHashMap&lt;String&gt; freq = new TObjectIntHashMap&lt;String&gt;();\n...\nfreq.adjustOrPutValue(word, 1, 1);\n</code></pre>\n\n<h3>MutableInt</h3>\n\n<pre><code>import java.util.HashMap;\nimport java.util.Map;\n...\nclass MutableInt {\n int value = 1; // note that we start at 1 since we're counting\n public void increment () { ++value; }\n public int get () { return value; }\n}\n...\nMap&lt;String, MutableInt&gt; freq = new HashMap&lt;String, MutableInt&gt;();\n...\nMutableInt count = freq.get(word);\nif (count == null) {\n freq.put(word, new MutableInt());\n}\nelse {\n count.increment();\n}\n</code></pre>\n" }, { "answer_id": 855154, "author": "Apocalisp", "author_id": 3434, "author_profile": "https://Stackoverflow.com/users/3434", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"http://code.google.com/p/functionaljava\" rel=\"nofollow noreferrer\">Functional Java</a> library's <code>TreeMap</code> datastructure has an <code>update</code> method in the latest trunk head:</p>\n\n<pre><code>public TreeMap&lt;K, V&gt; update(final K k, final F&lt;V, V&gt; f)\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>import static fj.data.TreeMap.empty;\nimport static fj.function.Integers.add;\nimport static fj.pre.Ord.stringOrd;\nimport fj.data.TreeMap;\n\npublic class TreeMap_Update\n {public static void main(String[] a)\n {TreeMap&lt;String, Integer&gt; map = empty(stringOrd);\n map = map.set(\"foo\", 1);\n map = map.update(\"foo\", add.f(1));\n System.out.println(map.get(\"foo\").some());}}\n</code></pre>\n\n<p>This program prints \"2\".</p>\n" }, { "answer_id": 4257986, "author": "the felis leo", "author_id": 517668, "author_profile": "https://Stackoverflow.com/users/517668", "pm_score": 2, "selected": false, "text": "<p>\"put\" need \"get\" (to ensure no duplicate key).<br>\nSo directly do a \"put\",<br>\nand if there was a previous value, then do an addition:</p>\n\n<pre><code>Map map = new HashMap ();\n\nMutableInt newValue = new MutableInt (1); // default = inc\nMutableInt oldValue = map.put (key, newValue);\nif (oldValue != null) {\n newValue.add(oldValue); // old + inc\n}\n</code></pre>\n\n<p>If count starts at 0, then add 1: (or any others values...)</p>\n\n<pre><code>Map map = new HashMap ();\n\nMutableInt newValue = new MutableInt (0); // default\nMutableInt oldValue = map.put (key, newValue);\nif (oldValue != null) {\n newValue.setValue(oldValue + 1); // old + inc\n}\n</code></pre>\n\n<p><em>Notice :</em> This code is not thread safe. Use it to build then use the map, not to concurrently update it. </p>\n\n<p><em>Optimization :</em> In a loop, keep old value to become the new value of next loop.</p>\n\n<pre><code>Map map = new HashMap ();\nfinal int defaut = 0;\nfinal int inc = 1;\n\nMutableInt oldValue = new MutableInt (default);\nwhile(true) {\n MutableInt newValue = oldValue;\n\n oldValue = map.put (key, newValue); // insert or...\n if (oldValue != null) {\n newValue.setValue(oldValue + inc); // ...update\n\n oldValue.setValue(default); // reuse\n } else\n oldValue = new MutableInt (default); // renew\n }\n}\n</code></pre>\n" }, { "answer_id": 4283959, "author": "the felis leo", "author_id": 521173, "author_profile": "https://Stackoverflow.com/users/521173", "pm_score": 2, "selected": false, "text": "<p>Google Collections HashMultiset :<br>\n - quite elegant to use<br>\n - but consume CPU and memory</p>\n\n<p>Best would be to have a method like : <code>Entry&lt;K,V&gt; getOrPut(K);</code> \n(elegant, and low cost)</p>\n\n<p>Such a method will compute hash and index only once,\nand then we could do what we want with the entry\n(either replace or update the value).</p>\n\n<p>More elegant:<br>\n - take a <code>HashSet&lt;Entry&gt;</code><br>\n - extend it so that <code>get(K)</code> put a new Entry if needed<br>\n - Entry could be your own object.<br>\n--> <code>(new MyHashSet()).get(k).increment();</code> </p>\n" }, { "answer_id": 11287489, "author": "Eamonn O'Brien-Strain", "author_id": 978525, "author_profile": "https://Stackoverflow.com/users/978525", "pm_score": 2, "selected": false, "text": "<p>A variation on the MutableInt approach that might be even faster, if a bit of a hack, is to use a single-element int array: </p>\n\n<pre><code>Map&lt;String,int[]&gt; map = new HashMap&lt;String,int[]&gt;();\n...\nint[] value = map.get(key);\nif (value == null) \n map.put(key, new int[]{1} );\nelse\n ++value[0];\n</code></pre>\n\n<p>It would be interesting if you could rerun your performance tests with this variation. It might be the fastest.</p>\n\n<hr>\n\n<p>Edit: The above pattern worked fine for me, but eventually I changed to use Trove's collections to reduce memory size in some very large maps I was creating -- and as a bonus it was also faster.</p>\n\n<p>One really nice feature is that the <code>TObjectIntHashMap</code> class has a single <code>adjustOrPutValue</code> call that, depending on whether there is already a value at that key, will either put an initial value or increment the existing value. This is perfect for incrementing:</p>\n\n<pre><code>TObjectIntHashMap&lt;String&gt; map = new TObjectIntHashMap&lt;String&gt;();\n...\nmap.adjustOrPutValue(key, 1, 1);\n</code></pre>\n" }, { "answer_id": 12266382, "author": "H6.", "author_id": 419863, "author_profile": "https://Stackoverflow.com/users/419863", "pm_score": 5, "selected": false, "text": "<h2>Google <a href=\"https://github.com/google/guava\" rel=\"noreferrer\">Guava</a> is your friend...</h2>\n\n<p>...at least in some cases. They have this nice <a href=\"http://google.github.io/guava/releases/21.0/api/docs/index.html?com/google/common/util/concurrent/AtomicLongMap.html\" rel=\"noreferrer\"><em>AtomicLongMap</em></a>. Especially nice because you are dealing with <em>long</em> as value in your map.</p>\n\n<p>E.g.</p>\n\n\n\n<pre class=\"lang-java prettyprint-override\"><code>AtomicLongMap&lt;String&gt; map = AtomicLongMap.create();\n[...]\nmap.getAndIncrement(word);\n</code></pre>\n\n<p>Also possible to add more then 1 to the value:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>map.getAndAdd(word, 112L); \n</code></pre>\n" }, { "answer_id": 18792535, "author": "Craig P. Motlin", "author_id": 23572, "author_profile": "https://Stackoverflow.com/users/23572", "pm_score": 1, "selected": false, "text": "<p>If you're using <a href=\"http://www.eclipse.org/collections/\" rel=\"nofollow noreferrer\">Eclipse Collections</a>, you can use a <code>HashBag</code>. It will be the most efficient approach in terms of memory usage and it will also perform well in terms of execution speed.</p>\n\n<p><code>HashBag</code> is backed by a <code>MutableObjectIntMap</code> which stores primitive ints instead of <code>Counter</code> objects. This reduces memory overhead and improves execution speed.</p>\n\n<p><code>HashBag</code> provides the API you'd need since it's a <code>Collection</code> that also allows you to query for the number of occurrences of an item.</p>\n\n<p>Here's an example from the <a href=\"https://github.com/eclipse/eclipse-collections-kata\" rel=\"nofollow noreferrer\">Eclipse Collections Kata</a>.</p>\n\n<pre><code>MutableBag&lt;String&gt; bag =\n HashBag.newBagWith(\"one\", \"two\", \"two\", \"three\", \"three\", \"three\");\n\nAssert.assertEquals(3, bag.occurrencesOf(\"three\"));\n\nbag.add(\"one\");\nAssert.assertEquals(2, bag.occurrencesOf(\"one\"));\n\nbag.addOccurrences(\"one\", 4);\nAssert.assertEquals(6, bag.occurrencesOf(\"one\"));\n</code></pre>\n\n<p><strong>Note:</strong> I am a committer for Eclipse Collections.</p>\n" }, { "answer_id": 25354509, "author": "leventov", "author_id": 648955, "author_profile": "https://Stackoverflow.com/users/648955", "pm_score": 6, "selected": false, "text": "<p>A little research in 2016: <a href=\"https://github.com/leventov/java-word-count\" rel=\"noreferrer\">https://github.com/leventov/java-word-count</a>, <a href=\"https://github.com/leventov/java-word-count/blob/8a12a5ea4f53f01b9ee0e57f8aec70d75bc2030d/src/jmh/java/com/koloboke/wordcount/WordCount.java\" rel=\"noreferrer\">benchmark source code</a></p>\n\n<p>Best results per method (smaller is better):</p>\n\n<pre><code> time, ms\nkolobokeCompile 18.8\nkoloboke 19.8\ntrove 20.8\nfastutil 22.7\nmutableInt 24.3\natomicInteger 25.3\neclipse 26.9\nhashMap 28.0\nhppc 33.6\nhppcRt 36.5\n</code></pre>\n\n<p>Time\\space results:\n<img src=\"https://i.stack.imgur.com/nR5yp.png\" width=\"600\"></p>\n" }, { "answer_id": 33711386, "author": "off99555", "author_id": 2593810, "author_profile": "https://Stackoverflow.com/users/2593810", "pm_score": 6, "selected": false, "text": "<pre><code>Map&lt;String, Integer&gt; map = new HashMap&lt;&gt;();\nString key = \"a random key\";\nint count = map.getOrDefault(key, 0); // ensure count will be one of 0,1,2,3,...\nmap.put(key, count + 1);\n</code></pre>\n\n<p>And that's how you increment a value with simple code.</p>\n\n<p>Benefit:</p>\n\n<ul>\n<li>No need to add a new class or use another concept of mutable int</li>\n<li>Not relying on any library</li>\n<li>Easy to understand what's going on exactly (Not too much abstraction)</li>\n</ul>\n\n<p>Downside:</p>\n\n<ul>\n<li>The hash map will be searched twice for get() and put(). So it will not be the most performant code. </li>\n</ul>\n\n<p>Theoretically, once you call get(), you already know where to put(), so you should not have to search again. But searching in hash map usually takes a very minimal time that you can kind of ignore this performance issue.</p>\n\n<p>But if you are very serious about the issue, you are a perfectionist, another way is to use merge method, this is (probably) more efficient than the previous code snippet as you will be (theoretically) searching the map only once: (though this code is not obvious from first sight, it's short and performant)</p>\n\n<pre><code>map.merge(key, 1, (a,b) -&gt; a+b);\n</code></pre>\n\n<p>Suggestion: you should care about code readability more than little performance gain in most of the time. If the first code snippet is easier for you to understand then use it. But if you are able to understand the 2nd one fine then you can also go for it!</p>\n" }, { "answer_id": 37296257, "author": "MGoksu", "author_id": 3721429, "author_profile": "https://Stackoverflow.com/users/3721429", "pm_score": 1, "selected": false, "text": "<p>I don't know how efficient it is but the below code works as well.You need to define a <code>BiFunction</code> at the beginning. Plus, you can make more than just increment with this method.</p>\n\n<pre><code>public static Map&lt;String, Integer&gt; strInt = new HashMap&lt;String, Integer&gt;();\n\npublic static void main(String[] args) {\n BiFunction&lt;Integer, Integer, Integer&gt; bi = (x,y) -&gt; {\n if(x == null)\n return y;\n return x+y;\n };\n strInt.put(\"abc\", 0);\n\n\n strInt.merge(\"abc\", 1, bi);\n strInt.merge(\"abc\", 1, bi);\n strInt.merge(\"abc\", 1, bi);\n strInt.merge(\"abcd\", 1, bi);\n\n System.out.println(strInt.get(\"abc\"));\n System.out.println(strInt.get(\"abcd\"));\n}\n</code></pre>\n\n<p>output is</p>\n\n<pre><code>3\n1\n</code></pre>\n" }, { "answer_id": 37439971, "author": "akhil_mittal", "author_id": 1216775, "author_profile": "https://Stackoverflow.com/users/1216775", "pm_score": 4, "selected": false, "text": "<p>You can make use of <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#computeIfAbsent-K-java.util.function.Function-\" rel=\"noreferrer\">computeIfAbsent</a> method in <code>Map</code> interface provided in <strong>Java 8</strong>. </p>\n\n<pre><code>final Map&lt;String,AtomicLong&gt; map = new ConcurrentHashMap&lt;&gt;();\nmap.computeIfAbsent(\"A\", k-&gt;new AtomicLong(0)).incrementAndGet();\nmap.computeIfAbsent(\"B\", k-&gt;new AtomicLong(0)).incrementAndGet();\nmap.computeIfAbsent(\"A\", k-&gt;new AtomicLong(0)).incrementAndGet(); //[A=2, B=1]\n</code></pre>\n\n<p>The method <code>computeIfAbsent</code> checks if the specified key is already associated with a value or not? If no associated value then it attempts to compute its value using the given mapping function. In any case it returns the current (existing or computed) value associated with the specified key, or null if the computed value is null.</p>\n\n<p>On a side note if you have a situation where multiple threads update a common sum you can have a look at <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/LongAdder.html\" rel=\"noreferrer\">LongAdder</a> class.Under high contention, expected throughput of this class is significantly higher than <code>AtomicLong</code>, at the expense of higher space consumption.</p>\n" }, { "answer_id": 42648785, "author": "LE GALL Benoît", "author_id": 244911, "author_profile": "https://Stackoverflow.com/users/244911", "pm_score": 9, "selected": false, "text": "<p>Now there is a shorter way with Java 8 using <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Map.html#merge(K,V,java.util.function.BiFunction)\" rel=\"noreferrer\"><code>Map::merge</code></a>. </p>\n\n<pre><code>myMap.merge(key, 1, Integer::sum)\n</code></pre>\n\n<p>What it does:</p>\n\n<ul>\n<li>if <em>key</em> do not exists, put <em>1</em> as value</li>\n<li>otherwise <em>sum 1</em> to the value linked to <em>key</em></li>\n</ul>\n\n<p>More information <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#merge-K-V-java.util.function.BiFunction-\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 48715920, "author": "Keith", "author_id": 43370, "author_profile": "https://Stackoverflow.com/users/43370", "pm_score": -1, "selected": false, "text": "<p>Since a lot of people search Java topics for Groovy answers, here's how you can do it in Groovy:</p>\n\n<pre><code>dev map = new HashMap&lt;String, Integer&gt;()\nmap.put(\"key1\", 3)\n\nmap.merge(\"key1\", 1) {a, b -&gt; a + b}\nmap.merge(\"key2\", 1) {a, b -&gt; a + b}\n</code></pre>\n" }, { "answer_id": 54507230, "author": "ggaugler", "author_id": 10429757, "author_profile": "https://Stackoverflow.com/users/10429757", "pm_score": -1, "selected": false, "text": "<p>Hope I'm understanding your question correctly, I'm coming to Java from Python so I can empathize with your struggle. </p>\n\n<p>if you have</p>\n\n<pre><code>map.put(key, 1)\n</code></pre>\n\n<p>you would do</p>\n\n<pre><code>map.put(key, map.get(key) + 1)\n</code></pre>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 55341335, "author": "sudoz", "author_id": 4305743, "author_profile": "https://Stackoverflow.com/users/4305743", "pm_score": 3, "selected": false, "text": "<p>Quite simple, just use the built-in function in <code>Map.java</code> as followed</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>map.put(key, map.getOrDefault(key, 0) + 1);\n</code></pre>\n" }, { "answer_id": 56712619, "author": "Assaduzzaman Assad", "author_id": 9809339, "author_profile": "https://Stackoverflow.com/users/9809339", "pm_score": -1, "selected": false, "text": "<p>The simple and easy way in java 8 is the following:</p>\n\n<pre><code>final ConcurrentMap&lt;String, AtomicLong&gt; map = new ConcurrentHashMap&lt;String, AtomicLong&gt;();\n map.computeIfAbsent(\"foo\", key -&gt; new AtomicLong(0)).incrementAndGet();\n</code></pre>\n" }, { "answer_id": 57838567, "author": "Eugene Chung", "author_id": 968152, "author_profile": "https://Stackoverflow.com/users/968152", "pm_score": 3, "selected": false, "text": "<p>I suggest to use Java 8 Map::compute().\nIt considers the case when a key doesn't exist, too.</p>\n\n<pre><code>Map.compute(num, (k, v) -&gt; (v == null) ? 1 : v + 1);\n</code></pre>\n" }, { "answer_id": 68159505, "author": "Sarvar N", "author_id": 2490074, "author_profile": "https://Stackoverflow.com/users/2490074", "pm_score": 1, "selected": false, "text": "<p>Counting using streams and <code>getOrDefault</code>:</p>\n<pre><code>String s = &quot;abcdeff&quot;;\ns.chars().mapToObj(c -&gt; (char) c)\n .forEach(c -&gt; {\n int count = countMap.getOrDefault(c, 0) + 1;\n countMap.put(c, count);\n });\n</code></pre>\n" } ]
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</a>. Though, I have listed them below for you.</p>\n\n<pre><code> 10.0.0.0 - 10.255.255.255 (10/8 prefix)\n 172.16.0.0 - 172.31.255.255 (172.16/12 prefix)\n 192.168.0.0 - 192.168.255.255 (192.168/16 prefix)\n</code></pre>\n\n<p>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 <a href=\"http://www.faqs.org/rfcs/rfc3300.html\" rel=\"noreferrer\">RFC 3300</a>. </p>\n\n<p>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 <a href=\"http://www.faqs.org/rfcs/rfc4193.html\" rel=\"noreferrer\">RFC 4193</a>.</p>\n" }, { "answer_id": 81375, "author": "Muxa", "author_id": 10793, "author_profile": "https://Stackoverflow.com/users/10793", "pm_score": 2, "selected": false, "text": "<p>also, 169.254.0.0 - 169.254.255.255 are reserved for automatic private IP addressing. Refer to <a href=\"http://en.wikipedia.org/wiki/Link-local_address\" rel=\"nofollow noreferrer\">Link-local address wikipedia article</a></p>\n" } ]
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.com/\" rel=\"nofollow noreferrer\">svn book</a> for help. If you don't want to use Apache, you can also do minimalistic access control using svnserve.</p>\n" }, { "answer_id": 81457, "author": "Stephen Bailey", "author_id": 15385, "author_profile": "https://Stackoverflow.com/users/15385", "pm_score": 6, "selected": false, "text": "<p>In your <strong>svn\\repos\\YourRepo\\conf</strong> folder you will find two files, <strong>authz</strong> and <strong>passwd</strong>. These are the two you need to adjust.</p>\n\n<p>In the <strong>passwd</strong> file you need to add some usernames and passwords. I assume you have already done this since you have people using it:</p>\n\n<pre><code>[users]\nUser1=password1\nUser2=password2\n</code></pre>\n\n<p>Then you want to assign permissions accordingly with the <strong>authz</strong> file:</p>\n\n<p>Create the conceptual groups you want, and add people to it:</p>\n\n<pre><code>[groups]\nallaccess = user1\nsomeaccess = user2\n</code></pre>\n\n<p>Then choose what access they have from both the permissions and project level.</p>\n\n<p>So let's give our \"all access\" guys all access from the root:</p>\n\n<pre><code>[/]\n@allaccess = rw\n</code></pre>\n\n<p>But only give our \"some access\" guys read-only access to some lower level project:</p>\n\n<pre><code>[/someproject]\n@someaccess = r\n</code></pre>\n\n<p>You will also find some simple documentation in the <strong>authz</strong> and <strong>passwd</strong> files.</p>\n" }, { "answer_id": 81468, "author": "RB.", "author_id": 15393, "author_profile": "https://Stackoverflow.com/users/15393", "pm_score": 3, "selected": false, "text": "<p>Although I would suggest the Apache approach is better, SVN Serve works fine and is pretty straightforward.</p>\n\n<p>Assuming your repository is called \"my_repo\", and it is stored in C:\\svn_repos:</p>\n\n<ol>\n<li><p>Create a file called \"passwd\" in \"C:\\svn_repos\\my_repo\\conf\". This file should look like:</p>\n\n<pre><code>[Users]\nusername = password\njohn = johns_password\nsteve = steves_password\n</code></pre></li>\n<li><p>In C:\\svn_repos\\my_repo\\conf\\svnserve.conf set:</p>\n\n<pre><code>[general]\npassword-db = passwd\nauth-access=read\nauth-access=write\n</code></pre></li>\n</ol>\n\n<p>This will force users to log in to read or write to this repository.</p>\n\n<p>Follow these steps for each repository, only including the appropriate users in the <code>passwd</code> file for each repository.</p>\n" }, { "answer_id": 81711, "author": "Matthew Schinckel", "author_id": 188, "author_profile": "https://Stackoverflow.com/users/188", "pm_score": 3, "selected": false, "text": "<p>You can use svn+ssh:, and then it's based on access control to the repository at the given location.</p>\n\n<p>This is how I host a project group repository at my uni, where I can't set up anything else. Just having a directory that the group owns, and running svn-admin (or whatever it was) in there means that I didn't need to do any configuration.</p>\n" }, { "answer_id": 83418, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 5, "selected": false, "text": "<p>@Stephen Bailey </p>\n\n<p>To complete your answer, you can also delegate the user rights to the project manager, through a plain text file in your repository.</p>\n\n<p>To do that, you set up your SVN database with a default <code>authz</code> file containing the following:</p>\n\n<pre><code>###########################################################################\n# The content of this file always precedes the content of the\n# $REPOS/admin/acl_descriptions.txt file.\n# It describes the immutable permissions on main folders.\n###########################################################################\n[groups]\nsvnadmins = xxx,yyy,....\n\n[/]\n@svnadmins = rw\n* = r\n[/admin]\n@svnadmins = rw\n@projadmins = r\n* =\n\n[/admin/acl_descriptions.txt]\n@projadmins = rw\n</code></pre>\n\n<p>This default <code>authz</code> file authorizes the SVN administrators to modify a visible plain text file within your SVN repository, called <strong>'/admin/acl_descriptions.txt'</strong>, in which the SVN administrators or project managers will modify and register the users.</p>\n\n<p>Then you set up a pre-commit hook which will detect if the revision is composed of that file (and only that file). </p>\n\n<p>If it is, this hook's script will validate the content of your plain text file and check if each line is compliant with the SVN syntax.</p>\n\n<p>Then a post-commit hook will update the <code>\\conf\\authz</code> file with the <strong>concatenation</strong> of:</p>\n\n<ul>\n<li>the TEMPLATE <code>authz</code> file presented above</li>\n<li>the plain text file <code>/admin/acl_descriptions.txt</code></li>\n</ul>\n\n<p>The first iteration is done by the SVN administrator, who adds:</p>\n\n<pre><code>[groups]\nprojadmins = zzzz\n</code></pre>\n\n<p>He commits his modification, and that updates the <code>authz</code> file.</p>\n\n<p>Then the project manager 'zzzz' can add, remove or declare any group of users and any users he wants.\nHe commits the file and the <code>authz</code> file is updated.</p>\n\n<p><strong>That way, the SVN administrator does not have to individually manage any and all users for all SVN repositories</strong>.</p>\n" }, { "answer_id": 1793965, "author": "Chris Burgess", "author_id": 43034, "author_profile": "https://Stackoverflow.com/users/43034", "pm_score": 5, "selected": false, "text": "<p>One gotcha which caught me out:</p>\n\n<pre><code>[repos:/path/to/dir/] # this won't work\n</code></pre>\n\n<p>but</p>\n\n<pre><code>[repos:/path/to/dir] # this is right\n</code></pre>\n\n<p>You need to not include a trailing slash on the directory, or you'll see 403 for the OPTIONS request.</p>\n" }, { "answer_id": 61511926, "author": "bahrep", "author_id": 761095, "author_profile": "https://Stackoverflow.com/users/761095", "pm_score": 0, "selected": false, "text": "<p>Apache Subversion supports <a href=\"https://www.visualsvn.com/support/svnbook/serverconfig/pathbasedauthz/\" rel=\"nofollow noreferrer\">path-based authorization</a> that helps you configure granular permissions for user and group accounts on paths in your repositories (files or directories). Path-based authorization supports three access levels - No Access, Read Only and Read / Write.</p>\n\n<p>Path-based authorization permissions are stored in per-repository or per-server authorization files with a special syntax. Here is an example from SVNBook:</p>\n\n<pre><code>[calc:/branches/calc/bug-142]\nharry = rw\nsally = r\n</code></pre>\n\n<p>When you require a complex permission structure with many paths and accounts you can benefit from a GUI-based permission management tools provided by VisualSVN Server:</p>\n\n<ul>\n<li>Server administrators can manage user and group permissions via the VisualSVN Server Manager console or PowerShell,</li>\n<li>Non-admin users can manage permissions via RepoCfg.</li>\n</ul>\n\n<p><em>Repository permissions in VisualSVN Server Manager</em>\n<a href=\"https://i.stack.imgur.com/XjoMn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XjoMn.png\" alt=\"enter image description here\"></a></p>\n\n<p><em>Repository permissions in PowerShell</em>\n<a href=\"https://i.stack.imgur.com/4DeLR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4DeLR.png\" alt=\"enter image description here\"></a></p>\n\n<p><em>Non-admin users can manage permissions via the RepoCfg tool</em>\n<a href=\"https://i.stack.imgur.com/RHPLJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RHPLJ.png\" alt=\"enter image description here\"></a></p>\n" } ]
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 specification (5.6.2 Binary Numeric Promotion), operands of type byte and short are automatically promoted to int before being handed to the operators.</p>\n\n<p>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.</p>\n\n<pre>byte a = 23;\nbyte b = 34;\nbyte c = (byte) (a + b);</pre>\n\n<p>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.)</p>\n\n<p>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.</p>\n" }, { "answer_id": 81446, "author": "David Sykes", "author_id": 3154, "author_profile": "https://Stackoverflow.com/users/3154", "pm_score": 3, "selected": false, "text": "<p>The answer to your follow-up question is here: </p>\n\n<blockquote>\n <p>operands of type byte and short are automatically promoted to int before being handed to the operators</p>\n</blockquote>\n\n<p>So, in your example, <code>a</code> and <code>b</code> are both converted to an <code>int</code> before being handed to the + operator. The result of adding two <code>int</code>s together is also an <code>int</code>. Trying to then assign that <code>int</code> to a <code>byte</code> value causes the error because there is a potential loss of precision. By explicitly casting the result you are telling the compiler \"I know what I am doing\".</p>\n" }, { "answer_id": 81490, "author": "jrudolph", "author_id": 7647, "author_profile": "https://Stackoverflow.com/users/7647", "pm_score": 2, "selected": false, "text": "<p>I think, the matter is, that the JVM supports only two types of stack values: word sized and double word sized. </p>\n\n<p>Then they probably decided that they would need only one operation that works on word sized integers on the stack. So there's only iadd, imul and so on at bytecode level (and no operators for bytes and shorts).</p>\n\n<p>So you get an int value as the result of these operations which Java can't safely convert back to the smaller byte and short data types. So they force you to cast to narrow the value back down to byte/short.</p>\n\n<p>But in the end you are right: This behaviour is not consistent to the behaviour of ints, for example. You can without problem add two ints and get no error if the result overflows.</p>\n" }, { "answer_id": 81728, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 1, "selected": false, "text": "<p>The Java language always promotes arguments of arithmetic operators to int, long, float or double. So take the expression:</p>\n\n<pre><code>a + b\n</code></pre>\n\n<p>where a and b are of type byte. This is shorthand for:</p>\n\n<pre><code>(int)a + (int)b\n</code></pre>\n\n<p>This expression is of type int. It clearly makes sense to give an error when assigning an int value to a byte variable.</p>\n\n<p>Why would the language be defined in this way? Suppose a was 60 and b was 70, then a+b is -126 - integer overflow. As part of a more complicated expression that was expected to result in an int, this may become a difficult bug. Restrict use of byte and short to array storage, constants for file formats/network protocols and puzzlers.</p>\n\n<p>There is an interesting recording from JavaPolis 2007. James Gosling is giving an example about how complicated unsigned arithmetic is (and why it isn't in Java). Josh Bloch points out that his example gives the wrong example under normal signed arithmetic too. For understandable arithmetic, we need arbitrary precision.</p>\n" }, { "answer_id": 73372404, "author": "Dean", "author_id": 8749628, "author_profile": "https://Stackoverflow.com/users/8749628", "pm_score": 0, "selected": false, "text": "<p>In Java Language Specification (5.6.2 Binary Numeric Promotion):</p>\n<blockquote>\n<p>1 If any expression is of type double, then the promoted type is double, and other expressions that are not of type double undergo widening primitive conversion to double.</p>\n<p>2 Otherwise, if any expression is of type float, then the promoted type is float, and other expressions that are not of type float undergo widening primitive conversion to float.</p>\n<p>3 Otherwise, if any expression is of type long, then the promoted type is long, and other expressions that are not of type long undergo widening primitive conversion to long.</p>\n<p>4 Otherwise, none of the expressions are of type double, float, or long. In this case, the promoted type is int, and any expressions that are not of type int undergo widening primitive conversion to int.</p>\n</blockquote>\n<p>Your code belongs to case 4. variables <code>a</code> and <code>b</code> are both converted to an <code>int</code> before being handed to the <code>+</code> operator. The result of <code>+</code> operation is also of type <code>int</code> not <code>byte</code></p>\n" } ]
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. 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:</p>\n\n<p>put the javascript in a weird place, like anywhere that executes a URL. for instance:</p>\n\n<pre><code>&lt;div style=\"background:url('javascript:alert(this);');\" /&gt;\n</code></pre>\n\n<p>sometimes the word 'javascript' gets cut out, but occasionally you can sneak it through as java\\nscript, or something similar.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n" }, { "answer_id": 89760, "author": "Devin Reams", "author_id": 16248, "author_profile": "https://Stackoverflow.com/users/16248", "pm_score": 3, "selected": false, "text": "<p>From the official <a href=\"http://faq.wordpress.com/2006/05/07/javascript-can-i-use-that-on-my-blog/\" rel=\"nofollow noreferrer\">WordPress.com FAQ</a>:</p>\n\n<blockquote>\n <p>Javascript can be used for malicious purposes and while what you want to do is okay it does not mean all javascript will be okay.</p>\n</blockquote>\n\n<p>It goes on to remind the reader that both MySpace and LiveJournal had been affected by malicious Javascript and, therefore, will not be permitted (as it may be exploited by users with poor intentions). They can't risk it with amazingly large sites (think I Can Has Cheezburger, Anderson Cooper 360, Fox, etc.).</p>\n\n<p>If you think you have Javascript that would benefit WordPress.com you can <a href=\"http://wordpress.com/contact-support/\" rel=\"nofollow noreferrer\">contact them directly</a>.</p>\n" }, { "answer_id": 2510303, "author": "MLCWO", "author_id": 301092, "author_profile": "https://Stackoverflow.com/users/301092", "pm_score": 1, "selected": false, "text": "<p>There is not work around for it. Wordpress does not currently support Javascript. Sorry.</p>\n" }, { "answer_id": 3501756, "author": "naugtur", "author_id": 173077, "author_profile": "https://Stackoverflow.com/users/173077", "pm_score": 0, "selected": false, "text": "<p>Just find a good site about XSS if You really need that js to work. But if it works for You it works for anybody, and You post a tutorian on how to do an XSS attack on Your page with posts or comments. </p>\n\n<p>reference:\n<a href=\"http://ha.ckers.org/xss.html\" rel=\"nofollow noreferrer\">http://ha.ckers.org/xss.html</a></p>\n" } ]
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 variants may use more than one byte per char, therefore the 11 byte field might have space for less than 11 chars depending on the encoding.</p>\n\n<p>See also <a href=\"http://www.joelonsoftware.com/articles/Unicode.html\" rel=\"noreferrer\">http://www.joelonsoftware.com/articles/Unicode.html</a></p>\n" }, { "answer_id": 81469, "author": "Seldaek", "author_id": 6512, "author_profile": "https://Stackoverflow.com/users/6512", "pm_score": 2, "selected": false, "text": "<p>I am not sure since I am not an Oracle user, but I assume that the difference lies when you use multi-byte character sets such as Unicode (UTF-16/32). In this case, 11 Bytes could account for less than 11 characters.</p>\n\n<p>Also those field types might be treated differently in regard to accented characters or case, for example 'binaryField(ete) = \"été\"' will not match while 'charField(ete) = \"été\"' might (again not sure about Oracle).</p>\n" }, { "answer_id": 81492, "author": "David Sykes", "author_id": 3154, "author_profile": "https://Stackoverflow.com/users/3154", "pm_score": 9, "selected": true, "text": "<p>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.</p>\n\n<p>If you define the field as <code>VARCHAR2(11 BYTE)</code>, 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.</p>\n\n<p>By defining the field as <code>VARCHAR2(11 CHAR)</code> 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.</p>\n" }, { "answer_id": 81714, "author": "user15453", "author_id": 15453, "author_profile": "https://Stackoverflow.com/users/15453", "pm_score": 4, "selected": false, "text": "<p>Depending on the system configuration, size of CHAR mesured in BYTES can vary. In your examples:</p>\n\n<ol>\n<li>Limits field to 11 <b>BYTE</b></li>\n<li>Limits field to 11 <b>CHAR</b>acters</li>\n</ol>\n\n<p><hr/>\nConclusion: 1 CHAR is not equal to 1 BYTE.<br/><br/></p>\n" }, { "answer_id": 67398489, "author": "Aman Singh Rajpoot", "author_id": 12937828, "author_profile": "https://Stackoverflow.com/users/12937828", "pm_score": 1, "selected": false, "text": "<p>In simple words when you write <code>NAME VARCHAR2(11 BYTE)</code> then only 11 Byte can be accommodated in that variable.</p>\n<p>No matter which characters set you are using, for example, if you are using Unicode (UTF-16) then only half of the size of Name can be accommodated in <code>NAME</code>.</p>\n<p>On the other hand, if you write <code>NAME VARCHAR2(11 CHAR)</code> then <code>NAME</code> can accommodate 11 CHAR regardless of their character encoding.</p>\n<p><code>BYTE</code> is the default if you do not specify <code>BYTE</code> or <code>CHAR</code></p>\n<p>So if you write <code>NAME VARCHAR2(4000 BYTE)</code> and use Unicode(UTF-16) character encoding then only 2000 characters can be accommodated in <code>NAME</code></p>\n<p>That means the size limit on the variable is applied in <code>BYTES</code> and it depends on the character encoding that how many characters can be accommodated in that vraible.</p>\n" } ]
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 field defined as a <a href=\"http://code.google.com/appengine/docs/datastore/typesandpropertyclasses.html\" rel=\"nofollow noreferrer\">BlobProperty</a>)</p>\n\n<p>There is an example in the previous link:</p>\n\n<pre><code>class MyModel(db.Model):\n blob = db.BlobProperty()\n\nobj = MyModel()\nobj.blob = db.Blob( file_contents )\n</code></pre>\n" }, { "answer_id": 81489, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 0, "selected": false, "text": "<p>There's no flat file storing in Google App Engine. Everything has to go in to the <a href=\"http://code.google.com/appengine/docs/datastore/\" rel=\"nofollow noreferrer\">Datastore</a> which is a bit like a relational database but not quite.</p>\n\n<p>You could store the files as <a href=\"http://code.google.com/appengine/docs/datastore/typesandpropertyclasses.html#TextProperty\" rel=\"nofollow noreferrer\">TextProperty</a> or <a href=\"http://code.google.com/appengine/docs/datastore/typesandpropertyclasses.html#BlobProperty\" rel=\"nofollow noreferrer\">BlobProperty</a> attributes.</p>\n\n<p>There is a 1MB limit on DataStore entries which may or may not be a problem.</p>\n" }, { "answer_id": 143798, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>There is a thread in Google Groups about it:</p>\n\n<p><a href=\"http://groups.google.com/group/google-appengine/browse_thread/thread/f9d0f22d8de8c025/bba32165e308dd13?lnk=gst&amp;q=uploading+files#bba32165e308dd13\" rel=\"noreferrer\">Uploading Files</a></p>\n\n<p>With a lot of useful code, that discussion helped me very much in uploading files.</p>\n" }, { "answer_id": 173918, "author": "sastanin", "author_id": 25450, "author_profile": "https://Stackoverflow.com/users/25450", "pm_score": 6, "selected": false, "text": "<p>In fact, this question is answered in the App Egnine documentation. See an example on <a href=\"http://code.google.com/appengine/docs/images/usingimages.html#Uploading\" rel=\"noreferrer\">Uploading User Images</a>.</p>\n\n<p>HTML code, inside &lt;form&gt;&lt;/form&gt;:</p>\n\n<pre>&lt;input type=\"file\" name=\"img\"/&gt;</pre>\n\n<p>Python code:</p>\n\n<pre>class Guestbook(webapp.RequestHandler):\n def post(self):\n greeting = Greeting()\n if users.get_current_user():\n greeting.author = users.get_current_user()\n greeting.content = self.request.get(\"content\")\n avatar = self.request.get(\"img\")\n greeting.avatar = db.Blob(avatar)\n greeting.put()\n self.redirect('/')</pre>\n" }, { "answer_id": 534354, "author": "Joe Petrini", "author_id": 53488, "author_profile": "https://Stackoverflow.com/users/53488", "pm_score": 2, "selected": false, "text": "<p>If your still having a problem, check you are using enctype in the form tag</p>\n\n<p>No:</p>\n\n<pre><code>&lt;form encoding=\"multipart/form-data\" action=\"/upload\"&gt;\n</code></pre>\n\n<p>Yes:</p>\n\n<pre><code>&lt;form enctype=\"multipart/form-data\" action=\"/upload\"&gt;\n</code></pre>\n" }, { "answer_id": 1240820, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Personally I found the tutorial described <a href=\"http://shogi-software.blogspot.com/2009/04/google-app-engine-and-file-upload.html\" rel=\"nofollow noreferrer\">here</a> useful when using the Java run time with GAE. For some reason, when I tried to upload a file using</p>\n\n<pre><code>&lt;form action=\"/testservelet\" method=\"get\" enctype=\"multipart/form-data\"&gt;\n &lt;div&gt;\n Myfile:&lt;input type=\"file\" name=\"file\" size=\"50\"/&gt;\n &lt;/div&gt;\n\n &lt;div&gt;\n &lt;input type=\"submit\" value=\"Upload file\"&gt;\n &lt;/div&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>I found that my HttpServlet class for some reason wouldn't accept the form with the 'enctype' attribute. Removing it works, however, this means I can't upload any files.</p>\n" }, { "answer_id": 1987486, "author": "jbochi", "author_id": 230636, "author_profile": "https://Stackoverflow.com/users/230636", "pm_score": 3, "selected": false, "text": "<p>Google has released a service for storing large files. Have a look at <a href=\"http://code.google.com/appengine/docs/python/blobstore/\" rel=\"nofollow noreferrer\">blobstore API documentation</a>. If your files are > 1MB, you should use it.</p>\n" }, { "answer_id": 3050807, "author": "Bili", "author_id": 331191, "author_profile": "https://Stackoverflow.com/users/331191", "pm_score": 3, "selected": false, "text": "<p>I try it today, It works as following:</p>\n\n<p>my sdk version is 1.3.x</p>\n\n<p>html page:</p>\n\n<pre><code>&lt;form enctype=\"multipart/form-data\" action=\"/upload\" method=\"post\" &gt; \n&lt;input type=\"file\" name=\"myfile\" /&gt; \n&lt;input type=\"submit\" /&gt; \n&lt;/form&gt; \n</code></pre>\n\n<p>Server Code:</p>\n\n<pre><code>file_contents = self.request.POST.get('myfile').file.read() \n</code></pre>\n" }, { "answer_id": 3545032, "author": "Honza Pokorny", "author_id": 244182, "author_profile": "https://Stackoverflow.com/users/244182", "pm_score": 0, "selected": false, "text": "<p>I have observed some strange behavior when uploading files on App Engine. When you submit the following form:</p>\n\n<pre><code>&lt;form method=\"post\" action=\"/upload\" enctype=\"multipart/form-data\"&gt;\n &lt;input type=\"file\" name=\"img\" /&gt;\n ...\n&lt;/form&gt;\n</code></pre>\n\n<p>And then you extract the <code>img</code> from the request like this:</p>\n\n<pre><code>img_contents = self.request.get('img')\n</code></pre>\n\n<p>The <code>img_contents</code> variable is a <code>str()</code> in Google Chrome, but it's unicode in Firefox. And as you now, the <code>db.Blob()</code> constructor takes a string and will throw an error if you pass in a unicode string. </p>\n\n<p>Does anyone know how this can be fixed?</p>\n\n<p>Also, what I find absolutely strange is that when I copy and paste the Guestbook application (with avatars), it works perfectly. I do everything exactly the same way in my code, but it just won't work. I'm very close to pulling my hair out.</p>\n" }, { "answer_id": 4787543, "author": "101010", "author_id": 451007, "author_profile": "https://Stackoverflow.com/users/451007", "pm_score": 7, "selected": true, "text": "<p>Here is a complete, working file. I pulled the original from the Google site and modified it to make it slightly more real world.</p>\n\n<p>A few things to notice:</p>\n\n<ol>\n<li>This code uses the <a href=\"http://code.google.com/appengine/docs/python/blobstore/\" rel=\"noreferrer\">BlobStore API</a></li>\n<li><p>The purpose of this line in the\nServeHandler class is to \"fix\" the\nkey so that it gets rid of any name\nmangling that may have occurred in\nthe browser (I didn't observe any in\nChrome)</p>\n\n<pre><code>blob_key = str(urllib.unquote(blob_key))\n</code></pre></li>\n<li><p>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.</p>\n\n<pre><code>self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True)\n</code></pre></li>\n</ol>\n\n<p>Good Luck!</p>\n\n<pre><code>import os\nimport urllib\n\nfrom google.appengine.ext import blobstore\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp import blobstore_handlers\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.ext.webapp.util import run_wsgi_app\n\nclass MainHandler(webapp.RequestHandler):\n def get(self):\n upload_url = blobstore.create_upload_url('/upload')\n self.response.out.write('&lt;html&gt;&lt;body&gt;')\n self.response.out.write('&lt;form action=\"%s\" method=\"POST\" enctype=\"multipart/form-data\"&gt;' % upload_url)\n self.response.out.write(\"\"\"Upload File: &lt;input type=\"file\" name=\"file\"&gt;&lt;br&gt; &lt;input type=\"submit\" name=\"submit\" value=\"Submit\"&gt; &lt;/form&gt;&lt;/body&gt;&lt;/html&gt;\"\"\")\n\n for b in blobstore.BlobInfo.all():\n self.response.out.write('&lt;li&gt;&lt;a href=\"/serve/%s' % str(b.key()) + '\"&gt;' + str(b.filename) + '&lt;/a&gt;')\n\nclass UploadHandler(blobstore_handlers.BlobstoreUploadHandler):\n def post(self):\n upload_files = self.get_uploads('file')\n blob_info = upload_files[0]\n self.redirect('/')\n\nclass ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):\n def get(self, blob_key):\n blob_key = str(urllib.unquote(blob_key))\n if not blobstore.get(blob_key):\n self.error(404)\n else:\n self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True)\n\ndef main():\n application = webapp.WSGIApplication(\n [('/', MainHandler),\n ('/upload', UploadHandler),\n ('/serve/([^/]+)?', ServeHandler),\n ], debug=True)\n run_wsgi_app(application)\n\nif __name__ == '__main__':\n main()\n</code></pre>\n" }, { "answer_id": 11814685, "author": "vivek_jonam", "author_id": 586836, "author_profile": "https://Stackoverflow.com/users/586836", "pm_score": 0, "selected": false, "text": "<p>There is a way of using <strong>flat file system</strong>( Atleast in usage perspective)</p>\n\n<p>There is this <a href=\"http://code.google.com/p/gaevfs/\" rel=\"nofollow\"><strong>Google App Engine Virtual FileSystem project</strong></a>. that is implemented with the help of datastore and memcache APIs to emulate an ordinary filesystem. Using this library you can use in you project a <strong>similar filesystem access(read and write)</strong>.</p>\n" } ]
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 to set a minimum height, or some padding on the block.</p>\n" }, { "answer_id": 124415, "author": "Ross Morrissey", "author_id": 6997, "author_profile": "https://Stackoverflow.com/users/6997", "pm_score": -1, "selected": false, "text": "<p>Make sure your target list is styled float:left</p>\n\n<p>I had a similar experience today.</p>\n" }, { "answer_id": 2189260, "author": "Colby", "author_id": 264910, "author_profile": "https://Stackoverflow.com/users/264910", "pm_score": 1, "selected": false, "text": "<p>add dropOnEmpty:true to the options parameters.</p>\n" } ]
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" }, { "answer_id": 81672, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 5, "selected": true, "text": "<p>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.</p>\n\n<p>see notify_of_job_status() in jobs.c.</p>\n\n<p>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.</p>\n\n<pre><code>(script 2&gt; /dev/null)\n</code></pre>\n\n<p>which will lose all error messages, but just from that script, not from anything else run in that shell.</p>\n\n<p>You can save and restore standard error, by redirecting a new filedescriptor to point there:</p>\n\n<pre><code>exec 3&gt;&amp;2 # 3 is now a copy of 2\nexec 2&gt; /dev/null # 2 now points to /dev/null\nscript # run script with redirected stderr\nexec 2&gt;&amp;3 # restore stderr to saved\nexec 3&gt;&amp;- # close saved version\n</code></pre>\n\n<p>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.</p>\n\n<hr>\n\n<p><strong>EDIT:</strong></p>\n\n<p><em>For more appropriate answer check answer given by <a href=\"https://stackoverflow.com/users/129332/mark-edgar\">Mark Edgar</a></em></p>\n" }, { "answer_id": 4833055, "author": "clemep", "author_id": 594384, "author_profile": "https://Stackoverflow.com/users/594384", "pm_score": 1, "selected": false, "text": "<p>disown did exactly the right thing for me -- the exec 3>&amp;2 is risky for a lot of reasons -- set +bm didn't seem to work inside a script, only at the command prompt</p>\n" }, { "answer_id": 4849503, "author": "MarcH", "author_id": 317623, "author_profile": "https://Stackoverflow.com/users/317623", "pm_score": 4, "selected": false, "text": "<p>Solution: use SIGINT (works only in non-interactive shells)</p>\n\n<p>Demo:</p>\n\n<pre><code>cat &gt; silent.sh &lt;&lt;\"EOF\"\nsleep 100 &amp;\nkill -INT $!\nsleep 1\nEOF\n\nsh silent.sh\n</code></pre>\n\n<p><a href=\"http://thread.gmane.org/gmane.comp.shells.bash.bugs/15798\" rel=\"noreferrer\">http://thread.gmane.org/gmane.comp.shells.bash.bugs/15798</a></p>\n" }, { "answer_id": 5722874, "author": "Mark Edgar", "author_id": 129332, "author_profile": "https://Stackoverflow.com/users/129332", "pm_score": 7, "selected": false, "text": "<p>In order to silence the message, you must be redirecting <code>stderr</code> <strong>at the time the message is generated</strong>. Because the <a href=\"http://ss64.com/bash/kill.html\" rel=\"noreferrer\"><code>kill</code></a> command sends a signal and doesn't wait for the target process to respond, redirecting <code>stderr</code> of the <code>kill</code> command does you no good. The bash builtin <a href=\"http://ss64.com/bash/wait.html\" rel=\"noreferrer\"><code>wait</code></a> was made specifically for this purpose.</p>\n\n<p>Here is very simple example that kills the most recent background command. (<a href=\"https://stackoverflow.com/a/5163260/117471\">Learn more about $! here.</a>)</p>\n\n<pre><code>kill $!\nwait $! 2&gt;/dev/null\n</code></pre>\n\n<p>Because both <code>kill</code> and <code>wait</code> accept multiple pids, you can also do batch kills. Here is an example that kills all background processes (of the current process/script of course).</p>\n\n<pre><code>kill $(jobs -rp)\nwait $(jobs -rp) 2&gt;/dev/null\n</code></pre>\n\n<p>I was led here from <a href=\"https://stackoverflow.com/questions/5719030/bash-silently-kill-background-function-process/5722850\">bash: silently kill background function process</a>.</p>\n" }, { "answer_id": 12198152, "author": "Ralph", "author_id": 1636189, "author_profile": "https://Stackoverflow.com/users/1636189", "pm_score": 2, "selected": false, "text": "<p>Is this what we are all looking for?</p>\n\n<p>Not wanted: </p>\n\n<pre><code>$ sleep 3 &amp;\n[1] 234\n&lt;pressing enter a few times....&gt;\n$\n$\n[1]+ Done sleep 3\n$\n</code></pre>\n\n<p>Wanted:</p>\n\n<pre><code>$ (set +m; sleep 3 &amp;)\n&lt;again, pressing enter several times....&gt;\n$\n$\n$\n$\n$\n</code></pre>\n\n<p>As you can see, no job end message. Works for me in bash scripts as well, also for killed background processes.</p>\n\n<p>'set +m' disables job control (see 'help set') for the current shell. So if you enter your command in a subshell (as done here in brackets) you will not influence the job control settings of the current shell. Only disadvantage is that you need to get the pid of your background process back to the current shell if you want to check whether it has terminated, or evaluate the return code.</p>\n" }, { "answer_id": 13223242, "author": "Coder of Salvation", "author_id": 1659796, "author_profile": "https://Stackoverflow.com/users/1659796", "pm_score": 2, "selected": false, "text": "<p>This also works for killall (for those who prefer it):</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>killall -s SIGINT (yourprogram) \n</code></pre>\n\n<p>suppresses the message... I was running mpg123 in background mode.\nIt could only silently be killed by sending a ctrl-c (SIGINT) instead of a SIGTERM (default).</p>\n" }, { "answer_id": 15300185, "author": "phily", "author_id": 2149422, "author_profile": "https://Stackoverflow.com/users/2149422", "pm_score": 0, "selected": false, "text": "<p>Another way to disable job notifications is to place your command to be backgrounded in a <code>sh -c 'cmd &amp;'</code> construct.</p>\n\n<pre><code>#!/bin/bash\n# ...\npid=\"`sh -c 'sleep 30 &amp; echo ${!}' | head -1`\"\nkill \"$pid\"\n# ...\n\n# or put several cmds in sh -c '...' construct\nsh -c '\nsleep 30 &amp;\npid=\"${!}\"\nsleep 5 \nkill \"${pid}\"\n'\n</code></pre>\n" }, { "answer_id": 16424178, "author": "J-o-h-n-", "author_id": 2359158, "author_profile": "https://Stackoverflow.com/users/2359158", "pm_score": 0, "selected": false, "text": "<p>Had success with adding '<code>jobs 2&gt;&amp;1 &gt;/dev/null</code>' to the script, not certain if it will help anyone else's script, but here is a sample.</p>\n\n<pre><code> while true; do echo $RANDOM; done | while read line\n do\n echo Random is $line the last jobid is $(jobs -lp)\n jobs 2&gt;&amp;1 &gt;/dev/null\n sleep 3\n done\n</code></pre>\n" }, { "answer_id": 17257986, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Simple:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>{ kill $! } 2&gt;/dev/null\n</code></pre>\n\n<p>Advantage? can use any signal</p>\n\n<p>ex:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>{ kill -9 $PID } 2&gt;/dev/null\n</code></pre>\n" }, { "answer_id": 48726125, "author": "Al Joslin", "author_id": 2912739, "author_profile": "https://Stackoverflow.com/users/2912739", "pm_score": -1, "selected": false, "text": "<p>I found that putting the kill command in a function and then backgrounding the function suppresses the termination output</p>\n\n<pre><code>function killCmd() {\n kill $1\n}\n\nkillCmd $somePID &amp;\n</code></pre>\n" }, { "answer_id": 66355103, "author": "James Z.M. Gao", "author_id": 7704140, "author_profile": "https://Stackoverflow.com/users/7704140", "pm_score": 2, "selected": false, "text": "<p>The <code>Terminated</code> is logged by the default signal handler of bash 3.x and 4.x. Just trap the TERM signal at the very first of child process:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/sh\n\n## assume script name is test.sh\n\nfoo() {\n trap 'exit 0' TERM ## here is the key\n while true; do sleep 1; done\n}\n\necho before child\nps aux | grep 'test\\.s[h]\\|slee[p]'\n\nfoo &amp;\npid=$!\n\nsleep 1 # wait trap is done\n\necho before kill\nps aux | grep 'test\\.s[h]\\|slee[p]'\n\nkill $pid ## no need to redirect stdin/stderr\n\nsleep 1 # wait kill is done\n\necho after kill\nps aux | grep 'test\\.s[h]\\|slee[p]'\n\n</code></pre>\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" }, { "answer_id": 81672, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 5, "selected": true, "text": "<p>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.</p>\n\n<p>see notify_of_job_status() in jobs.c.</p>\n\n<p>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.</p>\n\n<pre><code>(script 2&gt; /dev/null)\n</code></pre>\n\n<p>which will lose all error messages, but just from that script, not from anything else run in that shell.</p>\n\n<p>You can save and restore standard error, by redirecting a new filedescriptor to point there:</p>\n\n<pre><code>exec 3&gt;&amp;2 # 3 is now a copy of 2\nexec 2&gt; /dev/null # 2 now points to /dev/null\nscript # run script with redirected stderr\nexec 2&gt;&amp;3 # restore stderr to saved\nexec 3&gt;&amp;- # close saved version\n</code></pre>\n\n<p>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.</p>\n\n<hr>\n\n<p><strong>EDIT:</strong></p>\n\n<p><em>For more appropriate answer check answer given by <a href=\"https://stackoverflow.com/users/129332/mark-edgar\">Mark Edgar</a></em></p>\n" }, { "answer_id": 4833055, "author": "clemep", "author_id": 594384, "author_profile": "https://Stackoverflow.com/users/594384", "pm_score": 1, "selected": false, "text": "<p>disown did exactly the right thing for me -- the exec 3>&amp;2 is risky for a lot of reasons -- set +bm didn't seem to work inside a script, only at the command prompt</p>\n" }, { "answer_id": 4849503, "author": "MarcH", "author_id": 317623, "author_profile": "https://Stackoverflow.com/users/317623", "pm_score": 4, "selected": false, "text": "<p>Solution: use SIGINT (works only in non-interactive shells)</p>\n\n<p>Demo:</p>\n\n<pre><code>cat &gt; silent.sh &lt;&lt;\"EOF\"\nsleep 100 &amp;\nkill -INT $!\nsleep 1\nEOF\n\nsh silent.sh\n</code></pre>\n\n<p><a href=\"http://thread.gmane.org/gmane.comp.shells.bash.bugs/15798\" rel=\"noreferrer\">http://thread.gmane.org/gmane.comp.shells.bash.bugs/15798</a></p>\n" }, { "answer_id": 5722874, "author": "Mark Edgar", "author_id": 129332, "author_profile": "https://Stackoverflow.com/users/129332", "pm_score": 7, "selected": false, "text": "<p>In order to silence the message, you must be redirecting <code>stderr</code> <strong>at the time the message is generated</strong>. Because the <a href=\"http://ss64.com/bash/kill.html\" rel=\"noreferrer\"><code>kill</code></a> command sends a signal and doesn't wait for the target process to respond, redirecting <code>stderr</code> of the <code>kill</code> command does you no good. The bash builtin <a href=\"http://ss64.com/bash/wait.html\" rel=\"noreferrer\"><code>wait</code></a> was made specifically for this purpose.</p>\n\n<p>Here is very simple example that kills the most recent background command. (<a href=\"https://stackoverflow.com/a/5163260/117471\">Learn more about $! here.</a>)</p>\n\n<pre><code>kill $!\nwait $! 2&gt;/dev/null\n</code></pre>\n\n<p>Because both <code>kill</code> and <code>wait</code> accept multiple pids, you can also do batch kills. Here is an example that kills all background processes (of the current process/script of course).</p>\n\n<pre><code>kill $(jobs -rp)\nwait $(jobs -rp) 2&gt;/dev/null\n</code></pre>\n\n<p>I was led here from <a href=\"https://stackoverflow.com/questions/5719030/bash-silently-kill-background-function-process/5722850\">bash: silently kill background function process</a>.</p>\n" }, { "answer_id": 12198152, "author": "Ralph", "author_id": 1636189, "author_profile": "https://Stackoverflow.com/users/1636189", "pm_score": 2, "selected": false, "text": "<p>Is this what we are all looking for?</p>\n\n<p>Not wanted: </p>\n\n<pre><code>$ sleep 3 &amp;\n[1] 234\n&lt;pressing enter a few times....&gt;\n$\n$\n[1]+ Done sleep 3\n$\n</code></pre>\n\n<p>Wanted:</p>\n\n<pre><code>$ (set +m; sleep 3 &amp;)\n&lt;again, pressing enter several times....&gt;\n$\n$\n$\n$\n$\n</code></pre>\n\n<p>As you can see, no job end message. Works for me in bash scripts as well, also for killed background processes.</p>\n\n<p>'set +m' disables job control (see 'help set') for the current shell. So if you enter your command in a subshell (as done here in brackets) you will not influence the job control settings of the current shell. Only disadvantage is that you need to get the pid of your background process back to the current shell if you want to check whether it has terminated, or evaluate the return code.</p>\n" }, { "answer_id": 13223242, "author": "Coder of Salvation", "author_id": 1659796, "author_profile": "https://Stackoverflow.com/users/1659796", "pm_score": 2, "selected": false, "text": "<p>This also works for killall (for those who prefer it):</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>killall -s SIGINT (yourprogram) \n</code></pre>\n\n<p>suppresses the message... I was running mpg123 in background mode.\nIt could only silently be killed by sending a ctrl-c (SIGINT) instead of a SIGTERM (default).</p>\n" }, { "answer_id": 15300185, "author": "phily", "author_id": 2149422, "author_profile": "https://Stackoverflow.com/users/2149422", "pm_score": 0, "selected": false, "text": "<p>Another way to disable job notifications is to place your command to be backgrounded in a <code>sh -c 'cmd &amp;'</code> construct.</p>\n\n<pre><code>#!/bin/bash\n# ...\npid=\"`sh -c 'sleep 30 &amp; echo ${!}' | head -1`\"\nkill \"$pid\"\n# ...\n\n# or put several cmds in sh -c '...' construct\nsh -c '\nsleep 30 &amp;\npid=\"${!}\"\nsleep 5 \nkill \"${pid}\"\n'\n</code></pre>\n" }, { "answer_id": 16424178, "author": "J-o-h-n-", "author_id": 2359158, "author_profile": "https://Stackoverflow.com/users/2359158", "pm_score": 0, "selected": false, "text": "<p>Had success with adding '<code>jobs 2&gt;&amp;1 &gt;/dev/null</code>' to the script, not certain if it will help anyone else's script, but here is a sample.</p>\n\n<pre><code> while true; do echo $RANDOM; done | while read line\n do\n echo Random is $line the last jobid is $(jobs -lp)\n jobs 2&gt;&amp;1 &gt;/dev/null\n sleep 3\n done\n</code></pre>\n" }, { "answer_id": 17257986, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Simple:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>{ kill $! } 2&gt;/dev/null\n</code></pre>\n\n<p>Advantage? can use any signal</p>\n\n<p>ex:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>{ kill -9 $PID } 2&gt;/dev/null\n</code></pre>\n" }, { "answer_id": 48726125, "author": "Al Joslin", "author_id": 2912739, "author_profile": "https://Stackoverflow.com/users/2912739", "pm_score": -1, "selected": false, "text": "<p>I found that putting the kill command in a function and then backgrounding the function suppresses the termination output</p>\n\n<pre><code>function killCmd() {\n kill $1\n}\n\nkillCmd $somePID &amp;\n</code></pre>\n" }, { "answer_id": 66355103, "author": "James Z.M. Gao", "author_id": 7704140, "author_profile": "https://Stackoverflow.com/users/7704140", "pm_score": 2, "selected": false, "text": "<p>The <code>Terminated</code> is logged by the default signal handler of bash 3.x and 4.x. Just trap the TERM signal at the very first of child process:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/sh\n\n## assume script name is test.sh\n\nfoo() {\n trap 'exit 0' TERM ## here is the key\n while true; do sleep 1; done\n}\n\necho before child\nps aux | grep 'test\\.s[h]\\|slee[p]'\n\nfoo &amp;\npid=$!\n\nsleep 1 # wait trap is done\n\necho before kill\nps aux | grep 'test\\.s[h]\\|slee[p]'\n\nkill $pid ## no need to redirect stdin/stderr\n\nsleep 1 # wait kill is done\n\necho after kill\nps aux | grep 'test\\.s[h]\\|slee[p]'\n\n</code></pre>\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 be able to create a view that, when its values change, in turn it will update the constituent tables.</p>\n" }, { "answer_id": 81565, "author": "Martin Marconcini", "author_id": 2684, "author_profile": "https://Stackoverflow.com/users/2684", "pm_score": 2, "selected": false, "text": "<p>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.</p>\n\n<p>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: </p>\n\n<pre><code>SELECT * FROM SALESLEAD WHERE LeadSouce = (int) EnmLeadSource.Foo; //pseudocode\n</code></pre>\n\n<p>And your code will have a</p>\n\n<pre><code>public enum EnmLeadSource \n{\n Foo = 1,\n Bar = 2\n}\n</code></pre>\n\n<p>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.</p>\n\n<p>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)</p>\n\n<p><strong>Update</strong>: Since you're using .NET, the DB Backend is \"irrelevant\" if you're constructing a query through code. Imagine this function:</p>\n\n<pre><code>public void GiveMeSalesLeadGiven( EnmLeadSource thisLeadSource )\n{\n // Construct your string using the value of thisLeadSource \n}\n</code></pre>\n\n<p>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:</p>\n\n<p>1) All the \"number 1\" have to be number \"2\". You'll have to update the table.\n2) 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).</p>\n\n<p>The Enum is a very useful structure if properly used. </p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 81570, "author": "pilif", "author_id": 5083, "author_profile": "https://Stackoverflow.com/users/5083", "pm_score": 0, "selected": false, "text": "<p>I really don't see your problem behind the join. </p>\n\n<p>Naturally, asking directly by the FK_LeadSourceID is wrong, but using the JOIN seems to be the right way to go as I masks changing IDs perfectly fine. If, for example, \"foo\" becomes 3 at one day (and you update the foreign key field), the last query you've displayed will still work exactly the same.</p>\n\n<p>If you want to make the change to the schema without altering the current queries in the application, then a view encompassing this join is the way to go.</p>\n\n<p>Or if you fear that the join Syntax is non-intuitive, there's always the subselect...</p>\n\n<pre><code>SELECT * FROM SalesLead where FK_LeadSourceID = \n (SELECT LeadSourceID from LeadSource WHERE LeadSource = 'foo')\n</code></pre>\n\n<p>but remember to keep an index on LeadSource.LeadSource - at least if you have a lot of them stored in the table.</p>\n" }, { "answer_id": 81623, "author": "Olaf Kock", "author_id": 13447, "author_profile": "https://Stackoverflow.com/users/13447", "pm_score": 0, "selected": false, "text": "<p>If you \"improve design\" by introducing new relations/tables, you'll certainly have the need for different entities. If so, you'll need to deal with their semantics. </p>\n\n<p>In the previous solution you were able to just update the LeadSource name to whatever you wanted in the appropriate SalesLead row. If you update the name in your new structure, you do so for all SalesLead rows.</p>\n\n<p>There is no way around dealing with these different semantics. You just have to do so. In order to make the tables easier to query, you might use views as already suggested, but I'd expect them mostly for reporting purposes or backward compatibility, provided they are not updatable, because everybody updating this view would not be aware of changed semantics.</p>\n\n<p>If you dislike the join try\nSELECT * FROM SalesLead where LeadSourceId IN (SELECT Id FROM LeadSource WHERE LeadSource = 'foo')</p>\n" }, { "answer_id": 81642, "author": "Seb Rose", "author_id": 12405, "author_profile": "https://Stackoverflow.com/users/12405", "pm_score": 0, "selected": false, "text": "<p>In a typical application the user would be presented with a list of Lead Sources (returned by querying the LeadSource table) and the subsequent SalesLead query would be dynamically created by the application based upon the user's selection.</p>\n\n<p>Your application appears to have some 'well known' lead sources that you need to write specific queries for. If this is the case, then add a third (unique) field to the LeadSource table that includes an invariant 'name' that you can use as the basis of your application's queries. </p>\n\n<p>This shifts the burden of magic-ness from a DB generated magic number (that may vary from installation to installation) to a system defined magic name (that is fixed by design).</p>\n" }, { "answer_id": 82185, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 0, "selected": false, "text": "<p>There's a false dichotomy here.</p>\n\n<pre><code>SELECT * FROM SalesLead \nINNER JOIN LeadSource ON SalesLead.FK_LeadSourceID = LeadSource.LeadSourceId \nwhere LeadSource.LeadSource = \"foo\"\n</code></pre>\n\n<p>doesn't break any more than the original</p>\n\n<pre><code>SELECT * FROM SalesLead Where LeadSource = 'foo'\n</code></pre>\n\n<p>when <code>foo</code> changes to <code>foobar</code>. Also, if you're using parameterized queries (and you really should be), you don't have to change anything when <code>foo</code> changes to <code>foobar</code>.</p>\n" }, { "answer_id": 82628, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 2, "selected": false, "text": "<p>Have you considered just not using an artificial key for the <code>LeadSource</code> table? Then you get to use <code>LeadSource</code> as the FK in <code>SalesLead</code>, which simplifies your queries while retaining the benefits of using a canonical set of values (the rows in <code>LeadSource</code>).</p>\n" } ]
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 you to specify arguments.</p>\n\n<p>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.</p>\n\n<p>I don't have Infopath installed so I unfortunately can't try it out. But hopefully it helps you out a little.</p>\n" }, { "answer_id": 90804, "author": "bryansh", "author_id": 211367, "author_profile": "https://Stackoverflow.com/users/211367", "pm_score": 1, "selected": false, "text": "<p>Here's an article about finding the install path for Office Apps:</p>\n\n<p><a href=\"http://support.microsoft.com/kb/234788\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/234788</a></p>\n" }, { "answer_id": 984209, "author": "Jason Watts", "author_id": 117526, "author_profile": "https://Stackoverflow.com/users/117526", "pm_score": 0, "selected": false, "text": "<p>Try using browser based form and querystring instead</p>\n" } ]
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 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.</p>\n\n<p>You could do this in SQL 2005 like this:</p>\n\n<pre><code>declare @spid int\n , @cmd varchar(200)\ndeclare Mycurs cursor for\nselect spid\n from master..sysprocesses\n where status = 'sleeping'\n and last_batch &gt; dateadd( s, -1, getdate())\nopen mycurs\nfetch next from mycurs into @spid\nwhile @@fetch_status = 0\n begin\n select @cmd = 'kill ' + cast(@spid as varchar)\n exec(@cmd )\n fetch next from mycurs into @spid\n end\ndeallocate MyCurs\n</code></pre>\n" }, { "answer_id": 811204, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>But, instead of killing these processes manually, shouldn't there be a way to avoid these? I have the same problem in a project</p>\n\n<p>In our Web application, we are performing some updates using a Web service (i.e. a program calls a webservice method. The method opens a connection, does an update, commits and closes the connection using connection.close()) </p>\n\n<p>In the sqlserver mgmt studio if I do a sp_who2, I see that the connections increase as teh app is running - in fact at the rate of 1 connection per update execution. AND the concerning part is that it crosses the 100 and then does not allow more connections into the db. Users are not able to login as well the programs fail as they cannot get any more new connections.</p>\n\n<p>How to ensure that the connections are reused - We have not written any connection pooling code, using the default asp.net and Sqlserver connection pooling. Why are the connections not be reused and why are they not vanishing after being \"Closed\" ?\nDoes this depend on the fact that a webservice is handling the transaction ?</p>\n\n<p>Thanks a lot</p>\n" } ]
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>WindowFlags</em> parameter to the dialog constructor. </p>\n\n<p>For instance you can specify only the <em>TitleHint</em> and <em>SystemMenu</em> flags by doing:</p>\n\n<pre><code>QDialog *d = new QDialog(0, Qt::WindowSystemMenuHint | Qt::WindowTitleHint);\nd-&gt;exec();\n</code></pre>\n\n<p>If you add the <em>Qt::WindowContextHelpButtonHint</em> flag you will get the help button back.</p>\n\n<p>In PyQt you can do:</p>\n\n<pre><code>from PyQt4 import QtGui, QtCore\napp = QtGui.QApplication([])\nd = QtGui.QDialog(None, QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint)\nd.exec_()\n</code></pre>\n\n<p>More details on window flags can be found on the <a href=\"https://doc.qt.io/qt-5.7/qt.html#WindowType-enum\" rel=\"noreferrer\">WindowType enum</a> in the Qt documentation.</p>\n" }, { "answer_id": 82303, "author": "AMM", "author_id": 11212, "author_profile": "https://Stackoverflow.com/users/11212", "pm_score": 5, "selected": false, "text": "<p>Ok , I found a way to do this.</p>\n\n<p>It does deal with the Window flags. So here is the code i used:</p>\n\n<pre><code>Qt::WindowFlags flags = windowFlags()\n\nQt::WindowFlags helpFlag =\nQt::WindowContextHelpButtonHint;\n\nflags = flags &amp; (~helpFlag); \nsetWindowFlags(flags);\n</code></pre>\n\n<p>But by doing this sometimes the icon of the dialog gets reset. So to make sure the icon of the dialog does not change you can add two lines.</p>\n\n<pre><code>QIcon icon = windowIcon();\n\nQt::WindowFlags flags = windowFlags();\n\nQt::WindowFlags helpFlag =\nQt::WindowContextHelpButtonHint;\n\nflags = flags &amp; (~helpFlag); \n\nsetWindowFlags(flags);\n\nsetWindowIcon(icon);\n</code></pre>\n" }, { "answer_id": 358270, "author": "Michael Bishop", "author_id": 45114, "author_profile": "https://Stackoverflow.com/users/45114", "pm_score": 2, "selected": false, "text": "<p>The answers listed here will work, but to answer it yourself, I'd recommend you run the example program <code>$QTDIR/examples/widgets/windowflags</code>. That will allow you to test all the configurations of window flags and their effects. Very useful for figuring out squirrelly windowflags problems.</p>\n" }, { "answer_id": 3817398, "author": "brandoneggar", "author_id": 461134, "author_profile": "https://Stackoverflow.com/users/461134", "pm_score": 0, "selected": false, "text": "<p>I couldn't find a slot but you can override the virtual <code>winEvent</code> function.</p>\n\n<pre><code>#if defined(Q_WS_WIN)\nbool MyWizard::winEvent(MSG * msg, long * result)\n{\n switch (msg-&gt;message)\n {\n case WM_NCLBUTTONDOWN:\n if (msg-&gt;wParam == HTHELP)\n {\n\n }\n break;\n default:\n break;\n }\n return QWizard::winEvent(msg, result);\n}\n#endif\n</code></pre>\n" }, { "answer_id": 22039439, "author": "rrwick", "author_id": 2438989, "author_profile": "https://Stackoverflow.com/users/2438989", "pm_score": 4, "selected": false, "text": "<p>I ran into this issue in Windows 7, Qt 5.2, and the flags combination that worked best for me was this:</p>\n\n<p><strong>Qt::WindowTitleHint | Qt::WindowCloseButtonHint</strong></p>\n\n<p>This gives me a working close button but no question mark help button. Using just Qt::WindowTitleHint or Qt::WindowSystemMenuHint got rid of the help button, but it also disabled the close button.</p>\n\n<p>As Michael Bishop suggested, it was playing with the windowflags example that led me to this combination. Thanks!</p>\n" }, { "answer_id": 30934930, "author": "Jens A. Koch", "author_id": 1163786, "author_profile": "https://Stackoverflow.com/users/1163786", "pm_score": 6, "selected": false, "text": "<pre><code>// remove question mark from the title bar\nsetWindowFlags(windowFlags() &amp; ~Qt::WindowContextHelpButtonHint);\n</code></pre>\n" }, { "answer_id": 45939311, "author": "Predelnik", "author_id": 1269661, "author_profile": "https://Stackoverflow.com/users/1269661", "pm_score": 2, "selected": false, "text": "<p>The following way to remove question marks by default for all the dialogs in application could be used:</p>\n\n<p>Attach the following event filter to <code>QApplication</code> somewhere at the start of your program:</p>\n\n<pre><code> bool eventFilter (QObject *watched, QEvent *event) override\n {\n if (event-&gt;type () == QEvent::Create)\n {\n if (watched-&gt;isWidgetType ())\n {\n auto w = static_cast&lt;QWidget *&gt; (watched);\n w-&gt;setWindowFlags (w-&gt;windowFlags () &amp; (~Qt::WindowContextHelpButtonHint));\n }\n }\n return QObject::eventFilter (watched, event);\n }\n</code></pre>\n" }, { "answer_id": 49905954, "author": "Parker Coates", "author_id": 4757, "author_profile": "https://Stackoverflow.com/users/4757", "pm_score": 5, "selected": false, "text": "<p>As of Qt 5.10, you can disable these buttons globally with a single <code>QApplication</code> attribute!</p>\n\n<pre><code>QApplication::setAttribute(Qt::AA_DisableWindowContextHelpButton);\n</code></pre>\n" }, { "answer_id": 70467468, "author": "Pascal Vallaster", "author_id": 15889585, "author_profile": "https://Stackoverflow.com/users/15889585", "pm_score": 2, "selected": false, "text": "<p>As the solution for PyQt4 from @amos didn't work for me and the version of PyQt4 is deprecated, here is my solution on how to remove the &quot;?&quot; in the dialog-box in PyQt5:</p>\n<pre><code>class window(QDialog):\n def __init__(self):\n super(window, self).__init__()\n loadUi(&quot;window.ui&quot;, self)\n self.setWindowFlag(QtCore.Qt.WindowContextHelpButtonHint,False) # This removes it\n</code></pre>\n" } ]
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 how much memory you need to store your string. You could also use String.Format instead.</p>\n\n<p>If this is all your submit button is doing why make it a .Net page at all and instead just have a GET form go to nextpage.aspx for processing?</p>\n" }, { "answer_id": 81704, "author": "Ian Oxley", "author_id": 1904, "author_profile": "https://Stackoverflow.com/users/1904", "pm_score": 2, "selected": true, "text": "<p>The easiest way would be to use a non-server-side &lt;form&gt; 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 &lt;label&gt; tags and associate them with your radio buttons):</p>\n\n<pre><code>&lt;form action=\"...\" method=\"get\"&gt;\n &lt;input type=\"radio\" name=\"apBoat\" id=\"Apb1\" value=\"1\" /&gt; &lt;label for=\"Apb1\"&gt;detail1&lt;/label&gt;\n &lt;input type=\"radio\" name=\"apBoat\" id=\"Apb2\" value=\"2\" /&gt; &lt;label for=\"Apb2\"&gt;detail2&lt;/label&gt;\n\n &lt;input type=\"radio\" name=\"cBoat\" id=\"Cb1\" value=\"1\" /&gt; &lt;label for=\"Cb1\"&gt;detail1&lt;/label&gt;\n &lt;input type=\"radio\" name=\"cBoat\" id=\"Cb2\" value=\"2\" /&gt; &lt;label for=\"Cb2\"&gt;detail2&lt;/label&gt;\n&lt;/form&gt;\n</code></pre>\n" } ]
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://server/path/file</a></p>\n\n<p>Does that get redirected to:\n<a href=\"http://server/path/\" rel=\"nofollow noreferrer\">http://server/path/</a></p>\n\n<p>Or does it get redirected to:\n<a href=\"http://server/path/file/\" rel=\"nofollow noreferrer\">http://server/path/file/</a></p>\n\n<p>As in: Do you want the redirects to go to the parent path, or do you just want to add a slash and assume directory out of the current path?</p>\n" }, { "answer_id": 81760, "author": "MB.", "author_id": 11961, "author_profile": "https://Stackoverflow.com/users/11961", "pm_score": 3, "selected": true, "text": "<p>I think the following might work:</p>\n\n<pre><code>RewriteEngine on \nRewriteCond %{REQUEST_URI} ^/[^\\.]+[^/]$\nRewriteRule ^(.*)$ http://%{HTTP_HOST}/$1/ [R=301,L]\n</code></pre>\n\n<p>When it comes to mod_rewrite I can never be sure without testing though...</p>\n" }, { "answer_id": 193294, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 0, "selected": false, "text": "<p>MB's RewriteRule above will fail on paths like <code>/a</code> because it needs to match at least two characters after the slash. Moreover it only matches on top directory URLs.</p>\n\n<pre><code>RewriteRule ^(([^\\/]+\\/)*[^\\/\\.]+)$ http://%{HTTP_HOST}/$1/ [R=301,L]\n</code></pre>\n\n<p>Is the purpose of this to reduce history pollution/false negatives?</p>\n" } ]
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 you notify the thread that needs to know about the status of the transaction.</p>\n" }, { "answer_id": 81967, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If I was writing from scratch I would do that, but this is a server application that we are just doing an upgrade to rather than a large rework.</p>\n" }, { "answer_id": 83695, "author": "longneck", "author_id": 8250, "author_profile": "https://Stackoverflow.com/users/8250", "pm_score": 0, "selected": false, "text": "<p>instead of trying to fake transactions with table locks, why not switch to innodb tables where you get actual transactions? just make sure to set the default transaction isolation level to REPEATABLE READ.</p>\n" }, { "answer_id": 94062, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>As I said, it is not so easy to 'switch' or re-architect when this is a live, in production system. I'm slightly frustrated that MySQL provides no methods to check for locks or choose not to hang waiting on a lock.</p>\n" }, { "answer_id": 94540, "author": "pestophagous", "author_id": 10278, "author_profile": "https://Stackoverflow.com/users/10278", "pm_score": 0, "selected": false, "text": "<p>I don't know if this is a good idea in terms of resource usage and \"best practices\" and \"cleanliness\" and all the rest... but you have now repeatedly described the handcuffs that bind you in terms of re-architecting a \"clean\" system... so here goes.....</p>\n\n<p>Could you open a new, separate connection just for sending the LOCK statement? Then close that connection when you catch the timeout alarm? By closing/destroying the connection that was dedicated to the LOCK statement, would not that essentially \"cancel\" the LOCK statment? I am not certain if such events would occur as I have described/guessed, but maybe it is something to test out.</p>\n" }, { "answer_id": 102263, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>My experience described so far indicates to me that closing a connection in which a query is running causes a seg fault. Therefore dispatching that query into a different connection wouldn't really help, as that would also seg fault.</p>\n" }, { "answer_id": 158725, "author": "Danut Enachioiu", "author_id": 24226, "author_profile": "https://Stackoverflow.com/users/24226", "pm_score": 2, "selected": false, "text": "<p>You can implement a \"cancel-like\" behavior this way:</p>\n\n<p>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. </p>\n\n<p>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. </p>\n\n<p>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.</p>\n" } ]
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 involves reflection underwater, but the most simple way?</p>\n" }, { "answer_id": 81718, "author": "Paul van Brenk", "author_id": 1837197, "author_profile": "https://Stackoverflow.com/users/1837197", "pm_score": 5, "selected": false, "text": "<p>You're going to have to check all types in the graph of objects being serialized for the serializable attribute. The easiest way is to try to serialize the object and catch the exception. (But that's not the cleanest solution). Type.IsSerializable and checking for the serializalbe attribute don't take the graph into account.</p>\n\n<p><em>Sample</em></p>\n\n<pre><code>[Serializable]\npublic class A\n{\n public B B = new B();\n}\n\npublic class B\n{\n public string a = \"b\";\n}\n\n[Serializable]\npublic class C\n{\n public D D = new D();\n}\n\n[Serializable]\npublic class D\n{\n public string d = \"D\";\n}\n\n\nclass Program\n{\n static void Main(string[] args)\n {\n\n var a = typeof(A);\n\n var aa = new A();\n\n Console.WriteLine(\"A: {0}\", a.IsSerializable); // true (WRONG!)\n\n var c = typeof(C);\n\n Console.WriteLine(\"C: {0}\", c.IsSerializable); //true\n\n var form = new BinaryFormatter();\n // throws\n form.Serialize(new MemoryStream(), aa);\n }\n}\n</code></pre>\n" }, { "answer_id": 81762, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 8, "selected": true, "text": "<p>You have a lovely property on the <code>Type</code> class called <code>IsSerializable</code>.</p>\n" }, { "answer_id": 81833, "author": "Michael Meadows", "author_id": 7643, "author_profile": "https://Stackoverflow.com/users/7643", "pm_score": 3, "selected": false, "text": "<p>Here's a 3.5 variation that makes it available to all classes using an extension method.</p>\n\n<pre><code>public static bool IsSerializable(this object obj)\n{\n if (obj is ISerializable)\n return true;\n return Attribute.IsDefined(obj.GetType(), typeof(SerializableAttribute));\n}\n</code></pre>\n" }, { "answer_id": 82260, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": false, "text": "<p>Use Type.IsSerializable as others have pointed out.</p>\n\n<p>It's probably not worth attempting to reflect and check if all members in the object graph are serializable. </p>\n\n<p>A member could be declared as a serializable type, but in fact be instantiated as a derived type that is not serializable, as in the following contrived example:</p>\n\n<pre><code>[Serializable]\npublic class MyClass\n{\n public Exception TheException; // serializable\n}\n\npublic class MyNonSerializableException : Exception\n{\n...\n}\n\n...\nMyClass myClass = new MyClass();\nmyClass.TheException = new MyNonSerializableException();\n// myClass now has a non-serializable member\n</code></pre>\n\n<p>Therefore, even if you determine that a specific instance of your type is serializable, you can't in general be sure this will be true of all instances.</p>\n" }, { "answer_id": 4037838, "author": "Mike_G", "author_id": 52051, "author_profile": "https://Stackoverflow.com/users/52051", "pm_score": 4, "selected": false, "text": "<p>This is an old question, that may need to be updated for .NET 3.5+. Type.IsSerializable can actually return false if the class uses the DataContract attribute. Here is a snippet i use, if it stinks, let me know :)</p>\n\n<pre><code>public static bool IsSerializable(this object obj)\n{\n Type t = obj.GetType();\n\n return Attribute.IsDefined(t, typeof(DataContractAttribute)) || t.IsSerializable || (obj is IXmlSerializable)\n\n}\n</code></pre>\n" }, { "answer_id": 5913032, "author": "Eric", "author_id": 741895, "author_profile": "https://Stackoverflow.com/users/741895", "pm_score": 0, "selected": false, "text": "<p>The exception object might be serializable , but using an other exception which is not.\nThis is what I just had with WCF System.ServiceModel.FaultException: FaultException is serializable but ExceptionDetail is not!</p>\n\n<p>So I am using the following:</p>\n\n<pre><code>// Check if the exception is serializable and also the specific ones if generic\nvar exceptionType = ex.GetType();\nvar allSerializable = exceptionType.IsSerializable;\nif (exceptionType.IsGenericType)\n {\n Type[] typeArguments = exceptionType.GetGenericArguments();\n allSerializable = typeArguments.Aggregate(allSerializable, (current, tParam) =&gt; current &amp; tParam.IsSerializable);\n }\n if (!allSerializable)\n {\n // Create a new Exception for not serializable exceptions!\n ex = new Exception(ex.Message);\n }\n</code></pre>\n" }, { "answer_id": 13054478, "author": "sewershingle", "author_id": 496047, "author_profile": "https://Stackoverflow.com/users/496047", "pm_score": 2, "selected": false, "text": "<p>I took the answer on this question and the answer <a href=\"https://stackoverflow.com/questions/236599/how-to-unit-test-if-my-object-is-really-serializable/236698#236698\">here</a> and modified it so you get a List of types that aren't serializable. That way you can easily know which ones to mark.</p>\n\n<pre><code> private static void NonSerializableTypesOfParentType(Type type, List&lt;string&gt; nonSerializableTypes)\n {\n // base case\n if (type.IsValueType || type == typeof(string)) return;\n\n if (!IsSerializable(type))\n nonSerializableTypes.Add(type.Name);\n\n foreach (var propertyInfo in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))\n {\n if (propertyInfo.PropertyType.IsGenericType)\n {\n foreach (var genericArgument in propertyInfo.PropertyType.GetGenericArguments())\n {\n if (genericArgument == type) continue; // base case for circularly referenced properties\n NonSerializableTypesOfParentType(genericArgument, nonSerializableTypes);\n }\n }\n else if (propertyInfo.GetType() != type) // base case for circularly referenced properties\n NonSerializableTypesOfParentType(propertyInfo.PropertyType, nonSerializableTypes);\n }\n }\n\n private static bool IsSerializable(Type type)\n {\n return (Attribute.IsDefined(type, typeof(SerializableAttribute)));\n //return ((type is ISerializable) || (Attribute.IsDefined(type, typeof(SerializableAttribute))));\n }\n</code></pre>\n\n<p>And then you call it...</p>\n\n<pre><code> List&lt;string&gt; nonSerializableTypes = new List&lt;string&gt;();\n NonSerializableTypesOfParentType(aType, nonSerializableTypes);\n</code></pre>\n\n<p>When it runs, nonSerializableTypes will have the list. There may be a better way of doing this than passing in an empty List to the recursive method. Someone correct me if so.</p>\n" }, { "answer_id": 25096555, "author": "ElektroStudios", "author_id": 1248295, "author_profile": "https://Stackoverflow.com/users/1248295", "pm_score": 1, "selected": false, "text": "<p>My solution, in VB.NET:</p>\n\n<p>For Objects:</p>\n\n<pre><code>''' &lt;summary&gt;\n''' Determines whether an object can be serialized.\n''' &lt;/summary&gt;\n''' &lt;param name=\"Object\"&gt;The object.&lt;/param&gt;\n''' &lt;returns&gt;&lt;c&gt;true&lt;/c&gt; if object can be serialized; otherwise, &lt;c&gt;false&lt;/c&gt;.&lt;/returns&gt;\nPrivate Function IsObjectSerializable(ByVal [Object] As Object,\n Optional ByVal SerializationFormat As SerializationFormat =\n SerializationFormat.Xml) As Boolean\n\n Dim Serializer As Object\n\n Using fs As New IO.MemoryStream\n\n Select Case SerializationFormat\n\n Case Data.SerializationFormat.Binary\n Serializer = New Runtime.Serialization.Formatters.Binary.BinaryFormatter()\n\n Case Data.SerializationFormat.Xml\n Serializer = New Xml.Serialization.XmlSerializer([Object].GetType)\n\n Case Else\n Throw New ArgumentException(\"Invalid SerializationFormat\", SerializationFormat)\n\n End Select\n\n Try\n Serializer.Serialize(fs, [Object])\n Return True\n\n Catch ex As InvalidOperationException\n Return False\n\n End Try\n\n End Using ' fs As New MemoryStream\n\nEnd Function\n</code></pre>\n\n<p>For Types:</p>\n\n<pre><code>''' &lt;summary&gt;\n''' Determines whether a Type can be serialized.\n''' &lt;/summary&gt;\n''' &lt;typeparam name=\"T\"&gt;&lt;/typeparam&gt;\n''' &lt;returns&gt;&lt;c&gt;true&lt;/c&gt; if Type can be serialized; otherwise, &lt;c&gt;false&lt;/c&gt;.&lt;/returns&gt;\nPrivate Function IsTypeSerializable(Of T)() As Boolean\n\n Return Attribute.IsDefined(GetType(T), GetType(SerializableAttribute))\n\nEnd Function\n\n''' &lt;summary&gt;\n''' Determines whether a Type can be serialized.\n''' &lt;/summary&gt;\n''' &lt;typeparam name=\"T\"&gt;&lt;/typeparam&gt;\n''' &lt;param name=\"Type\"&gt;The Type.&lt;/param&gt;\n''' &lt;returns&gt;&lt;c&gt;true&lt;/c&gt; if Type can be serialized; otherwise, &lt;c&gt;false&lt;/c&gt;.&lt;/returns&gt;\nPrivate Function IsTypeSerializable(Of T)(ByVal Type As T) As Boolean\n\n Return Attribute.IsDefined(GetType(T), GetType(SerializableAttribute))\n\nEnd Function\n</code></pre>\n" } ]
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 the correct one would be <code>&lt;User&gt;\\Application Data</code></p>\n" }, { "answer_id": 81779, "author": "pilif", "author_id": 5083, "author_profile": "https://Stackoverflow.com/users/5083", "pm_score": 3, "selected": true, "text": "<p>There is no such folder.</p>\n\n<p>But you can create one.</p>\n\n<p>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</p>\n\n<p>Feel free to create a folder there in your installer and set the ACL so that everyone can write to that folder.</p>\n\n<p>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.</p>\n\n<p>Here is some sample InnoSetup code to create that folder:</p>\n\n<pre><code>[Dirs]\nName: {code:getDBPath}; Flags: uninsalwaysuninstall; Permissions: authusers-modify\n\n[Code]\n\n\nfunction getDBPath(Param: String): String;\nvar\n Version: TWindowsVersion;\nbegin\n Result := ExpandConstant('{app}\\data');\n GetWindowsVersionEx(Version);\n if (Version.Major &gt;= 5) then begin\n Result := ExpandConstant('{commonappdata}\\myprog');\n end;\nend;\n</code></pre>\n" } ]
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>.</p>\n\n<p>Alternatively, you could roll your own by just using a database (e.g. sqllite) and SQL. Optionally, write a wrapper script that parses your plain-text file and command-line options, and generates the corresponding SQL.</p>\n" }, { "answer_id": 81782, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://roundup.sourceforge.net/\" rel=\"nofollow noreferrer\">http://roundup.sourceforge.net/</a></p>\n" }, { "answer_id": 81799, "author": "binOr", "author_id": 990, "author_profile": "https://Stackoverflow.com/users/990", "pm_score": 0, "selected": false, "text": "<p>Fogbugz has a <a href=\"http://support.fogcreek.com/default.asp?W840\" rel=\"nofollow noreferrer\">Command Line Client</a>.</p>\n" }, { "answer_id": 81801, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 1, "selected": false, "text": "<p>@Peter Hilton,</p>\n\n<p>I'm going to create such system. So I'm wondering whether such system exists. General idea is to keep it as simple as possible: command line utility to manage tasks &amp; simple server wit REST interface. I used dozen different task tracking system and come to conclusion that I don't need fancy UI. It should be like Subversion - you can happily work with command-line based svn.exe</p>\n" }, { "answer_id": 83775, "author": "Matt", "author_id": 15368, "author_profile": "https://Stackoverflow.com/users/15368", "pm_score": 2, "selected": false, "text": "<p>Have you seen <a href=\"http://github.com/schacon/ticgit/wikis\" rel=\"nofollow noreferrer\">ticgit</a>. It sounds like it might do just what you guys are after.</p>\n" }, { "answer_id": 211318, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<blockquote>\n <p>Ditz is a simple, light-weight distributed issue tracker designed to work\n with distributed version control systems like darcs and git.</p>\n</blockquote>\n\n<p>Ditz: <a href=\"http://web.archive.org/web/20121212202849/http://gitorious.org/ditz\" rel=\"nofollow noreferrer\">http://web.archive.org/web/20121212202849/http://gitorious.org/ditz</a> </p>\n\n<p>Also cloned here: <a href=\"https://github.com/jashmenn/ditz\" rel=\"nofollow noreferrer\">https://github.com/jashmenn/ditz</a></p>\n" }, { "answer_id": 248713, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 1, "selected": false, "text": "<p>I've abused the <code>cal</code> and <code>calendar</code> commandline tools regularly for this type of task.</p>\n" }, { "answer_id": 2334299, "author": "Offe", "author_id": 191304, "author_profile": "https://Stackoverflow.com/users/191304", "pm_score": 0, "selected": false, "text": "<p>Have a look at <a href=\"http://pitz.tplus1.com/\" rel=\"nofollow noreferrer\">Pitz</a> and <a href=\"http://bugseverywhere.org/be/show/HomePage\" rel=\"nofollow noreferrer\">Bugs Everywhere</a>. </p>\n" }, { "answer_id": 2596785, "author": "taltman", "author_id": 311492, "author_profile": "https://Stackoverflow.com/users/311492", "pm_score": 0, "selected": false, "text": "<p>I use <a href=\"http://www.org-mode.org\" rel=\"nofollow noreferrer\">org-mode</a> with emacs in terminal mode (emacs -nw).</p>\n" }, { "answer_id": 3764787, "author": "Henrik", "author_id": 63984, "author_profile": "https://Stackoverflow.com/users/63984", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://codespeak.net/ciss/\" rel=\"nofollow noreferrer\">ciss</a> issue tracker is a simple commandline tool for managing your ISSUES.txt file.</p>\n" }, { "answer_id": 24465778, "author": "neoneye", "author_id": 78336, "author_profile": "https://Stackoverflow.com/users/78336", "pm_score": 2, "selected": false, "text": "<h1>Erlangs Ticket System</h1>\n\n<p>Created by Peter Högfeldt in 1986. This is the ticket system that was used in the Erlang distribution.</p>\n\n<p>Source: <a href=\"https://joearms.github.io/published/2014-06-25-minimal-viable-program.html\" rel=\"nofollow noreferrer\">Joe Armstrong's blog</a></p>\n" }, { "answer_id": 54624847, "author": "mesibo", "author_id": 4895359, "author_profile": "https://Stackoverflow.com/users/4895359", "pm_score": 0, "selected": false, "text": "<p>We have used a few tools earlier. We now use a GitHub private repository to maintain various developer TBD lists (as .md files) and issue tracking because of the following advantages: </p>\n\n<ul>\n<li>Developers are already using GitHub and they don't need to learn anything new. </li>\n<li>Developers can use whatever tool they are comfortable with to maintain TBD list; command line or graphical editors, GitHub web interface or plenty of mobile clients</li>\n<li>Markdown support</li>\n<li>Reliable backup </li>\n<li>Merging and revision history</li>\n<li>Flexible file organization for different projects and modules </li>\n</ul>\n" } ]
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. It is trying to look for a file called \" stdio.h \" with a space at the beginning and end.</p>\n" }, { "answer_id": 81736, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 2, "selected": false, "text": "<p>You should try to install MinGW in the default install directory (i.e. C:\\MinGW) I read many times it was recommended to avoid problems. There may be a (wrongly) hardcoded path in gcc.</p>\n" }, { "answer_id": 89036, "author": "aib", "author_id": 1088, "author_profile": "https://Stackoverflow.com/users/1088", "pm_score": 0, "selected": false, "text": "<p>Also note that main() should return an int:</p>\n\n<pre><code>int main(void)\n</code></pre>\n" }, { "answer_id": 21968019, "author": "kaka", "author_id": 1934048, "author_profile": "https://Stackoverflow.com/users/1934048", "pm_score": -1, "selected": false, "text": "<p>You can use</p>\n\n<p>$ sudo apt-get install build-essential</p>\n\n<p>to solve this problem</p>\n" } ]
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 <a href=\"http://en.wikipedia.org/wiki/Covariant_return_type\" rel=\"nofollow noreferrer\">covariant returns</a>. <code>Java 5</code> added support, but it didn't receive the pub it deserved.</p>\n" }, { "answer_id": 81796, "author": "jrudolph", "author_id": 7647, "author_profile": "https://Stackoverflow.com/users/7647", "pm_score": 1, "selected": false, "text": "<p>Something like that should work:</p>\n\n<pre><code>interface Node{\n}\ninterface NodeType&lt;T extends Node&gt;{\n T createInstance();\n}\nclass Thing implements Node{}\nclass ThingType implements NodeType&lt;Thing&gt;{\n public Thing createInstance() {\n return new Thing();\n }\n}\nclass UberThing extends Thing{}\nclass UberThingType extends ThingType{\n @Override\n public UberThing createInstance() {\n return new UberThing();\n }\n}\n</code></pre>\n" }, { "answer_id": 81825, "author": "UlfJack", "author_id": 15551, "author_profile": "https://Stackoverflow.com/users/15551", "pm_score": 2, "selected": false, "text": "<p>Two ways:</p>\n\n<p>(a) Don't use generics. It's probably not necessary in this case. (Although that depends on the code you havn't shown.)</p>\n\n<p>(b) Generify AbstractNodeType as follows:</p>\n\n<pre><code>public abstract class AbstractNodeType&lt;T extends AbstractNode&gt; {\n public abstract T createInstance();\n}\npublic class ThingType&lt;Thing&gt; {\n public Thing createInstance() {\n return new Thing(...);\n }\n}\n</code></pre>\n" } ]
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 enough to stop the garbage collection?</p>\n" }, { "answer_id": 81755, "author": "Grad van Horck", "author_id": 12569, "author_profile": "https://Stackoverflow.com/users/12569", "pm_score": -1, "selected": false, "text": "<p>Assign the new Thread to a local field?</p>\n\n<pre><code>class YourClass\n{\n Thread thread;\n\n void Start()\n {\n thread = new Thread(Foo);\n thread.Start();\n GC.Collect();\n }\n}\n</code></pre>\n\n<p>Garbage Collection collects everyting that is not references, so in your code there is no field/variable referencing to the thread, so it will be collected.</p>\n" }, { "answer_id": 81763, "author": "EricSchaefer", "author_id": 8976, "author_profile": "https://Stackoverflow.com/users/8976", "pm_score": 5, "selected": true, "text": "<p>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.</p>\n" }, { "answer_id": 81805, "author": "ima", "author_id": 5733, "author_profile": "https://Stackoverflow.com/users/5733", "pm_score": 2, "selected": false, "text": "<p>It's a hard-wired feature of garbage collector. Running threads are not collected.</p>\n" }, { "answer_id": 100763, "author": "Damien_The_Unbeliever", "author_id": 15498, "author_profile": "https://Stackoverflow.com/users/15498", "pm_score": 0, "selected": false, "text": "<p>Important point to note though - if your thread is marked with IsBackground=True, it won't prevent the whole process from exiting</p>\n" }, { "answer_id": 100850, "author": "Ilya Ryzhenkov", "author_id": 18575, "author_profile": "https://Stackoverflow.com/users/18575", "pm_score": 3, "selected": false, "text": "<p>It depends on whether the thread is running or not. If you just created Thread object and didn't start it, it is an ordinary managed object, i.e. eligible for GC. As soon as you start thread, or when you obtain Thread object for already running thread (GetCurrentThread) it is a bit different. The \"exposed object\", managed Thread, is now hold on strong reference within CLR, so you always get the same instance. When thread terminates, this strong reference is released, and the managed object will be collected as soon as you don't have any other references to (now dead) Thread.</p>\n" } ]
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 \"onbeforeunload\" event.</p>\n" }, { "answer_id": 221162, "author": "Joshi Spawnbrood", "author_id": 15392, "author_profile": "https://Stackoverflow.com/users/15392", "pm_score": 0, "selected": false, "text": "<p>Are you sure nothing is tryin to access the map , when you close the window?</p>\n\n<p>I'd do this type of test:</p>\n\n<p>have a wrapper to reach the map itself, and, on unload, have the wrapper block access to map itself.</p>\n" }, { "answer_id": 364640, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 1, "selected": false, "text": "<p>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).</p>\n" } ]
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 {[email protected]?} 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 available tools are, for example, the mCRL2 toolset (using a ACP-based language), the Mobility Workbench (pi-calculus) and Spin (PROMELA).</p>\n\n<p>Otherwise I would suggest removing every bit of code that is not essential to the problem and finding a minimal case where the deadlock occurs. I doubt that it the 100 threads and 1300 tasks are essential to get a deadlock. With a smaller case you can probably just add some debug prints which provide enough information the solve the problem.</p>\n" }, { "answer_id": 82061, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 1, "selected": false, "text": "<p>Ok, the problem seems to be in your ThreadPool#signal method. What may happen is:</p>\n\n<p>1 - All your worker are busy and you try to process a new job</p>\n\n<p>2 - line 90 gets a nil worker</p>\n\n<p>3 - a worker get freed and signals it, but the signal is lost as the ThreadPool is not waiting for it</p>\n\n<p>4 - you fall on line 95, waiting even though there is a free worker.</p>\n\n<p>The error here is that you can signal a free worker even when nobody is listening. This ThreadPool#signal method should be:</p>\n\n<pre><code>def signal\n @mutex.synchronize { @cv.signal }\nend\n</code></pre>\n\n<p>And the problem is the same in the Worker object. What might happen is:</p>\n\n<p>1 - The Worker just completed a job</p>\n\n<p>2 - It checks (line 17) if there is a job waiting: there isn't</p>\n\n<p>3 - The thread pool send a new job and signals it ... but the signal is lost</p>\n\n<p>4 - The worker wait for a signal, even though it is marked as busy</p>\n\n<p>You should put your initialize method as:</p>\n\n<pre><code>def initialize(callback)\n @mutex = Mutex.new\n @cv = ConditionVariable.new\n @callback = callback\n @mutex.synchronize {@running = true}\n @thread = Thread.new do\n @mutex.synchronize do\n while @running\n block = get_block\n if block\n @mutex.unlock\n block.call\n @mutex.lock\n reset_block\n # Signal the ThreadPool that this worker is ready for another job\n @callback.signal\n else\n # Wait for a new job\n @cv.wait(@mutex)\n end\n end\n end\n end\nend\n</code></pre>\n\n<p>Next, the Worker#get_block and Worker#reset_block methods should not be synchronized anymore. That way, you cannot have a block assigned to a worker between the test for a block and the wait for a signal.</p>\n" }, { "answer_id": 82777, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 5, "selected": true, "text": "<p>Ok, so the main problem with the implementation is: how to make sure no signal is lost and avoid dead locks ?</p>\n\n<p>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:</p>\n\n<pre><code>require 'thread'\nbegin\n require 'fasttread'\nrescue LoadError\n $stderr.puts \"Using the ruby-core thread implementation\"\nend\n\nclass ThreadPool\n class Worker\n def initialize(thread_queue)\n @mutex = Mutex.new\n @cv = ConditionVariable.new\n @queue = thread_queue\n @running = true\n @thread = Thread.new do\n @mutex.synchronize do\n while @running\n @cv.wait(@mutex)\n block = get_block\n if block\n @mutex.unlock\n block.call\n @mutex.lock\n reset_block\n end\n @queue &lt;&lt; self\n end\n end\n end\n end\n\n def name\n @thread.inspect\n end\n\n def get_block\n @block\n end\n\n def set_block(block)\n @mutex.synchronize do\n raise RuntimeError, \"Thread already busy.\" if @block\n @block = block\n # Signal the thread in this class, that there's a job to be done\n @cv.signal\n end\n end\n\n def reset_block\n @block = nil\n end\n\n def busy?\n @mutex.synchronize { [email protected]? }\n end\n\n def stop\n @mutex.synchronize do\n @running = false\n @cv.signal\n end\n @thread.join\n end\n end\n\n attr_accessor :max_size\n\n def initialize(max_size = 10)\n @max_size = max_size\n @queue = Queue.new\n @workers = []\n end\n\n def size\n @workers.size\n end\n\n def busy?\n @queue.size &lt; @workers.size\n end\n\n def shutdown\n @workers.each { |w| w.stop }\n @workers = []\n end\n\n alias :join :shutdown\n\n def process(block=nil,&amp;blk)\n block = blk if block_given?\n worker = get_worker\n worker.set_block(block)\n end\n\n private\n\n def get_worker\n if [email protected]? or @workers.size == @max_size\n return @queue.pop\n else\n worker = Worker.new(@queue)\n @workers &lt;&lt; worker\n worker\n end\n end\n\nend\n</code></pre>\n\n<p>And here is a simple test code:</p>\n\n<pre><code>tp = ThreadPool.new 500\n(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\" } }\ntp.shutdown\n</code></pre>\n" }, { "answer_id": 2063180, "author": "Filipe Miguel Fonseca", "author_id": 112744, "author_profile": "https://Stackoverflow.com/users/112744", "pm_score": 3, "selected": false, "text": "<p>You can try the <a href=\"http://gemcutter.org/gems/work_queue\" rel=\"nofollow noreferrer\">work_queue</a> gem, designed to coordinate work between a producer and a pool of worker threads.</p>\n" }, { "answer_id": 51769759, "author": "bking", "author_id": 7915982, "author_profile": "https://Stackoverflow.com/users/7915982", "pm_score": 1, "selected": false, "text": "<p>Top commenter's code has helped out so much over the years. Here it is updated for ruby 2.x and improved with thread identification. How is that an improvement? When each thread has an ID, you can compose ThreadPool with an array which stores arbitrary information. Some ideas:</p>\n\n<ul>\n<li>No array: typical ThreadPool usage. Even with the GIL it makes threading dead easy to code and very useful for high-latency applications like high-volume web crawling,</li>\n<li>ThreadPool and Array sized to number of CPUs: easy to fork processes to use all CPUs,</li>\n<li>ThreadPool and Array sized to number of resources: e.g., each array element represents one processor across a pool of instances, so if you have 10 instances each with 4 CPUs, the TP can manage work across 40 subprocesses.</li>\n</ul>\n\n<p>With these last two, rather than thinking about threads doing work think about the ThreadPool managing subprocesses that are doing the work. The management task is lightweight and when combined with subprocesses, who cares about the GIL. </p>\n\n<p>With this class, you can code up a cluster based MapReduce in about a hundred lines of code! This code is beautifully short although it can be a bit of a mind-bend to fully grok. Hope it helps.</p>\n\n<pre><code># Usage:\n#\n# Thread.abort_on_exception = true # help localize errors while debugging\n# pool = ThreadPool.new(thread_pool_size)\n# 50.times {|i|\n# pool.process { ... }\n# or\n# pool.process {|id| ... } # worker identifies itself as id\n# }\n# pool.shutdown()\n\nclass ThreadPool\n\n require 'thread'\n\n class ThreadPoolWorker\n\n attr_accessor :id\n\n def initialize(thread_queue, id)\n @id = id # worker id is exposed thru tp.process {|id| ... }\n @mutex = Mutex.new\n @cv = ConditionVariable.new\n @idle_queue = thread_queue\n @running = true\n @block = nil\n @thread = Thread.new {\n @mutex.synchronize {\n while @running\n @cv.wait(@mutex) # block until there is work to do\n if @block\n @mutex.unlock\n begin\n @block.call(@id)\n ensure\n @mutex.lock\n end\n @block = nil\n end\n @idle_queue &lt;&lt; self\n end\n }\n }\n end\n\n def set_block(block)\n @mutex.synchronize {\n raise RuntimeError, \"Thread is busy.\" if @block\n @block = block\n @cv.signal # notify thread in this class, there is work to be done\n }\n end\n\n def busy?\n @mutex.synchronize { ! @block.nil? }\n end\n\n def stop\n @mutex.synchronize {\n @running = false\n @cv.signal\n }\n @thread.join\n end\n\n def name\n @thread.inspect\n end\n end\n\n\n attr_accessor :max_size, :queue\n\n def initialize(max_size = 10)\n @process_mutex = Mutex.new\n @max_size = max_size\n @queue = Queue.new # of idle workers\n @workers = [] # array to hold workers\n\n # construct workers\n @max_size.times {|i| @workers &lt;&lt; ThreadPoolWorker.new(@queue, i) }\n\n # queue up workers (workers in queue are idle and available to\n # work). queue blocks if no workers are available.\n @max_size.times {|i| @queue &lt;&lt; @workers[i] }\n\n sleep 1 # important to give threads a chance to initialize\n end\n\n def size\n @workers.size\n end\n\n def idle\n @queue.size\n end\n\n # are any threads idle\n\n def busy?\n # @queue.size &lt; @workers.size\n @queue.size == 0 &amp;&amp; @workers.size == @max_size\n end\n\n # block until all threads finish\n\n def shutdown\n @workers.each {|w| w.stop }\n @workers = []\n end\n\n alias :join :shutdown\n\n def process(block = nil, &amp;blk)\n @process_mutex.synchronize {\n block = blk if block_given?\n worker = @queue.pop # assign to next worker; block until one is ready\n worker.set_block(block) # give code block to worker and tell it to start\n }\n end\n\n\nend\n</code></pre>\n" } ]
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 {[email protected]?} 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 { [email protected]? } 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 [email protected]? 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; typeid(a).name() &lt;&lt; '\\n';\n</code></pre>\n\n<p>You might have to activate RTTI in your compiler options for this to work. Additionally, the output of this depends on the compiler. It might be a raw type name or a name mangling symbol or anything in between.</p>\n" }, { "answer_id": 81913, "author": "mdec", "author_id": 15534, "author_profile": "https://Stackoverflow.com/users/15534", "pm_score": 6, "selected": false, "text": "<p>Don't forget to include <code>&lt;typeinfo&gt;</code></p>\n\n<p>I believe what you are referring to is runtime type identification. You can achieve the above by doing .</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;typeinfo&gt;\n\nusing namespace std;\n\nint main() {\n int i;\n cout &lt;&lt; typeid(i).name();\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 81939, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": false, "text": "<p>You could use a traits class for this. Something like:</p>\n\n<pre><code>#include &lt;iostream&gt;\nusing namespace std;\n\ntemplate &lt;typename T&gt; class type_name {\npublic:\n static const char *name;\n};\n\n#define DECLARE_TYPE_NAME(x) template&lt;&gt; const char *type_name&lt;x&gt;::name = #x;\n#define GET_TYPE_NAME(x) (type_name&lt;typeof(x)&gt;::name)\n\nDECLARE_TYPE_NAME(int);\n\nint main()\n{\n int a = 12;\n cout &lt;&lt; GET_TYPE_NAME(a) &lt;&lt; endl;\n}\n</code></pre>\n\n<p>The <code>DECLARE_TYPE_NAME</code> define exists to make your life easier in declaring this traits class for all the types you expect to need.</p>\n\n<p>This might be more useful than the solutions involving <code>typeid</code> because you get to control the output. For example, using <code>typeid</code> for <code>long long</code> on my compiler gives \"x\".</p>\n" }, { "answer_id": 81956, "author": "Nick", "author_id": 3233, "author_profile": "https://Stackoverflow.com/users/3233", "pm_score": 5, "selected": false, "text": "<p>You can use templates.</p>\n\n<pre><code>template &lt;typename T&gt; const char* typeof(T&amp;) { return \"unknown\"; } // default\ntemplate&lt;&gt; const char* typeof(int&amp;) { return \"int\"; }\ntemplate&lt;&gt; const char* typeof(float&amp;) { return \"float\"; }\n</code></pre>\n\n<p>In the example above, when the type is not matched it will print \"unknown\". </p>\n" }, { "answer_id": 82102, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 5, "selected": false, "text": "<p>Note that the names generated by the RTTI feature of C++ is <strong>not</strong> portable.\nFor example, the class</p>\n\n<pre><code>MyNamespace::CMyContainer&lt;int, test_MyNamespace::CMyObject&gt;\n</code></pre>\n\n<p>will have the following names:</p>\n\n<pre><code>// MSVC 2003:\nclass MyNamespace::CMyContainer[int,class test_MyNamespace::CMyObject]\n// G++ 4.2:\nN8MyNamespace8CMyContainerIiN13test_MyNamespace9CMyObjectEEE\n</code></pre>\n\n<p>So you can't use this information for serialization. But still, the typeid(a).name() property can still be used for log/debug purposes</p>\n" }, { "answer_id": 82144, "author": "James Hopkin", "author_id": 11828, "author_profile": "https://Stackoverflow.com/users/11828", "pm_score": 3, "selected": false, "text": "<p>The other answers involving RTTI (typeid) are probably what you want, as long as:</p>\n\n<ul>\n<li>you can afford the memory overhead (which can be considerable with some compilers)</li>\n<li>the class names your compiler returns are useful</li>\n</ul>\n\n<p>The alternative, (similar to Greg Hewgill's answer), is to build a compile-time table of traits.</p>\n\n<pre><code>template &lt;typename T&gt; struct type_as_string;\n\n// declare your Wibble type (probably with definition of Wibble)\ntemplate &lt;&gt;\nstruct type_as_string&lt;Wibble&gt;\n{\n static const char* const value = \"Wibble\";\n};\n</code></pre>\n\n<p>Be aware that if you wrap the declarations in a macro, you'll have trouble declaring names for template types taking more than one parameter (e.g. std::map), due to the comma.</p>\n\n<p>To access the name of the type of a variable, all you need is</p>\n\n<pre><code>template &lt;typename T&gt;\nconst char* get_type_as_string(const T&amp;)\n{\n return type_as_string&lt;T&gt;::value;\n}\n</code></pre>\n" }, { "answer_id": 14617848, "author": "NickV", "author_id": 1617892, "author_profile": "https://Stackoverflow.com/users/1617892", "pm_score": 7, "selected": false, "text": "<p>Very ugly but does the trick if you only want compile time info (e.g. for debugging):</p>\n\n<pre><code>auto testVar = std::make_tuple(1, 1.0, \"abc\");\ndecltype(testVar)::foo= 1;\n</code></pre>\n\n<p>Returns:</p>\n\n<pre><code>Compilation finished with errors:\nsource.cpp: In function 'int main()':\nsource.cpp:5:19: error: 'foo' is not a member of 'std::tuple&lt;int, double, const char*&gt;'\n</code></pre>\n" }, { "answer_id": 14633413, "author": "ipapadop", "author_id": 487362, "author_profile": "https://Stackoverflow.com/users/487362", "pm_score": 5, "selected": false, "text": "<p>As mentioned, <code>typeid().name()</code> may return a mangled name. In GCC (and some other compilers) you can work around it with the following code:</p>\n\n<pre><code>#include &lt;cxxabi.h&gt;\n#include &lt;iostream&gt;\n#include &lt;typeinfo&gt;\n#include &lt;cstdlib&gt;\n\nnamespace some_namespace { namespace another_namespace {\n\n class my_class { };\n\n} }\n\nint main() {\n typedef some_namespace::another_namespace::my_class my_type;\n // mangled\n std::cout &lt;&lt; typeid(my_type).name() &lt;&lt; std::endl;\n\n // unmangled\n int status = 0;\n char* demangled = abi::__cxa_demangle(typeid(my_type).name(), 0, 0, &amp;status);\n\n switch (status) {\n case -1: {\n // could not allocate memory\n std::cout &lt;&lt; \"Could not allocate memory\" &lt;&lt; std::endl;\n return -1;\n } break;\n case -2: {\n // invalid name under the C++ ABI mangling rules\n std::cout &lt;&lt; \"Invalid name\" &lt;&lt; std::endl;\n return -1;\n } break;\n case -3: {\n // invalid argument\n std::cout &lt;&lt; \"Invalid argument to demangle()\" &lt;&lt; std::endl;\n return -1;\n } break;\n }\n std::cout &lt;&lt; demangled &lt;&lt; std::endl;\n\n free(demangled);\n\n return 0;\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 20170989, "author": "Howard Hinnant", "author_id": 576911, "author_profile": "https://Stackoverflow.com/users/576911", "pm_score": 11, "selected": true, "text": "<p>C++11 update to a very old question: Print variable type in C++.</p>\n<p>The accepted (and good) answer is to use <code>typeid(a).name()</code>, where <code>a</code> is a variable name.</p>\n<p>Now in C++11 we have <code>decltype(x)</code>, which can turn an expression into a type. And <code>decltype()</code> comes with its own set of very interesting rules. For example <code>decltype(a)</code> and <code>decltype((a))</code> will generally be different types (and for good and understandable reasons once those reasons are exposed).</p>\n<p>Will our trusty <code>typeid(a).name()</code> help us explore this brave new world?</p>\n<p>No.</p>\n<p>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 <code>typeid(a).name()</code>. And this new tool is actually built on top of <code>typeid(a).name()</code>.</p>\n<p><strong>The fundamental issue:</strong></p>\n<pre><code>typeid(a).name()\n</code></pre>\n<p>throws away cv-qualifiers, references, and lvalue/rvalue-ness. For example:</p>\n<pre><code>const int ci = 0;\nstd::cout &lt;&lt; typeid(ci).name() &lt;&lt; '\\n';\n</code></pre>\n<p>For me outputs:</p>\n<pre><code>i\n</code></pre>\n<p>and I'm guessing on MSVC outputs:</p>\n<pre><code>int\n</code></pre>\n<p>I.e. the <code>const</code> is gone. This is not a QOI (Quality Of Implementation) issue. The standard mandates this behavior.</p>\n<p>What I'm recommending below is:</p>\n<pre><code>template &lt;typename T&gt; std::string type_name();\n</code></pre>\n<p>which would be used like this:</p>\n<pre><code>const int ci = 0;\nstd::cout &lt;&lt; type_name&lt;decltype(ci)&gt;() &lt;&lt; '\\n';\n</code></pre>\n<p>and for me outputs:</p>\n<pre><code>int const\n</code></pre>\n<p><code>&lt;disclaimer&gt;</code> I have not tested this on MSVC. <code>&lt;/disclaimer&gt;</code> But I welcome feedback from those who do.</p>\n<p><strong>The C++11 Solution</strong></p>\n<p>I am using <code>__cxa_demangle</code> for non-MSVC platforms as recommend by <a href=\"https://stackoverflow.com/users/487362/ipapadop\">ipapadop</a> in his answer to demangle types. But on MSVC I'm trusting <code>typeid</code> 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.</p>\n<pre><code>#include &lt;type_traits&gt;\n#include &lt;typeinfo&gt;\n#ifndef _MSC_VER\n# include &lt;cxxabi.h&gt;\n#endif\n#include &lt;memory&gt;\n#include &lt;string&gt;\n#include &lt;cstdlib&gt;\n\ntemplate &lt;class T&gt;\nstd::string\ntype_name()\n{\n typedef typename std::remove_reference&lt;T&gt;::type TR;\n std::unique_ptr&lt;char, void(*)(void*)&gt; own\n (\n#ifndef _MSC_VER\n abi::__cxa_demangle(typeid(TR).name(), nullptr,\n nullptr, nullptr),\n#else\n nullptr,\n#endif\n std::free\n );\n std::string r = own != nullptr ? own.get() : typeid(TR).name();\n if (std::is_const&lt;TR&gt;::value)\n r += &quot; const&quot;;\n if (std::is_volatile&lt;TR&gt;::value)\n r += &quot; volatile&quot;;\n if (std::is_lvalue_reference&lt;T&gt;::value)\n r += &quot;&amp;&quot;;\n else if (std::is_rvalue_reference&lt;T&gt;::value)\n r += &quot;&amp;&amp;&quot;;\n return r;\n}\n</code></pre>\n<p><strong>The Results</strong></p>\n<p>With this solution I can do this:</p>\n<pre><code>int&amp; foo_lref();\nint&amp;&amp; foo_rref();\nint foo_value();\n\nint\nmain()\n{\n int i = 0;\n const int ci = 0;\n std::cout &lt;&lt; &quot;decltype(i) is &quot; &lt;&lt; type_name&lt;decltype(i)&gt;() &lt;&lt; '\\n';\n std::cout &lt;&lt; &quot;decltype((i)) is &quot; &lt;&lt; type_name&lt;decltype((i))&gt;() &lt;&lt; '\\n';\n std::cout &lt;&lt; &quot;decltype(ci) is &quot; &lt;&lt; type_name&lt;decltype(ci)&gt;() &lt;&lt; '\\n';\n std::cout &lt;&lt; &quot;decltype((ci)) is &quot; &lt;&lt; type_name&lt;decltype((ci))&gt;() &lt;&lt; '\\n';\n std::cout &lt;&lt; &quot;decltype(static_cast&lt;int&amp;&gt;(i)) is &quot; &lt;&lt; type_name&lt;decltype(static_cast&lt;int&amp;&gt;(i))&gt;() &lt;&lt; '\\n';\n std::cout &lt;&lt; &quot;decltype(static_cast&lt;int&amp;&amp;&gt;(i)) is &quot; &lt;&lt; type_name&lt;decltype(static_cast&lt;int&amp;&amp;&gt;(i))&gt;() &lt;&lt; '\\n';\n std::cout &lt;&lt; &quot;decltype(static_cast&lt;int&gt;(i)) is &quot; &lt;&lt; type_name&lt;decltype(static_cast&lt;int&gt;(i))&gt;() &lt;&lt; '\\n';\n std::cout &lt;&lt; &quot;decltype(foo_lref()) is &quot; &lt;&lt; type_name&lt;decltype(foo_lref())&gt;() &lt;&lt; '\\n';\n std::cout &lt;&lt; &quot;decltype(foo_rref()) is &quot; &lt;&lt; type_name&lt;decltype(foo_rref())&gt;() &lt;&lt; '\\n';\n std::cout &lt;&lt; &quot;decltype(foo_value()) is &quot; &lt;&lt; type_name&lt;decltype(foo_value())&gt;() &lt;&lt; '\\n';\n}\n</code></pre>\n<p>and the output is:</p>\n<pre><code>decltype(i) is int\ndecltype((i)) is int&amp;\ndecltype(ci) is int const\ndecltype((ci)) is int const&amp;\ndecltype(static_cast&lt;int&amp;&gt;(i)) is int&amp;\ndecltype(static_cast&lt;int&amp;&amp;&gt;(i)) is int&amp;&amp;\ndecltype(static_cast&lt;int&gt;(i)) is int\ndecltype(foo_lref()) is int&amp;\ndecltype(foo_rref()) is int&amp;&amp;\ndecltype(foo_value()) is int\n</code></pre>\n<p>Note (for example) the difference between <code>decltype(i)</code> and <code>decltype((i))</code>. The former is the type of the <em>declaration</em> of <code>i</code>. The latter is the &quot;type&quot; of the <em>expression</em> <code>i</code>. (expressions never have reference type, but as a convention <code>decltype</code> represents lvalue expressions with lvalue references).</p>\n<p>Thus this tool is an excellent vehicle just to learn about <code>decltype</code>, in addition to exploring and debugging your own code.</p>\n<p>In contrast, if I were to build this just on <code>typeid(a).name()</code>, without adding back lost cv-qualifiers or references, the output would be:</p>\n<pre><code>decltype(i) is int\ndecltype((i)) is int\ndecltype(ci) is int\ndecltype((ci)) is int\ndecltype(static_cast&lt;int&amp;&gt;(i)) is int\ndecltype(static_cast&lt;int&amp;&amp;&gt;(i)) is int\ndecltype(static_cast&lt;int&gt;(i)) is int\ndecltype(foo_lref()) is int\ndecltype(foo_rref()) is int\ndecltype(foo_value()) is int\n</code></pre>\n<p>I.e. Every reference and cv-qualifier is stripped off.</p>\n<p><strong>C++14 Update</strong></p>\n<p>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. :-)</p>\n<p><a href=\"https://stackoverflow.com/a/35943472/576911\">This answer</a> from <a href=\"https://stackoverflow.com/users/2969631/jamboree\">Jamboree</a> shows how to get the type name in C++14 at compile time. It is a brilliant solution for a couple reasons:</p>\n<ol>\n<li>It's at compile time!</li>\n<li>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).</li>\n</ol>\n<p><a href=\"https://stackoverflow.com/users/2969631/jamboree\">Jamboree's</a> <a href=\"https://stackoverflow.com/a/35943472/576911\">answer</a> 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.</p>\n<pre><code>#include &lt;cstddef&gt;\n#include &lt;stdexcept&gt;\n#include &lt;cstring&gt;\n#include &lt;ostream&gt;\n\n#ifndef _MSC_VER\n# if __cplusplus &lt; 201103\n# define CONSTEXPR11_TN\n# define CONSTEXPR14_TN\n# define NOEXCEPT_TN\n# elif __cplusplus &lt; 201402\n# define CONSTEXPR11_TN constexpr\n# define CONSTEXPR14_TN\n# define NOEXCEPT_TN noexcept\n# else\n# define CONSTEXPR11_TN constexpr\n# define CONSTEXPR14_TN constexpr\n# define NOEXCEPT_TN noexcept\n# endif\n#else // _MSC_VER\n# if _MSC_VER &lt; 1900\n# define CONSTEXPR11_TN\n# define CONSTEXPR14_TN\n# define NOEXCEPT_TN\n# elif _MSC_VER &lt; 2000\n# define CONSTEXPR11_TN constexpr\n# define CONSTEXPR14_TN\n# define NOEXCEPT_TN noexcept\n# else\n# define CONSTEXPR11_TN constexpr\n# define CONSTEXPR14_TN constexpr\n# define NOEXCEPT_TN noexcept\n# endif\n#endif // _MSC_VER\n\nclass static_string\n{\n const char* const p_;\n const std::size_t sz_;\n\npublic:\n typedef const char* const_iterator;\n\n template &lt;std::size_t N&gt;\n CONSTEXPR11_TN static_string(const char(&amp;a)[N]) NOEXCEPT_TN\n : p_(a)\n , sz_(N-1)\n {}\n\n CONSTEXPR11_TN static_string(const char* p, std::size_t N) NOEXCEPT_TN\n : p_(p)\n , sz_(N)\n {}\n\n CONSTEXPR11_TN const char* data() const NOEXCEPT_TN {return p_;}\n CONSTEXPR11_TN std::size_t size() const NOEXCEPT_TN {return sz_;}\n\n CONSTEXPR11_TN const_iterator begin() const NOEXCEPT_TN {return p_;}\n CONSTEXPR11_TN const_iterator end() const NOEXCEPT_TN {return p_ + sz_;}\n\n CONSTEXPR11_TN char operator[](std::size_t n) const\n {\n return n &lt; sz_ ? p_[n] : throw std::out_of_range(&quot;static_string&quot;);\n }\n};\n\ninline\nstd::ostream&amp;\noperator&lt;&lt;(std::ostream&amp; os, static_string const&amp; s)\n{\n return os.write(s.data(), s.size());\n}\n\ntemplate &lt;class T&gt;\nCONSTEXPR14_TN\nstatic_string\ntype_name()\n{\n#ifdef __clang__\n static_string p = __PRETTY_FUNCTION__;\n return static_string(p.data() + 31, p.size() - 31 - 1);\n#elif defined(__GNUC__)\n static_string p = __PRETTY_FUNCTION__;\n# if __cplusplus &lt; 201402\n return static_string(p.data() + 36, p.size() - 36 - 1);\n# else\n return static_string(p.data() + 46, p.size() - 46 - 1);\n# endif\n#elif defined(_MSC_VER)\n static_string p = __FUNCSIG__;\n return static_string(p.data() + 38, p.size() - 38 - 7);\n#endif\n}\n</code></pre>\n<p>This code will auto-backoff on the <code>constexpr</code> if you're still stuck in ancient C++11. And if you're painting on the cave wall with C++98/03, the <code>noexcept</code> is sacrificed as well.</p>\n<p><strong>C++17 Update</strong></p>\n<p>In the comments below <a href=\"https://stackoverflow.com/users/3624760/lyberta\">Lyberta</a> points out that the new <code>std::string_view</code> can replace <code>static_string</code>:</p>\n<pre><code>template &lt;class T&gt;\nconstexpr\nstd::string_view\ntype_name()\n{\n using namespace std;\n#ifdef __clang__\n string_view p = __PRETTY_FUNCTION__;\n return string_view(p.data() + 34, p.size() - 34 - 1);\n#elif defined(__GNUC__)\n string_view p = __PRETTY_FUNCTION__;\n# if __cplusplus &lt; 201402\n return string_view(p.data() + 36, p.size() - 36 - 1);\n# else\n return string_view(p.data() + 49, p.find(';', 49) - 49);\n# endif\n#elif defined(_MSC_VER)\n string_view p = __FUNCSIG__;\n return string_view(p.data() + 84, p.size() - 84 - 7);\n#endif\n}\n</code></pre>\n<p>I've updated the constants for VS thanks to the very nice detective work by Jive Dadson in the comments below.</p>\n<h2>Update:</h2>\n<p>Be sure to check out <a href=\"https://stackoverflow.com/a/56766138/576911\">this</a> rewrite or <a href=\"https://stackoverflow.com/a/64490578/576911\">this</a> rewrite below which eliminate the unreadable magic numbers in my latest formulation.</p>\n" }, { "answer_id": 29040615, "author": "Jahid", "author_id": 3744681, "author_profile": "https://Stackoverflow.com/users/3744681", "pm_score": 3, "selected": false, "text": "<p>I like Nick's method, A complete form might be this (for all basic data types):</p>\n\n<pre><code>template &lt;typename T&gt; const char* typeof(T&amp;) { return \"unknown\"; } // default\ntemplate&lt;&gt; const char* typeof(int&amp;) { return \"int\"; }\ntemplate&lt;&gt; const char* typeof(short&amp;) { return \"short\"; }\ntemplate&lt;&gt; const char* typeof(long&amp;) { return \"long\"; }\ntemplate&lt;&gt; const char* typeof(unsigned&amp;) { return \"unsigned\"; }\ntemplate&lt;&gt; const char* typeof(unsigned short&amp;) { return \"unsigned short\"; }\ntemplate&lt;&gt; const char* typeof(unsigned long&amp;) { return \"unsigned long\"; }\ntemplate&lt;&gt; const char* typeof(float&amp;) { return \"float\"; }\ntemplate&lt;&gt; const char* typeof(double&amp;) { return \"double\"; }\ntemplate&lt;&gt; const char* typeof(long double&amp;) { return \"long double\"; }\ntemplate&lt;&gt; const char* typeof(std::string&amp;) { return \"String\"; }\ntemplate&lt;&gt; const char* typeof(char&amp;) { return \"char\"; }\ntemplate&lt;&gt; const char* typeof(signed char&amp;) { return \"signed char\"; }\ntemplate&lt;&gt; const char* typeof(unsigned char&amp;) { return \"unsigned char\"; }\ntemplate&lt;&gt; const char* typeof(char*&amp;) { return \"char*\"; }\ntemplate&lt;&gt; const char* typeof(signed char*&amp;) { return \"signed char*\"; }\ntemplate&lt;&gt; const char* typeof(unsigned char*&amp;) { return \"unsigned char*\"; }\n</code></pre>\n" }, { "answer_id": 29043884, "author": "Jahid", "author_id": 3744681, "author_profile": "https://Stackoverflow.com/users/3744681", "pm_score": 3, "selected": false, "text": "<p>A more generic solution without function overloading than my previous one:</p>\n\n<pre><code>template&lt;typename T&gt;\nstd::string TypeOf(T){\n std::string Type=\"unknown\";\n if(std::is_same&lt;T,int&gt;::value) Type=\"int\";\n if(std::is_same&lt;T,std::string&gt;::value) Type=\"String\";\n if(std::is_same&lt;T,MyClass&gt;::value) Type=\"MyClass\";\n\n return Type;}\n</code></pre>\n\n<p>Here MyClass is user defined class. More conditions can be added here as well.</p>\n\n<p>Example:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\n\n\nclass MyClass{};\n\n\ntemplate&lt;typename T&gt;\nstd::string TypeOf(T){\n std::string Type=\"unknown\";\n if(std::is_same&lt;T,int&gt;::value) Type=\"int\";\n if(std::is_same&lt;T,std::string&gt;::value) Type=\"String\";\n if(std::is_same&lt;T,MyClass&gt;::value) Type=\"MyClass\";\n return Type;}\n\n\nint main(){;\n int a=0;\n std::string s=\"\";\n MyClass my;\n std::cout&lt;&lt;TypeOf(a)&lt;&lt;std::endl;\n std::cout&lt;&lt;TypeOf(s)&lt;&lt;std::endl;\n std::cout&lt;&lt;TypeOf(my)&lt;&lt;std::endl;\n\n return 0;}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>int\nString\nMyClass\n</code></pre>\n" }, { "answer_id": 35703301, "author": "Alan", "author_id": 1691719, "author_profile": "https://Stackoverflow.com/users/1691719", "pm_score": 3, "selected": false, "text": "<p>You may also use c++filt with option -t (type) to demangle the type name:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;typeinfo&gt;\n#include &lt;string&gt;\n\nusing namespace std;\n\nint main() {\n auto x = 1;\n string my_type = typeid(x).name();\n system((\"echo \" + my_type + \" | c++filt -t\").c_str());\n return 0;\n}\n</code></pre>\n\n<p>Tested on linux only.</p>\n" }, { "answer_id": 39937286, "author": "abodeofcode", "author_id": 6942726, "author_profile": "https://Stackoverflow.com/users/6942726", "pm_score": 4, "selected": false, "text": "<p>In C++11, we have decltype. There is no way in standard c++ to display exact type of variable declared using decltype. We can use boost typeindex i.e <code>type_id_with_cvr</code> (cvr stands for const, volatile, reference) to print type like below.</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;boost/type_index.hpp&gt;\n\nusing namespace std;\nusing boost::typeindex::type_id_with_cvr;\n\nint main() {\n int i = 0;\n const int ci = 0;\n cout &lt;&lt; \"decltype(i) is \" &lt;&lt; type_id_with_cvr&lt;decltype(i)&gt;().pretty_name() &lt;&lt; '\\n';\n cout &lt;&lt; \"decltype((i)) is \" &lt;&lt; type_id_with_cvr&lt;decltype((i))&gt;().pretty_name() &lt;&lt; '\\n';\n cout &lt;&lt; \"decltype(ci) is \" &lt;&lt; type_id_with_cvr&lt;decltype(ci)&gt;().pretty_name() &lt;&lt; '\\n';\n cout &lt;&lt; \"decltype((ci)) is \" &lt;&lt; type_id_with_cvr&lt;decltype((ci))&gt;().pretty_name() &lt;&lt; '\\n';\n cout &lt;&lt; \"decltype(std::move(i)) is \" &lt;&lt; type_id_with_cvr&lt;decltype(std::move(i))&gt;().pretty_name() &lt;&lt; '\\n';\n cout &lt;&lt; \"decltype(std::static_cast&lt;int&amp;&amp;&gt;(i)) is \" &lt;&lt; type_id_with_cvr&lt;decltype(static_cast&lt;int&amp;&amp;&gt;(i))&gt;().pretty_name() &lt;&lt; '\\n';\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 45457278, "author": "Graywolf", "author_id": 7138477, "author_profile": "https://Stackoverflow.com/users/7138477", "pm_score": 2, "selected": false, "text": "<pre><code>#include &lt;iostream&gt;\n#include &lt;typeinfo&gt;\nusing namespace std;\n#define show_type_name(_t) \\\n system((\"echo \" + string(typeid(_t).name()) + \" | c++filt -t\").c_str())\n\nint main() {\n auto a = {\"one\", \"two\", \"three\"};\n cout &lt;&lt; \"Type of a: \" &lt;&lt; typeid(a).name() &lt;&lt; endl;\n cout &lt;&lt; \"Real type of a:\\n\";\n show_type_name(a);\n for (auto s : a) {\n if (string(s) == \"one\") {\n cout &lt;&lt; \"Type of s: \" &lt;&lt; typeid(s).name() &lt;&lt; endl;\n cout &lt;&lt; \"Real type of s:\\n\";\n show_type_name(s);\n }\n cout &lt;&lt; s &lt;&lt; endl;\n }\n\n int i = 5;\n cout &lt;&lt; \"Type of i: \" &lt;&lt; typeid(i).name() &lt;&lt; endl;\n cout &lt;&lt; \"Real type of i:\\n\";\n show_type_name(i);\n return 0;\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Type of a: St16initializer_listIPKcE\nReal type of a:\nstd::initializer_list&lt;char const*&gt;\nType of s: PKc\nReal type of s:\nchar const*\none\ntwo\nthree\nType of i: i\nReal type of i:\nint\n</code></pre>\n" }, { "answer_id": 45743053, "author": "HolyBlackCat", "author_id": 2752075, "author_profile": "https://Stackoverflow.com/users/2752075", "pm_score": 3, "selected": false, "text": "<p>As I challenge I decided to test how far can one go with platform-independent (hopefully) template trickery.</p>\n\n<p>The names are assembled completely at compilation time. (Which means <code>typeid(T).name()</code> couldn't be used, thus you have to explicitly provide names for non-compound types. Otherwise placeholders will be displayed instead.)</p>\n\n<p>Example usage:</p>\n\n<pre><code>TYPE_NAME(int)\nTYPE_NAME(void)\n// You probably should list all primitive types here.\n\nTYPE_NAME(std::string)\n\nint main()\n{\n // A simple case\n std::cout &lt;&lt; type_name&lt;void(*)(int)&gt; &lt;&lt; '\\n';\n // -&gt; `void (*)(int)`\n\n // Ugly mess case\n // Note that compiler removes cv-qualifiers from parameters and replaces arrays with pointers.\n std::cout &lt;&lt; type_name&lt;void (std::string::*(int[3],const int, void (*)(std::string)))(volatile int*const*)&gt; &lt;&lt; '\\n';\n // -&gt; `void (std::string::*(int *,int,void (*)(std::string)))(volatile int *const*)`\n\n // A case with undefined types\n // If a type wasn't TYPE_NAME'd, it's replaced by a placeholder, one of `class?`, `union?`, `enum?` or `??`.\n std::cout &lt;&lt; type_name&lt;std::ostream (*)(int, short)&gt; &lt;&lt; '\\n';\n // -&gt; `class? (*)(int,??)`\n // With appropriate TYPE_NAME's, the output would be `std::string (*)(int,short)`.\n}\n</code></pre>\n\n<p>Code:</p>\n\n<pre><code>#include &lt;type_traits&gt;\n#include &lt;utility&gt;\n\nstatic constexpr std::size_t max_str_lit_len = 256;\n\ntemplate &lt;std::size_t I, std::size_t N&gt; constexpr char sl_at(const char (&amp;str)[N])\n{\n if constexpr(I &lt; N)\n return str[I];\n else\n return '\\0';\n}\n\nconstexpr std::size_t sl_len(const char *str)\n{\n for (std::size_t i = 0; i &lt; max_str_lit_len; i++)\n if (str[i] == '\\0')\n return i;\n return 0;\n}\n\ntemplate &lt;char ...C&gt; struct str_lit\n{\n static constexpr char value[] {C..., '\\0'};\n static constexpr int size = sl_len(value);\n\n template &lt;typename F, typename ...P&gt; struct concat_impl {using type = typename concat_impl&lt;F&gt;::type::template concat_impl&lt;P...&gt;::type;};\n template &lt;char ...CC&gt; struct concat_impl&lt;str_lit&lt;CC...&gt;&gt; {using type = str_lit&lt;C..., CC...&gt;;};\n template &lt;typename ...P&gt; using concat = typename concat_impl&lt;P...&gt;::type;\n};\n\ntemplate &lt;typename, const char *&gt; struct trim_str_lit_impl;\ntemplate &lt;std::size_t ...I, const char *S&gt; struct trim_str_lit_impl&lt;std::index_sequence&lt;I...&gt;, S&gt;\n{\n using type = str_lit&lt;S[I]...&gt;;\n};\ntemplate &lt;std::size_t N, const char *S&gt; using trim_str_lit = typename trim_str_lit_impl&lt;std::make_index_sequence&lt;N&gt;, S&gt;::type;\n\n#define STR_LIT(str) ::trim_str_lit&lt;::sl_len(str), ::str_lit&lt;STR_TO_VA(str)&gt;::value&gt;\n#define STR_TO_VA(str) STR_TO_VA_16(str,0),STR_TO_VA_16(str,16),STR_TO_VA_16(str,32),STR_TO_VA_16(str,48)\n#define STR_TO_VA_16(str,off) STR_TO_VA_4(str,0+off),STR_TO_VA_4(str,4+off),STR_TO_VA_4(str,8+off),STR_TO_VA_4(str,12+off)\n#define STR_TO_VA_4(str,off) ::sl_at&lt;off+0&gt;(str),::sl_at&lt;off+1&gt;(str),::sl_at&lt;off+2&gt;(str),::sl_at&lt;off+3&gt;(str)\n\ntemplate &lt;char ...C&gt; constexpr str_lit&lt;C...&gt; make_str_lit(str_lit&lt;C...&gt;) {return {};}\ntemplate &lt;std::size_t N&gt; constexpr auto make_str_lit(const char (&amp;str)[N])\n{\n return trim_str_lit&lt;sl_len((const char (&amp;)[N])str), str&gt;{};\n}\n\ntemplate &lt;std::size_t A, std::size_t B&gt; struct cexpr_pow {static constexpr std::size_t value = A * cexpr_pow&lt;A,B-1&gt;::value;};\ntemplate &lt;std::size_t A&gt; struct cexpr_pow&lt;A,0&gt; {static constexpr std::size_t value = 1;};\ntemplate &lt;std::size_t N, std::size_t X, typename = std::make_index_sequence&lt;X&gt;&gt; struct num_to_str_lit_impl;\ntemplate &lt;std::size_t N, std::size_t X, std::size_t ...Seq&gt; struct num_to_str_lit_impl&lt;N, X, std::index_sequence&lt;Seq...&gt;&gt;\n{\n static constexpr auto func()\n {\n if constexpr (N &gt;= cexpr_pow&lt;10,X&gt;::value)\n return num_to_str_lit_impl&lt;N, X+1&gt;::func();\n else\n return str_lit&lt;(N / cexpr_pow&lt;10,X-1-Seq&gt;::value % 10 + '0')...&gt;{};\n }\n};\ntemplate &lt;std::size_t N&gt; using num_to_str_lit = decltype(num_to_str_lit_impl&lt;N,1&gt;::func());\n\n\nusing spa = str_lit&lt;' '&gt;;\nusing lpa = str_lit&lt;'('&gt;;\nusing rpa = str_lit&lt;')'&gt;;\nusing lbr = str_lit&lt;'['&gt;;\nusing rbr = str_lit&lt;']'&gt;;\nusing ast = str_lit&lt;'*'&gt;;\nusing amp = str_lit&lt;'&amp;'&gt;;\nusing con = str_lit&lt;'c','o','n','s','t'&gt;;\nusing vol = str_lit&lt;'v','o','l','a','t','i','l','e'&gt;;\nusing con_vol = con::concat&lt;spa, vol&gt;;\nusing nsp = str_lit&lt;':',':'&gt;;\nusing com = str_lit&lt;','&gt;;\nusing unk = str_lit&lt;'?','?'&gt;;\n\nusing c_cla = str_lit&lt;'c','l','a','s','s','?'&gt;;\nusing c_uni = str_lit&lt;'u','n','i','o','n','?'&gt;;\nusing c_enu = str_lit&lt;'e','n','u','m','?'&gt;;\n\ntemplate &lt;typename T&gt; inline constexpr bool ptr_or_ref = std::is_pointer_v&lt;T&gt; || std::is_reference_v&lt;T&gt; || std::is_member_pointer_v&lt;T&gt;;\ntemplate &lt;typename T&gt; inline constexpr bool func_or_arr = std::is_function_v&lt;T&gt; || std::is_array_v&lt;T&gt;;\n\ntemplate &lt;typename T&gt; struct primitive_type_name {using value = unk;};\n\ntemplate &lt;typename T, typename = std::enable_if_t&lt;std::is_class_v&lt;T&gt;&gt;&gt; using enable_if_class = T;\ntemplate &lt;typename T, typename = std::enable_if_t&lt;std::is_union_v&lt;T&gt;&gt;&gt; using enable_if_union = T;\ntemplate &lt;typename T, typename = std::enable_if_t&lt;std::is_enum_v &lt;T&gt;&gt;&gt; using enable_if_enum = T;\ntemplate &lt;typename T&gt; struct primitive_type_name&lt;enable_if_class&lt;T&gt;&gt; {using value = c_cla;};\ntemplate &lt;typename T&gt; struct primitive_type_name&lt;enable_if_union&lt;T&gt;&gt; {using value = c_uni;};\ntemplate &lt;typename T&gt; struct primitive_type_name&lt;enable_if_enum &lt;T&gt;&gt; {using value = c_enu;};\n\ntemplate &lt;typename T&gt; struct type_name_impl;\n\ntemplate &lt;typename T&gt; using type_name_lit = std::conditional_t&lt;std::is_same_v&lt;typename primitive_type_name&lt;T&gt;::value::template concat&lt;spa&gt;,\n typename type_name_impl&lt;T&gt;::l::template concat&lt;typename type_name_impl&lt;T&gt;::r&gt;&gt;,\n typename primitive_type_name&lt;T&gt;::value,\n typename type_name_impl&lt;T&gt;::l::template concat&lt;typename type_name_impl&lt;T&gt;::r&gt;&gt;;\ntemplate &lt;typename T&gt; inline constexpr const char *type_name = type_name_lit&lt;T&gt;::value;\n\ntemplate &lt;typename T, typename = std::enable_if_t&lt;!std::is_const_v&lt;T&gt; &amp;&amp; !std::is_volatile_v&lt;T&gt;&gt;&gt; using enable_if_no_cv = T;\n\ntemplate &lt;typename T&gt; struct type_name_impl\n{\n using l = typename primitive_type_name&lt;T&gt;::value::template concat&lt;spa&gt;;\n using r = str_lit&lt;&gt;;\n};\ntemplate &lt;typename T&gt; struct type_name_impl&lt;const T&gt;\n{\n using new_T_l = std::conditional_t&lt;type_name_impl&lt;T&gt;::l::size &amp;&amp; !ptr_or_ref&lt;T&gt;,\n spa::concat&lt;typename type_name_impl&lt;T&gt;::l&gt;,\n typename type_name_impl&lt;T&gt;::l&gt;;\n using l = std::conditional_t&lt;ptr_or_ref&lt;T&gt;,\n typename new_T_l::template concat&lt;con&gt;,\n con::concat&lt;new_T_l&gt;&gt;;\n using r = typename type_name_impl&lt;T&gt;::r;\n};\ntemplate &lt;typename T&gt; struct type_name_impl&lt;volatile T&gt;\n{\n using new_T_l = std::conditional_t&lt;type_name_impl&lt;T&gt;::l::size &amp;&amp; !ptr_or_ref&lt;T&gt;,\n spa::concat&lt;typename type_name_impl&lt;T&gt;::l&gt;,\n typename type_name_impl&lt;T&gt;::l&gt;;\n using l = std::conditional_t&lt;ptr_or_ref&lt;T&gt;,\n typename new_T_l::template concat&lt;vol&gt;,\n vol::concat&lt;new_T_l&gt;&gt;;\n using r = typename type_name_impl&lt;T&gt;::r;\n};\ntemplate &lt;typename T&gt; struct type_name_impl&lt;const volatile T&gt;\n{\n using new_T_l = std::conditional_t&lt;type_name_impl&lt;T&gt;::l::size &amp;&amp; !ptr_or_ref&lt;T&gt;,\n spa::concat&lt;typename type_name_impl&lt;T&gt;::l&gt;,\n typename type_name_impl&lt;T&gt;::l&gt;;\n using l = std::conditional_t&lt;ptr_or_ref&lt;T&gt;,\n typename new_T_l::template concat&lt;con_vol&gt;,\n con_vol::concat&lt;new_T_l&gt;&gt;;\n using r = typename type_name_impl&lt;T&gt;::r;\n};\ntemplate &lt;typename T&gt; struct type_name_impl&lt;T *&gt;\n{\n using l = std::conditional_t&lt;func_or_arr&lt;T&gt;,\n typename type_name_impl&lt;T&gt;::l::template concat&lt;lpa, ast&gt;,\n typename type_name_impl&lt;T&gt;::l::template concat&lt; ast&gt;&gt;;\n using r = std::conditional_t&lt;func_or_arr&lt;T&gt;,\n rpa::concat&lt;typename type_name_impl&lt;T&gt;::r&gt;,\n typename type_name_impl&lt;T&gt;::r&gt;;\n};\ntemplate &lt;typename T&gt; struct type_name_impl&lt;T &amp;&gt;\n{\n using l = std::conditional_t&lt;func_or_arr&lt;T&gt;,\n typename type_name_impl&lt;T&gt;::l::template concat&lt;lpa, amp&gt;,\n typename type_name_impl&lt;T&gt;::l::template concat&lt; amp&gt;&gt;;\n using r = std::conditional_t&lt;func_or_arr&lt;T&gt;,\n rpa::concat&lt;typename type_name_impl&lt;T&gt;::r&gt;,\n typename type_name_impl&lt;T&gt;::r&gt;;\n};\ntemplate &lt;typename T&gt; struct type_name_impl&lt;T &amp;&amp;&gt;\n{\n using l = std::conditional_t&lt;func_or_arr&lt;T&gt;,\n typename type_name_impl&lt;T&gt;::l::template concat&lt;lpa, amp, amp&gt;,\n typename type_name_impl&lt;T&gt;::l::template concat&lt; amp, amp&gt;&gt;;\n using r = std::conditional_t&lt;func_or_arr&lt;T&gt;,\n rpa::concat&lt;typename type_name_impl&lt;T&gt;::r&gt;,\n typename type_name_impl&lt;T&gt;::r&gt;;\n};\ntemplate &lt;typename T, typename C&gt; struct type_name_impl&lt;T C::*&gt;\n{\n using l = std::conditional_t&lt;func_or_arr&lt;T&gt;,\n typename type_name_impl&lt;T&gt;::l::template concat&lt;lpa, type_name_lit&lt;C&gt;, nsp, ast&gt;,\n typename type_name_impl&lt;T&gt;::l::template concat&lt; type_name_lit&lt;C&gt;, nsp, ast&gt;&gt;;\n using r = std::conditional_t&lt;func_or_arr&lt;T&gt;,\n rpa::concat&lt;typename type_name_impl&lt;T&gt;::r&gt;,\n typename type_name_impl&lt;T&gt;::r&gt;;\n};\ntemplate &lt;typename T&gt; struct type_name_impl&lt;enable_if_no_cv&lt;T[]&gt;&gt;\n{\n using l = typename type_name_impl&lt;T&gt;::l;\n using r = lbr::concat&lt;rbr, typename type_name_impl&lt;T&gt;::r&gt;;\n};\ntemplate &lt;typename T, std::size_t N&gt; struct type_name_impl&lt;enable_if_no_cv&lt;T[N]&gt;&gt;\n{\n using l = typename type_name_impl&lt;T&gt;::l;\n using r = lbr::concat&lt;num_to_str_lit&lt;N&gt;, rbr, typename type_name_impl&lt;T&gt;::r&gt;;\n};\ntemplate &lt;typename T&gt; struct type_name_impl&lt;T()&gt;\n{\n using l = typename type_name_impl&lt;T&gt;::l;\n using r = lpa::concat&lt;rpa, typename type_name_impl&lt;T&gt;::r&gt;;\n};\ntemplate &lt;typename T, typename P1, typename ...P&gt; struct type_name_impl&lt;T(P1, P...)&gt;\n{\n using l = typename type_name_impl&lt;T&gt;::l;\n using r = lpa::concat&lt;type_name_lit&lt;P1&gt;,\n com::concat&lt;type_name_lit&lt;P&gt;&gt;..., rpa, typename type_name_impl&lt;T&gt;::r&gt;;\n};\n\n#define TYPE_NAME(t) template &lt;&gt; struct primitive_type_name&lt;t&gt; {using value = STR_LIT(#t);};\n</code></pre>\n" }, { "answer_id": 56453627, "author": "Milo Lu", "author_id": 2846062, "author_profile": "https://Stackoverflow.com/users/2846062", "pm_score": 3, "selected": false, "text": "<p>As explained by Scott Meyers in <em>Effective Modern C++</em>,</p>\n<blockquote>\n<p>Calls to <code>std::type_info::name</code> are not guaranteed to return anything sensible.</p>\n</blockquote>\n<p>The best solution is to let the compiler generate an error message during the type deduction, for example:</p>\n<pre><code>template&lt;typename T&gt;\nclass TD;\n\nint main(){\n const int theAnswer = 32;\n auto x = theAnswer;\n auto y = &amp;theAnswer;\n TD&lt;decltype(x)&gt; xType;\n TD&lt;decltype(y)&gt; yType;\n return 0;\n}\n</code></pre>\n<p>The result will be something like this, depending on the compilers:</p>\n<pre><code>test4.cpp:10:21: error: aggregate ‘TD&lt;int&gt; xType’ has incomplete type and cannot be defined TD&lt;decltype(x)&gt; xType;\n\ntest4.cpp:11:21: error: aggregate ‘TD&lt;const int *&gt; yType’ has incomplete type and cannot be defined TD&lt;decltype(y)&gt; yType;\n</code></pre>\n<p>Hence, we get to know that <code>x</code>'s type is <code>int</code> and <code>y</code>'s type is <code>const int*</code></p>\n" }, { "answer_id": 56766138, "author": "康桓瑋", "author_id": 11638718, "author_profile": "https://Stackoverflow.com/users/11638718", "pm_score": 7, "selected": false, "text": "<p>According to <a href=\"https://stackoverflow.com/a/20170989/11638718\">Howard</a>'s solution, if you don't like the magic number, I think this is a good way to represent and it looks intuitive:</p>\n<pre><code>#include &lt;string_view&gt;\n\ntemplate &lt;typename T&gt;\nconstexpr auto type_name() {\n std::string_view name, prefix, suffix;\n#ifdef __clang__\n name = __PRETTY_FUNCTION__;\n prefix = &quot;auto type_name() [T = &quot;;\n suffix = &quot;]&quot;;\n#elif defined(__GNUC__)\n name = __PRETTY_FUNCTION__;\n prefix = &quot;constexpr auto type_name() [with T = &quot;;\n suffix = &quot;]&quot;;\n#elif defined(_MSC_VER)\n name = __FUNCSIG__;\n prefix = &quot;auto __cdecl type_name&lt;&quot;;\n suffix = &quot;&gt;(void)&quot;;\n#endif\n name.remove_prefix(prefix.size());\n name.remove_suffix(suffix.size());\n return name;\n}\n</code></pre>\n<p><a href=\"https://godbolt.org/z/Mr1ercr49\" rel=\"noreferrer\">Demo.</a></p>\n" }, { "answer_id": 58331141, "author": "Val", "author_id": 7163942, "author_profile": "https://Stackoverflow.com/users/7163942", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/a/20170989\">Howard Hinnant</a> used magic numbers to extract type name. <a href=\"https://stackoverflow.com/a/56766138\">康桓瑋</a> suggested string prefix and suffix. But prefix/suffix keep changing.\nWith “probe_type” type_name automatically calculates prefix and suffix sizes for “probe_type” to extract type name:</p>\n<pre><code>#include &lt;string_view&gt;\nusing namespace std;\n\nnamespace typeName {\n template &lt;typename T&gt;\n constexpr string_view wrapped_type_name () {\n#ifdef __clang__\n return __PRETTY_FUNCTION__;\n#elif defined(__GNUC__)\n return __PRETTY_FUNCTION__;\n#elif defined(_MSC_VER)\n return __FUNCSIG__;\n#endif\n }\n\n class probe_type;\n constexpr string_view probe_type_name (&quot;typeName::probe_type&quot;);\n constexpr string_view probe_type_name_elaborated (&quot;class typeName::probe_type&quot;);\n constexpr string_view probe_type_name_used (wrapped_type_name&lt;probe_type&gt; ().find (probe_type_name_elaborated) != -1 ? probe_type_name_elaborated : probe_type_name);\n\n constexpr size_t prefix_size () {\n return wrapped_type_name&lt;probe_type&gt; ().find (probe_type_name_used);\n }\n\n constexpr size_t suffix_size () {\n return wrapped_type_name&lt;probe_type&gt; ().length () - prefix_size () - probe_type_name_used.length ();\n }\n\n template &lt;typename T&gt;\n string_view type_name () {\n constexpr auto type_name = wrapped_type_name&lt;T&gt; ();\n\n return type_name.substr (prefix_size (), type_name.length () - prefix_size () - suffix_size ());\n }\n}\n\n#include &lt;iostream&gt;\n\nusing typeName::type_name;\nusing typeName::probe_type;\n\nclass test;\n\nint main () {\n cout &lt;&lt; type_name&lt;class test&gt; () &lt;&lt; endl;\n\n cout &lt;&lt; type_name&lt;const int*&amp;&gt; () &lt;&lt; endl;\n cout &lt;&lt; type_name&lt;unsigned int&gt; () &lt;&lt; endl;\n\n const int ic = 42;\n const int* pic = &amp;ic;\n const int*&amp; rpic = pic;\n cout &lt;&lt; type_name&lt;decltype(ic)&gt; () &lt;&lt; endl;\n cout &lt;&lt; type_name&lt;decltype(pic)&gt; () &lt;&lt; endl;\n cout &lt;&lt; type_name&lt;decltype(rpic)&gt; () &lt;&lt; endl;\n\n cout &lt;&lt; type_name&lt;probe_type&gt; () &lt;&lt; endl;\n}\n</code></pre>\n<p>Output</p>\n<p><a href=\"https://godbolt.org\" rel=\"noreferrer\">gcc 10.2</a>:</p>\n<pre><code>test\nconst int *&amp;\nunsigned int\nconst int\nconst int *\nconst int *&amp;\ntypeName::probe_type\n</code></pre>\n<p><a href=\"https://godbolt.org\" rel=\"noreferrer\">clang 11.0.0</a>:</p>\n<pre><code>test\nconst int *&amp;\nunsigned int\nconst int\nconst int *\nconst int *&amp;\ntypeName::probe_type\n</code></pre>\n<p>VS 2019 version 16.7.6:</p>\n<pre><code>class test\nconst int*&amp;\nunsigned int\nconst int\nconst int*\nconst int*&amp;\nclass typeName::probe_type\n</code></pre>\n" }, { "answer_id": 61344776, "author": "Lars Melchior", "author_id": 2397086, "author_profile": "https://Stackoverflow.com/users/2397086", "pm_score": 2, "selected": false, "text": "<p>For anyone still visiting, I've recently had the same issue and decided to write a small library based on answers from this post. It provides constexpr type names and type indices und is is tested on Mac, Windows and Ubuntu.</p>\n\n<p>The library code is here: <a href=\"https://github.com/TheLartians/StaticTypeInfo\" rel=\"nofollow noreferrer\">https://github.com/TheLartians/StaticTypeInfo</a></p>\n" }, { "answer_id": 64490578, "author": "einpoklum", "author_id": 1593077, "author_profile": "https://Stackoverflow.com/users/1593077", "pm_score": 4, "selected": false, "text": "<p><sub>Another take on <a href=\"https://stackoverflow.com/a/56766138\">@康桓瑋's answer</a> (originally ), making less assumptions about the prefix and suffix specifics, and inspired by <a href=\"https://stackoverflow.com/a/58331141/1593077\">@Val's answer</a> - but without polluting the global namespace; without any conditions; and hopefully easier to read.</sub></p>\n<p>The popular compilers provide a macro with the current function's signature. Now, functions are templatable; so the signature contains the template arguments. So, the basic approach is: Given a type, be in a function with that type as a template argument.</p>\n<p>Unfortunately, the type name is wrapped in text describing the function, which is different between compilers. For example, with GCC, the signature of <code>template &lt;typename T&gt; int foo()</code> with type <code>double</code> is: <code>int foo() [T = double]</code>.</p>\n<p>So, how do you get rid of the wrapper text? @HowardHinnant's solution is the shortest and most &quot;direct&quot;: Just use per-compiler magic numbers to remove a prefix and a suffix. But obviously, that's very brittle; and nobody likes magic numbers in their code. It turns out, however, that given the macro value for a type with a known name, you can determine what prefix and suffix constitute the wrapping.</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>#include &lt;string_view&gt;\n\ntemplate &lt;typename T&gt; constexpr std::string_view type_name();\n\ntemplate &lt;&gt;\nconstexpr std::string_view type_name&lt;void&gt;()\n{ return &quot;void&quot;; }\n\nnamespace detail {\n\nusing type_name_prober = void;\n\ntemplate &lt;typename T&gt;\nconstexpr std::string_view wrapped_type_name() \n{\n#ifdef __clang__\n return __PRETTY_FUNCTION__;\n#elif defined(__GNUC__)\n return __PRETTY_FUNCTION__;\n#elif defined(_MSC_VER)\n return __FUNCSIG__;\n#else\n#error &quot;Unsupported compiler&quot;\n#endif\n}\n\nconstexpr std::size_t wrapped_type_name_prefix_length() { \n return wrapped_type_name&lt;type_name_prober&gt;().find(type_name&lt;type_name_prober&gt;()); \n}\n\nconstexpr std::size_t wrapped_type_name_suffix_length() { \n return wrapped_type_name&lt;type_name_prober&gt;().length() \n - wrapped_type_name_prefix_length() \n - type_name&lt;type_name_prober&gt;().length();\n}\n\n} // namespace detail\n\ntemplate &lt;typename T&gt;\nconstexpr std::string_view type_name() {\n constexpr auto wrapped_name = detail::wrapped_type_name&lt;T&gt;();\n constexpr auto prefix_length = detail::wrapped_type_name_prefix_length();\n constexpr auto suffix_length = detail::wrapped_type_name_suffix_length();\n constexpr auto type_name_length = wrapped_name.length() - prefix_length - suffix_length;\n return wrapped_name.substr(prefix_length, type_name_length);\n}\n</code></pre>\n<p>See it on <a href=\"https://godbolt.org/z/3ac5f5\" rel=\"noreferrer\"><kbd>GodBolt</kbd></a>. This should be working with MSVC as well.</p>\n" }, { "answer_id": 64717914, "author": "CourageousPotato", "author_id": 11502722, "author_profile": "https://Stackoverflow.com/users/11502722", "pm_score": 1, "selected": false, "text": "<p>Copying from this answer: <a href=\"https://stackoverflow.com/a/56766138/11502722\">https://stackoverflow.com/a/56766138/11502722</a></p>\n<p>I was able to get this <em>somewhat</em> working for C++ <code>static_assert()</code>. The wrinkle here is that <code>static_assert()</code> only accepts string literals; <code>constexpr string_view</code> will not work. You will need to accept extra text around the typename, but it works:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>template&lt;typename T&gt;\nconstexpr void assertIfTestFailed()\n{\n#ifdef __clang__\n static_assert(testFn&lt;T&gt;(), &quot;Test failed on this used type: &quot; __PRETTY_FUNCTION__);\n#elif defined(__GNUC__)\n static_assert(testFn&lt;T&gt;(), &quot;Test failed on this used type: &quot; __PRETTY_FUNCTION__);\n#elif defined(_MSC_VER)\n static_assert(testFn&lt;T&gt;(), &quot;Test failed on this used type: &quot; __FUNCSIG__);\n#else\n static_assert(testFn&lt;T&gt;(), &quot;Test failed on this used type (see surrounding logged error for details).&quot;);\n#endif\n }\n}\n</code></pre>\n<p>MSVC Output:</p>\n<pre><code>error C2338: Test failed on this used type: void __cdecl assertIfTestFailed&lt;class BadType&gt;(void)\n... continued trace of where the erroring code came from ...\n</code></pre>\n" }, { "answer_id": 67562646, "author": "Chris Uzdavinis", "author_id": 8309701, "author_profile": "https://Stackoverflow.com/users/8309701", "pm_score": 2, "selected": false, "text": "<p>For something different, here's a &quot;To English&quot; conversion of the type, deconstructing every qualifier, extent, argument, and so on, recursively building the string describing the type I think the &quot;deduced this&quot; proposal would help cut down many of the specializations. In any case, this was a fun morning exercise, regardless of excessive bloat. :)</p>\n<pre><code>struct X {\n using T = int *((*)[10]);\n T f(T, const unsigned long long * volatile * );\n};\n\nint main() {\n\n std::cout &lt;&lt; describe&lt;decltype(&amp;X::f)&gt;() &lt;&lt; std::endl;\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>pointer to member function of class 1X taking (pointer to array[10]\nof pointer to int, pointer to volatile pointer to const unsigned \nlong long), and returning pointer to array[10] of pointer to int\n</code></pre>\n<p>Here's the code:\n<a href=\"https://godbolt.org/z/7jKK4or43\" rel=\"nofollow noreferrer\">https://godbolt.org/z/7jKK4or43</a></p>\n<p><strong>Note</strong>: most current version is in my github: <a href=\"https://github.com/cuzdav/type_to_string\" rel=\"nofollow noreferrer\">https://github.com/cuzdav/type_to_string</a></p>\n<pre class=\"lang-cpp prettyprint-override\"><code>// Print types as strings, including functions, member \n\n#include &lt;type_traits&gt;\n#include &lt;typeinfo&gt;\n#include &lt;string&gt;\n#include &lt;utility&gt;\n\nnamespace detail {\n\ntemplate &lt;typename T&gt; struct Describe;\n\ntemplate &lt;typename T, class ClassT&gt; \nstruct Describe&lt;T (ClassT::*)&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ArgsT...)&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...)&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...) const&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...) volatile&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...) noexcept&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...) const volatile&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...) const noexcept&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...) volatile noexcept&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...) const volatile noexcept&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...)&amp;&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...) const &amp;&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...) volatile &amp;&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...) &amp; noexcept&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...) const volatile &amp;&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...) const &amp; noexcept&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...) volatile &amp; noexcept&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...) const volatile &amp; noexcept&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...) &amp;&amp;&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...) const &amp;&amp;&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...) volatile &amp;&amp;&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...) &amp;&amp; noexcept&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...) const volatile &amp;&amp;&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...) const &amp;&amp; noexcept&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...) volatile &amp;&amp; noexcept&gt; {\n static std::string describe();\n};\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstruct Describe&lt;RetT(ClassT::*)(ArgsT...) const volatile &amp;&amp; noexcept&gt; {\n static std::string describe();\n};\n\ntemplate &lt;typename T&gt;\nstd::string describe()\n{\n using namespace std::string_literals;\n auto terminal = [&amp;](char const * desc) {\n return desc + &quot; &quot;s + typeid(T).name();\n };\n if constexpr(std::is_const_v&lt;T&gt;) {\n return &quot;const &quot; + describe&lt;std::remove_const_t&lt;T&gt;&gt;();\n }\n else if constexpr(std::is_volatile_v&lt;T&gt;) {\n return &quot;volatile &quot; + describe&lt;std::remove_volatile_t&lt;T&gt;&gt;();\n }\n else if constexpr (std::is_same_v&lt;bool, T&gt;) {\n return &quot;bool&quot;;\n }\n else if constexpr(std::is_same_v&lt;char, T&gt;) {\n return &quot;char&quot;;\n }\n else if constexpr(std::is_same_v&lt;signed char, T&gt;) {\n return &quot;signed char&quot;;\n }\n else if constexpr(std::is_same_v&lt;unsigned char, T&gt;) {\n return &quot;unsigned char&quot;;\n }\n else if constexpr(std::is_unsigned_v&lt;T&gt;) {\n return &quot;unsigned &quot; + describe&lt;std::make_signed_t&lt;T&gt;&gt;();\n }\n else if constexpr(std::is_void_v&lt;T&gt;) {\n return &quot;void&quot;;\n }\n else if constexpr(std::is_integral_v&lt;T&gt;) {\n if constexpr(std::is_same_v&lt;short, T&gt;) \n return &quot;short&quot;;\n else if constexpr(std::is_same_v&lt;int, T&gt;) \n return &quot;int&quot;;\n else if constexpr(std::is_same_v&lt;long, T&gt;) \n return &quot;long&quot;;\n else if constexpr(std::is_same_v&lt;long long, T&gt;) \n return &quot;long long&quot;;\n }\n else if constexpr(std::is_same_v&lt;float, T&gt;) {\n return &quot;float&quot;;\n }\n else if constexpr(std::is_same_v&lt;double, T&gt;) {\n return &quot;double&quot;;\n }\n else if constexpr(std::is_same_v&lt;long double, T&gt;) {\n return &quot;long double&quot;;\n }\n else if constexpr(std::is_same_v&lt;std::nullptr_t, T&gt;) { \n return &quot;nullptr_t&quot;;\n }\n else if constexpr(std::is_class_v&lt;T&gt;) {\n return terminal(&quot;class&quot;);\n }\n else if constexpr(std::is_union_v&lt;T&gt;) {\n return terminal(&quot;union&quot;);\n }\n else if constexpr(std::is_enum_v&lt;T&gt;) {\n std::string result;\n if (!std::is_convertible_v&lt;T, std::underlying_type_t&lt;T&gt;&gt;) {\n result += &quot;scoped &quot;;\n }\n return result + terminal(&quot;enum&quot;);\n } \n else if constexpr(std::is_pointer_v&lt;T&gt;) {\n return &quot;pointer to &quot; + describe&lt;std::remove_pointer_t&lt;T&gt;&gt;();\n }\n else if constexpr(std::is_lvalue_reference_v&lt;T&gt;) {\n return &quot;lvalue-ref to &quot; + describe&lt;std::remove_reference_t&lt;T&gt;&gt;();\n }\n else if constexpr(std::is_rvalue_reference_v&lt;T&gt;) {\n return &quot;rvalue-ref to &quot; + describe&lt;std::remove_reference_t&lt;T&gt;&gt;();\n }\n else if constexpr(std::is_bounded_array_v&lt;T&gt;) {\n return &quot;array[&quot; + std::to_string(std::extent_v&lt;T&gt;) + &quot;] of &quot; +\n describe&lt;std::remove_extent_t&lt;T&gt;&gt;();\n }\n else if constexpr(std::is_unbounded_array_v&lt;T&gt;) {\n return &quot;array[] of &quot; + describe&lt;std::remove_extent_t&lt;T&gt;&gt;();\n }\n else if constexpr(std::is_function_v&lt;T&gt;) {\n return Describe&lt;T&gt;::describe();\n }\n else if constexpr(std::is_member_object_pointer_v&lt;T&gt;) {\n return Describe&lt;T&gt;::describe();\n }\n else if constexpr(std::is_member_function_pointer_v&lt;T&gt;) {\n return Describe&lt;T&gt;::describe();\n }\n}\n\ntemplate &lt;typename RetT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ArgsT...)&gt;::describe() {\n std::string result = &quot;function taking (&quot;;\n ((result += detail::describe&lt;ArgsT&gt;(&quot;, &quot;)), ...);\n return result + &quot;), returning &quot; + detail::describe&lt;RetT&gt;();\n}\n\ntemplate &lt;typename T, class ClassT&gt; \nstd::string Describe&lt;T (ClassT::*)&gt;::describe() {\n return &quot;pointer to member of &quot; + detail::describe&lt;ClassT&gt;() +\n &quot; of type &quot; + detail::describe&lt;T&gt;();\n}\n\nstruct Comma {\n char const * sep = &quot;&quot;;\n std::string operator()(std::string const&amp; str) {\n return std::exchange(sep, &quot;, &quot;) + str;\n }\n};\nenum Qualifiers {NONE=0, CONST=1, VOLATILE=2, NOEXCEPT=4, LVREF=8, RVREF=16};\n\ntemplate &lt;typename RetT, typename ClassT, typename... ArgsT&gt;\nstd::string describeMemberPointer(Qualifiers q) {\n std::string result = &quot;pointer to &quot;;\n if (NONE != (q &amp; CONST)) result += &quot;const &quot;;\n if (NONE != (q &amp; VOLATILE)) result += &quot;volatile &quot;;\n if (NONE != (q &amp; NOEXCEPT)) result += &quot;noexcept &quot;;\n if (NONE != (q &amp; LVREF)) result += &quot;lvalue-ref &quot;;\n if (NONE != (q &amp; RVREF)) result += &quot;rvalue-ref &quot;;\n result += &quot;member function of &quot; + detail::describe&lt;ClassT&gt;() + &quot; taking (&quot;;\n Comma comma;\n ((result += comma(detail::describe&lt;ArgsT&gt;())), ...);\n return result + &quot;), and returning &quot; + detail::describe&lt;RetT&gt;();\n}\n\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...)&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(NONE);\n}\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...) const&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(CONST);\n}\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...) noexcept&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(NOEXCEPT);\n}\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...) volatile&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(VOLATILE);\n}\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...) volatile noexcept&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(VOLATILE | NOEXCEPT);\n}\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...) const volatile&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(CONST | VOLATILE);\n}\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...) const noexcept&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(CONST | NOEXCEPT);\n}\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...) const volatile noexcept&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(CONST | VOLATILE | NOEXCEPT);\n}\n\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...) &amp;&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(LVREF);\n}\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...) const &amp;&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(LVREF | CONST);\n}\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...) &amp; noexcept&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(LVREF | NOEXCEPT);\n}\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...) volatile &amp;&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(LVREF | VOLATILE);\n}\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...) volatile &amp; noexcept&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(LVREF | VOLATILE | NOEXCEPT);\n}\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...) const volatile &amp;&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(LVREF | CONST | VOLATILE);\n}\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...) const &amp; noexcept&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(LVREF | CONST | NOEXCEPT);\n}\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...) const volatile &amp; noexcept&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(LVREF | CONST | VOLATILE | NOEXCEPT);\n}\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...)&amp;&amp;&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(RVREF);\n}\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...) const &amp;&amp;&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(RVREF | CONST);\n}\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...) &amp;&amp; noexcept&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(RVREF | NOEXCEPT);\n}\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...) volatile &amp;&amp;&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(RVREF | VOLATILE);\n}\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...) volatile &amp;&amp; noexcept&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(RVREF | VOLATILE | NOEXCEPT);\n}\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...) const volatile &amp;&amp;&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(RVREF | CONST | VOLATILE);\n}\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...) const &amp;&amp; noexcept&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(RVREF | CONST | NOEXCEPT);\n}\ntemplate &lt;typename RetT, class ClassT, typename... ArgsT&gt; \nstd::string Describe&lt;RetT(ClassT::*)(ArgsT...) const volatile &amp;&amp; noexcept&gt;::describe() {\n return describeMemberPointer&lt;RetT, ClassT, ArgsT...&gt;(RVREF | CONST | VOLATILE | NOEXCEPT);\n}\n\n} // detail\n\n///////////////////////////////////\n// Main function\n///////////////////////////////////\ntemplate &lt;typename T&gt;\nstd::string describe() {\n return detail::describe&lt;T&gt;();\n}\n\n\n///////////////////////////////////\n// Sample code\n///////////////////////////////////\n#include &lt;iostream&gt;\n\n\nstruct X {\n using T = int *((*)[10]);\n T f(T, const unsigned long long * volatile * );\n};\n\nint main() {\n std::cout &lt;&lt; describe&lt;decltype(&amp;X::f)&gt;() &lt;&lt; std::endl;\n}\n\n</code></pre>\n" }, { "answer_id": 70839988, "author": "Jonas", "author_id": 2378300, "author_profile": "https://Stackoverflow.com/users/2378300", "pm_score": 1, "selected": false, "text": "<p>Building on a number of the previous answers, I made this solution which does not store the result of <code>__PRETTY_FUNCTION__</code> in the binary. It uses a static array to hold the string representation of the type name.</p>\n<p>It requires C++23.</p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string_view&gt;\n#include &lt;array&gt;\n\ntemplate &lt;typename T&gt;\nconstexpr auto type_name() {\n auto gen = [] &lt;class R&gt; () constexpr -&gt; std::string_view {\n return __PRETTY_FUNCTION__;\n };\n constexpr std::string_view search_type = &quot;float&quot;;\n constexpr auto search_type_string = gen.template operator()&lt;float&gt;();\n constexpr auto prefix = search_type_string.find(search_type);\n constexpr auto suffix = search_type_string.size() - prefix - search_type.size();\n constexpr auto str = gen.template operator()&lt;T&gt;();\n constexpr int size = str.size() - prefix - suffix;\n constexpr auto static arr = [&amp;]&lt;std::size_t... I&gt;(std::index_sequence&lt;I...&gt;) constexpr {\n return std::array&lt;char, size&gt;{str[prefix + I]...};\n } (std::make_index_sequence&lt;size&gt;{});\n\n return std::string_view(arr.data(), size);\n}\n</code></pre>\n" }, { "answer_id": 72650356, "author": "Haseeb Mir", "author_id": 6219626, "author_profile": "https://Stackoverflow.com/users/6219626", "pm_score": 1, "selected": false, "text": "<p>C++ Data type resolve in Compile-Time using Template and Runtime using TypeId.</p>\n<p>Compile time solution.</p>\n<pre><code>template &lt;std::size_t...Idxs&gt;\nconstexpr auto substring_as_array(std::string_view str, std::index_sequence&lt;Idxs...&gt;)\n{\n return std::array{str[Idxs]..., '\\n'};\n}\n\ntemplate &lt;typename T&gt;\nconstexpr auto type_name_array()\n{\n#if defined(__clang__)\n constexpr auto prefix = std::string_view{&quot;[T = &quot;};\n constexpr auto suffix = std::string_view{&quot;]&quot;};\n constexpr auto function = std::string_view{__PRETTY_FUNCTION__};\n#elif defined(__GNUC__)\n constexpr auto prefix = std::string_view{&quot;with T = &quot;};\n constexpr auto suffix = std::string_view{&quot;]&quot;};\n constexpr auto function = std::string_view{__PRETTY_FUNCTION__};\n#elif defined(_MSC_VER)\n constexpr auto prefix = std::string_view{&quot;type_name_array&lt;&quot;};\n constexpr auto suffix = std::string_view{&quot;&gt;(void)&quot;};\n constexpr auto function = std::string_view{__FUNCSIG__};\n#else\n# error Unsupported compiler\n#endif\n\n constexpr auto start = function.find(prefix) + prefix.size();\n constexpr auto end = function.rfind(suffix);\n\n static_assert(start &lt; end);\n\n constexpr auto name = function.substr(start, (end - start));\n return substring_as_array(name, std::make_index_sequence&lt;name.size()&gt;{});\n}\n\ntemplate &lt;typename T&gt;\nstruct type_name_holder {\n static inline constexpr auto value = type_name_array&lt;T&gt;();\n};\n\ntemplate &lt;typename T&gt;\nconstexpr auto type_name() -&gt; std::string_view\n{\n constexpr auto&amp; value = type_name_holder&lt;T&gt;::value;\n return std::string_view{value.data(), value.size()};\n}\n</code></pre>\n<p>Runtime solution.</p>\n<pre><code>template &lt;typename T&gt;\nvoid PrintDataType(T type)\n{\n auto name = typeid(type).name();\n string cmd_str = &quot;echo '&quot; + string(name) + &quot;' | c++filt -t&quot;;\n system(cmd_str.c_str());\n}\n</code></pre>\n<p>Main Code</p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;map&gt;\n#include &lt;string&gt;\n#include &lt;typeinfo&gt;\n#include &lt;string_view&gt;\n#include &lt;array&gt; // std::array\n#include &lt;utility&gt; // std::index_sequence\nusing std::string;\n</code></pre>\n<blockquote>\n<pre><code>int main()\n{\n //Dynamic resolution.\n std::map&lt;int, int&gt; iMap;\n PrintDataType(iMap);\n \n //Compile type resolution.\n std::cout &lt;&lt; type_name&lt;std::list&lt;int&gt;&gt;() &lt;&lt; std::endl;\n\n return 0;\n}\n</code></pre>\n</blockquote>\n<p><a href=\"https://gist.github.com/haseeb-heaven/d6093f68d160b92ba1c69ccd9df7ec80\" rel=\"nofollow noreferrer\">Code Snippet</a></p>\n" }, { "answer_id": 73058336, "author": "CPP_is_no_STANDARD", "author_id": 18032104, "author_profile": "https://Stackoverflow.com/users/18032104", "pm_score": -1, "selected": false, "text": "<p>Consider this code:</p>\n<pre><code>#include &lt;iostream&gt;\n\nint main()\n{\n int a = 2; // Declare type &quot;int&quot;\n std::string b = &quot;Hi&quot;; // Declare type &quot;string&quot;\n long double c = 3438; // Declare type &quot;long double&quot;\n if(typeid(a) == typeid(int))\n {\n std::cout&lt;&lt;&quot;int\\n&quot;;\n }\n\n if(typeid(b) == typeid(std::string))\n {\n std::cout&lt;&lt;&quot;string\\n&quot;;\n }\n \n if(typeid(c) == typeid(long double))\n {\n std::cout&lt;&lt;&quot;long double&quot;;\n }\n return 0;\n}\n</code></pre>\n<p>I believe you want the whole word (rather than only printing the short form of <code>int</code> (which is <code>i</code>), you want <code>int</code>), that is why I did the <code>if</code>.</p>\n<p>For some of the variables (<code>string</code>,<code>long double</code> etc... which do not print the expected result comparing their short forms), you need to compare the result of applying the <code>typeid</code> operator with the <code>typeid</code> of a specific type.</p>\n<p>From cppreference:</p>\n<blockquote>\n<p>Returns an implementation defined null-terminated character string containing the name of the type. No guarantees are given; in particular, the returned string can be identical for several types and change between invocations of the same program.</p>\n</blockquote>\n<hr>\n<p>IMO, Python is better than C++ in this case. Python has built-in <code>type</code> function to directly access the data type of the variable.</p>\n" } ]
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>\n" }, { "answer_id": 1052918, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>take a look at <strong><a href=\"http://en.wikipedia.org/wiki/Mime_type\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Mime_type</a></strong></p>\n\n<p>There it says you should use application/javascript instead of text/javascript.</p>\n" } ]
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 function</a> can display the elapsed minutes. The if statement for the 12/31/9999 check I'll leave as an excercise for the reader ;-)</p>\n" }, { "answer_id": 81981, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>--you can play with the datediff using mi for minutes</p>\n\n<p>-- this give you second of each task</p>\n\n<pre><code>select Start, \n Stop, \n CASE \n WHEN Stop = '9999-12-31' THEN datediff(ss, start,getdate())\n ELSE datediff(ss, start,stop) \n END duration_in_seconds \n\nfrom mytable\n</code></pre>\n\n<p>-- sum</p>\n\n<pre><code>Select Sum(duration_in_seconds)\nfrom \n(\nselect Start, \n Stop, \n CASE \n WHEN Stop = '9999-12-31' THEN datediff(ss, start,getdate())\n ELSE datediff(ss, start,stop) \n END duration_in_seconds \n\nfrom mytable)x\n</code></pre>\n" }, { "answer_id": 81983, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 0, "selected": false, "text": "<p>Datediff becomes more difficult to use as you have more dateparts in your difference (i.e. in your case, looks like minutes and seconds; occasionally hours). Fortunately, in most variations of TSQL, you can simply perform math on the dates. Assuming this is a date field, you can probably just query:</p>\n\n<p>select duration = stop - start</p>\n\n<p>For a practical example, let's select the difference between two datetimes without bothering with a table:</p>\n\n<p>select convert(datetime,'2008-09-17 04:56:45.030') - convert(datetime,'2008-09-17 04:53:05.920')</p>\n\n<p>which returns \"1900-01-01 00:03:39.110\", indicating there are zero years/months/days; 3 mins, 39.11 seconds between these two datetimes. From there, your code can TimeSpan.Parse this value.</p>\n" }, { "answer_id": 82039, "author": "Nerdfest", "author_id": 7855, "author_profile": "https://Stackoverflow.com/users/7855", "pm_score": 2, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>Select Sum(\n DateDiff(\n Minute,\n IsNull((Select Start where Start != '9999.12.31'), GetDate()),\n IsNull((Select End where End != '9999.12.31'), GetDate())\n )\n)\nfrom *tableName*\n</code></pre>\n" }, { "answer_id": 82100, "author": "Martynnw", "author_id": 5466, "author_profile": "https://Stackoverflow.com/users/5466", "pm_score": 1, "selected": false, "text": "<p>The following will work for SQL Server, other databases use different functions for date calculation and getting the current time.</p>\n\n<pre><code>Select Case When (Stop &lt;&gt; '31 Dec 9999') Then \n DateDiff(mi, Start, Stop) \n Else \n DateDiff(mi, Start, GetDate()) \n End\nFrom ATable\n</code></pre>\n" }, { "answer_id": 83005, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 5, "selected": true, "text": "<pre><code>SELECT SUM( CASE WHEN Stop = '31 dec 9999' \n THEN DateDiff(mi, Start, Stop)\n ELSE DateDiff(mi, Start, GetDate())\n END ) AS TotalMinutes \nFROM task\n</code></pre>\n\n<p>However, a better solution would be to make the <code>Stop field nullable, and make it null when the task is still running. That way, you could do this: </p>\n\n<pre>SELECT SUM( DateDiff( mi, Start, IsNull(Stop, GetDate() ) ) AS TotalMinutes \nFROM task\n</code></pre>\n" }, { "answer_id": 86813, "author": "mattruma", "author_id": 1768, "author_profile": "https://Stackoverflow.com/users/1768", "pm_score": 0, "selected": false, "text": "<p>Using help from AJ's <a href=\"https://stackoverflow.com/questions/81905/transact-sql-to-sum-up-elapsed-time#83005\">answer</a>, BelowNinety's <a href=\"https://stackoverflow.com/questions/81905/transact-sql-to-sum-up-elapsed-time#82039\">answer</a> and Nerdfest's <a href=\"https://stackoverflow.com/questions/81905/transact-sql-to-sum-up-elapsed-time#82039\">answer</a>, I came up with the following:</p>\n\n<pre><code>Select Sum(\n Case When End = '12/31/9999 12:00:00 AM' Then\n DateDiff(mi, Start, Getdate()) \n Else \n DateDiff(mi, Start, End) \n End) As ElapsedTime \nFrom Table\n</code></pre>\n\n<p>Thanks for the help!</p>\n" }, { "answer_id": 136859, "author": "GilM", "author_id": 10192, "author_profile": "https://Stackoverflow.com/users/10192", "pm_score": 2, "selected": false, "text": "<p>I think this is cleaner:</p>\n\n<pre><code> SELECT SUM(\n DATEDIFF(mi, Start, ISNULL(NULLIF(Stop,'99991231'), GetDate()))\n ) AS ElapsedTime\n FROM Table\n</code></pre>\n" } ]
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://output stream.</p>\n\n<pre><code>$result = $db_con-&gt;query('SELECT * FROM `some_table`');\n$fp = fopen('php://output', 'w');\nif ($fp &amp;&amp; $result) {\n header('Content-Type: text/csv');\n header('Content-Disposition: attachment; filename=\"export.csv\"');\n while ($row = $result-&gt;fetch_array(MYSQLI_NUM)) {\n fputcsv($fp, array_values($row));\n }\n die;\n}\n</code></pre>\n" }, { "answer_id": 82016, "author": "Lasar", "author_id": 9438, "author_profile": "https://Stackoverflow.com/users/9438", "pm_score": 2, "selected": false, "text": "<p>If you have FTP/SFTP access you could just go ahead and upload phpMyAdmin yourself.</p>\n\n<p>I'm using this little package to make automated mysql backups from a server I only have FTP access to:<br>\n<a href=\"http://www.taw24.de/download/pafiledb.php?PHPSESSID=b48001ea004aacd86f5643a72feb2829&amp;action=viewfile&amp;fid=43&amp;id=1\" rel=\"nofollow noreferrer\">http://www.taw24.de/download/pafiledb.php?PHPSESSID=b48001ea004aacd86f5643a72feb2829&amp;action=viewfile&amp;fid=43&amp;id=1</a><br>\nThe site is in german but the download has some english documentation as well.</p>\n\n<p>A quick google also turns up this, but I have not used it myself:<br>\n<a href=\"http://snipplr.com/view/173/mysql-dump/\" rel=\"nofollow noreferrer\">http://snipplr.com/view/173/mysql-dump/</a></p>\n" }, { "answer_id": 82119, "author": "lewis", "author_id": 14442, "author_profile": "https://Stackoverflow.com/users/14442", "pm_score": 6, "selected": true, "text": "<p>You could use SQL for this:</p>\n\n<pre><code>$file = 'backups/mytable.sql';\n$result = mysql_query(\"SELECT * INTO OUTFILE '$file' FROM `##table##`\");\n</code></pre>\n\n<p>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.</p>\n\n<p>To get it back in to your DataBase from that file you can use:</p>\n\n<pre><code>$file = 'backups/mytable.sql';\n$result = mysql_query(\"LOAD DATA INFILE '$file' INTO TABLE `##table##`\");\n</code></pre>\n\n<p>The other option is to use PHP to invoke a system command on the server and run 'mysqldump':</p>\n\n<pre><code>$file = 'backups/mytable.sql';\nsystem(\"mysqldump --opt -h ##databaseserver## -u ##username## -p ##password## ##database | gzip &gt; \".$file);\n</code></pre>\n" }, { "answer_id": 84981, "author": "SeanDowney", "author_id": 5261, "author_profile": "https://Stackoverflow.com/users/5261", "pm_score": -1, "selected": false, "text": "<p>I use mysqldump via the command line :</p>\n\n<pre><code>exec(\"mysqldump sourceDatabase -uUsername -p'password' &gt; outputFilename.sql\");\n</code></pre>\n\n<p>Then you just download the resulting file and your done.</p>\n" }, { "answer_id": 85332, "author": "DreamWerx", "author_id": 15487, "author_profile": "https://Stackoverflow.com/users/15487", "pm_score": 2, "selected": false, "text": "<p>You might consider looking at: <a href=\"http://www.webyog.com\" rel=\"nofollow noreferrer\">http://www.webyog.com</a>\nThis is a great GUI admin tool, and they have a really neat HTTP-Tunneling feature (I'm not sure if this is only in enterprise which costs a few bucks). </p>\n\n<p>Basically you upload a script they provide into your webspace (php script) and point sqlyog manager to it and you can access the database(s). It uses this script to tunnel/proxy the requests/queries between your home client and the server.</p>\n\n<p>I know at least 1 person who uses this method with great results.</p>\n" }, { "answer_id": 97208, "author": "Shinhan", "author_id": 18219, "author_profile": "https://Stackoverflow.com/users/18219", "pm_score": 4, "selected": false, "text": "<p>You should also consider <a href=\"http://phpminadmin.sourceforge.net/\" rel=\"noreferrer\">phpMinAdmin</a> which is only one file, so its easy to upload and setup.</p>\n" }, { "answer_id": 30223691, "author": "T.Todua", "author_id": 2377343, "author_profile": "https://Stackoverflow.com/users/2377343", "pm_score": 3, "selected": false, "text": "<p><strong>WORKING SOLUTION</strong> (latest version at:\n<a href=\"https://github.com/tazotodua/useful-php-scripts/blob/master/export-mysql-database-sql-backup.php\" rel=\"noreferrer\"><strong>Export.php</strong></a> + <a href=\"https://github.com/tazotodua/useful-php-scripts/blob/master/import-sql-database-mysql.php\" rel=\"noreferrer\"><strong>Import.php</strong></a> )</p>\n\n<pre><code>EXPORT_TABLES(\"localhost\",\"user\",\"pass\",\"db_name\");\n</code></pre>\n\n<p>CODE:</p>\n\n<pre><code>//https://github.com/tazotodua/useful-php-scripts\nfunction EXPORT_TABLES($host,$user,$pass,$name, $tables=false, $backup_name=false ){\n $mysqli = new mysqli($host,$user,$pass,$name); $mysqli-&gt;select_db($name); $mysqli-&gt;query(\"SET NAMES 'utf8'\");\n $queryTables = $mysqli-&gt;query('SHOW TABLES'); while($row = $queryTables-&gt;fetch_row()) { $target_tables[] = $row[0]; } if($tables !== false) { $target_tables = array_intersect( $target_tables, $tables); }\n foreach($target_tables as $table){\n $result = $mysqli-&gt;query('SELECT * FROM '.$table); $fields_amount=$result-&gt;field_count; $rows_num=$mysqli-&gt;affected_rows; $res = $mysqli-&gt;query('SHOW CREATE TABLE '.$table); $TableMLine=$res-&gt;fetch_row();\n $content = (!isset($content) ? '' : $content) . \"\\n\\n\".$TableMLine[1].\";\\n\\n\";\n for ($i = 0, $st_counter = 0; $i &lt; $fields_amount; $i++, $st_counter=0) {\n while($row = $result-&gt;fetch_row()) { //when started (and every after 100 command cycle):\n if ($st_counter%100 == 0 || $st_counter == 0 ) {$content .= \"\\nINSERT INTO \".$table.\" VALUES\";}\n $content .= \"\\n(\";\n for($j=0; $j&lt;$fields_amount; $j++) { $row[$j] = str_replace(\"\\n\",\"\\\\n\", addslashes($row[$j]) ); if (isset($row[$j])){$content .= '\"'.$row[$j].'\"' ; }else {$content .= '\"\"';} if ($j&lt;($fields_amount-1)){$content.= ',';} }\n $content .=\")\";\n //every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler\n if ( (($st_counter+1)%100==0 &amp;&amp; $st_counter!=0) || $st_counter+1==$rows_num) {$content .= \";\";} else {$content .= \",\";} $st_counter=$st_counter+1;\n }\n } $content .=\"\\n\\n\\n\";\n }\n $backup_name = $backup_name ? $backup_name : $name.\"___(\".date('H-i-s').\"_\".date('d-m-Y').\")__rand\".rand(1,11111111).\".sql\";\n header('Content-Type: application/octet-stream'); header(\"Content-Transfer-Encoding: Binary\"); header(\"Content-disposition: attachment; filename=\\\"\".$backup_name.\"\\\"\"); echo $content; exit;\n}\n</code></pre>\n" }, { "answer_id": 32117725, "author": "Vali Munteanu", "author_id": 4800442, "author_profile": "https://Stackoverflow.com/users/4800442", "pm_score": 2, "selected": false, "text": "<p>Here is a <code>PHP</code> script I made which will backup all tables in your database. It is based on this <a href=\"http://davidwalsh.name/backup-mysql-database-php\" rel=\"nofollow\">http://davidwalsh.name/backup-mysql-database-php</a> with some improvements. First of all it will correctly set up <code>foreign key restrictions</code>.</p>\n\n<p>In my set up the script will run on a certain day of the week, let's say Monday. In case it did not run on Monday, it will still run on Tuesday (for example), creating the <code>.sql</code> file with the date of previous Monday, when it was supposed to run. It will erase <code>.sql</code> file from 4 weeks ago, so it always keeps the last 4 backups. Here's the code: </p>\n\n<pre><code>&lt;?php\n\nbackup_tables();\n\n// backup all tables in db\nfunction backup_tables()\n{\n $day_of_backup = 'Monday'; //possible values: `Monday` `Tuesday` `Wednesday` `Thursday` `Friday` `Saturday` `Sunday`\n $backup_path = 'databases/'; //make sure it ends with \"/\"\n $db_host = 'localhost';\n $db_user = 'root';\n $db_pass = '';\n $db_name = 'movies_database_1';\n\n //set the correct date for filename\n if (date('l') == $day_of_backup) {\n $date = date(\"Y-m-d\");\n } else {\n //set $date to the date when last backup had to occur\n $datetime1 = date_create($day_of_backup);\n $date = date(\"Y-m-d\", strtotime($day_of_backup.' -7 days'));\n }\n\n if (!file_exists($backup_path.$date.'-backup'.'.sql')) {\n\n //connect to db\n $link = mysqli_connect($db_host,$db_user,$db_pass);\n mysqli_set_charset($link,'utf8');\n mysqli_select_db($link,$db_name);\n\n //get all of the tables\n $tables = array();\n $result = mysqli_query($link, 'SHOW TABLES');\n while($row = mysqli_fetch_row($result))\n {\n $tables[] = $row[0];\n }\n\n //disable foreign keys (to avoid errors)\n $return = 'SET FOREIGN_KEY_CHECKS=0;' . \"\\r\\n\";\n $return.= 'SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\";' . \"\\r\\n\";\n $return.= 'SET AUTOCOMMIT=0;' . \"\\r\\n\";\n $return.= 'START TRANSACTION;' . \"\\r\\n\";\n\n //cycle through\n foreach($tables as $table)\n {\n $result = mysqli_query($link, 'SELECT * FROM '.$table);\n $num_fields = mysqli_num_fields($result);\n $num_rows = mysqli_num_rows($result);\n $i_row = 0;\n\n //$return.= 'DROP TABLE '.$table.';'; \n $row2 = mysqli_fetch_row(mysqli_query($link,'SHOW CREATE TABLE '.$table));\n $return.= \"\\n\\n\".$row2[1].\";\\n\\n\"; \n\n if ($num_rows !== 0) {\n $row3 = mysqli_fetch_fields($result);\n $return.= 'INSERT INTO '.$table.'( ';\n foreach ($row3 as $th) \n { \n $return.= '`'.$th-&gt;name.'`, '; \n }\n $return = substr($return, 0, -2);\n $return.= ' ) VALUES';\n\n for ($i = 0; $i &lt; $num_fields; $i++) \n {\n while($row = mysqli_fetch_row($result))\n {\n $return.=\"\\n(\";\n for($j=0; $j&lt;$num_fields; $j++) \n {\n $row[$j] = addslashes($row[$j]);\n $row[$j] = preg_replace(\"#\\n#\",\"\\\\n\",$row[$j]);\n if (isset($row[$j])) { $return.= '\"'.$row[$j].'\"' ; } else { $return.= '\"\"'; }\n if ($j&lt;($num_fields-1)) { $return.= ','; }\n }\n if (++$i_row == $num_rows) {\n $return.= \");\"; // last row\n } else {\n $return.= \"),\"; // not last row\n } \n }\n }\n }\n $return.=\"\\n\\n\\n\";\n }\n\n // enable foreign keys\n $return .= 'SET FOREIGN_KEY_CHECKS=1;' . \"\\r\\n\";\n $return.= 'COMMIT;';\n\n //set file path\n if (!is_dir($backup_path)) {\n mkdir($backup_path, 0755, true);\n }\n\n //delete old file\n $old_date = date(\"Y-m-d\", strtotime('-4 weeks', strtotime($date)));\n $old_file = $backup_path.$old_date.'-backup'.'.sql';\n if (file_exists($old_file)) unlink($old_file);\n\n //save file\n $handle = fopen($backup_path.$date.'-backup'.'.sql','w+');\n fwrite($handle,$return);\n fclose($handle);\n }\n}\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 56603821, "author": "Teepeemm", "author_id": 2336725, "author_profile": "https://Stackoverflow.com/users/2336725", "pm_score": 1, "selected": false, "text": "<p>I found that I didn't have enough permissions for <code>SELECT * INTO OUTFILE</code>.\nBut I was able to use enough php (iterating and imploding) to really cut down on the nested loops compared to other approaches.</p>\n\n<pre><code>$dbfile = tempnam(sys_get_temp_dir(),'sql');\n\n// array_chunk, but for an iterable\nfunction iter_chunk($iterable,$chunksize) {\n foreach ( $iterable as $item ) {\n $ret[] = $item;\n if ( count($ret) &gt;= $chunksize ) {\n yield $ret;\n $ret = array();\n }\n }\n if ( count($ret) &gt; 0 ) {\n yield $ret;\n }\n}\n\nfunction tupleFromArray($assocArr) {\n return '('.implode(',',array_map(function($val) {\n return '\"'.addslashes($val).'\"';\n },array_values($assocArr))).')';\n}\n\nfile_put_contents($dbfile,\"\\n-- Table $table --\\n/*\\n\");\n$description = $db-&gt;query(\"DESCRIBE `$table`\");\n$row = $description-&gt;fetch_assoc();\nfile_put_contents($dbfile,implode(\"\\t\",array_keys($row)).\"\\n\",FILE_APPEND);\nforeach ( $description as $row ) {\n file_put_contents($dbfile,implode(\"\\t\",array_values($row)).\"\\n\",FILE_APPEND);\n}\nfile_put_contents($dbfile,\"*/\\n\",FILE_APPEND);\nfile_put_contents($dbfile,\"DROP TABLE IF EXISTS `$table`;\\n\",FILE_APPEND);\nfile_put_contents($dbfile,array_pop($db-&gt;query(\"SHOW CREATE TABLE `$table`\")-&gt;fetch_row()),FILE_APPEND);\n$ret = $db-&gt;query(\"SELECT * FROM `$table`\");\n$chunkedData = iter_chunk($ret,1023);\nforeach ( $chunkedData as $chunk ) {\n file_put_contents($dbfile, \"\\n\\nINSERT INTO `$table` VALUES \" . implode(',',array_map('tupleFromArray',$chunk)) . \";\\n\", FILE_APPEND );\n}\nreadfile($dbfile);\nunlink($dbfile);\n</code></pre>\n\n<p>If you have tables with foreign keys, this approach can still work if you drop\nthem in the correct order and then recreate them in the correct (reverse) order.\nThe <code>CREATE</code> statement will create the foreign key dependency for you.\nGo through <code>SELECT * FROM information_schema.referential_constraints</code> to\ndetermine that order.</p>\n\n<p>If your foreign keys have a circular dependency, then there is no possible order to drop or create. In that case, you might be able to follow the lead of phpMyAdmin, which creates all of the foreign keys at the end. But this also means that you have to adjust the <code>CREATE</code> statements.</p>\n" } ]
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. Readibility certainly goes a long way, but I wouldn't trade it for reusability. Consider the case when you'll need to add another subclass - you'll also need to update the base class accordingly.</p>\n" }, { "answer_id": 82012, "author": "RickL", "author_id": 7261, "author_profile": "https://Stackoverflow.com/users/7261", "pm_score": 1, "selected": false, "text": "<p>If file length is something you retrieve often, why not implement a property in the BDictionary (?) class... so that you code becomes:</p>\n\n<pre><code>BDictionary torrent = BItem.DecodeFile(\"my.torrent\");\nint filelength = torrent.FileLength;\n</code></pre>\n\n<p>That way the implementation details are hidden from the user.</p>\n" }, { "answer_id": 82013, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 4, "selected": true, "text": "<p>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).</p>\n\n<p>That makes your code work in the same way and gives you a more readable error in case you should write</p>\n\n<pre><code> (BInteger)torrent[\"info\"][0][\"files\"][\"length\"];\n</code></pre>\n\n<p>by mistake.</p>\n" }, { "answer_id": 82023, "author": "Stormenet", "author_id": 2090, "author_profile": "https://Stackoverflow.com/users/2090", "pm_score": 0, "selected": false, "text": "<p>Did you concider parsing a simple \"path\" so you could write it this way:</p>\n\n<p><p><code>\nBDictionary torrent = BItem.DecodeFile(\"my.torrent\");<br />\nint filelength = (int)torrent.Fetch(\"info.files.0.length\");\n</code></p><p>\nPerhaps not the best way, but the readability increases(a little)</p></p>\n" }, { "answer_id": 82037, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 0, "selected": false, "text": "<ul>\n<li>If you have complete control of your codebase and your thought-process, by all means do.</li>\n<li>If not, you'll regret this the day some new person injects a BItem derivation that you didn't see coming into <em>your</em> BList or BDictionary.</li>\n</ul>\n\n<p>If you have to do this, atleast wrap it (control access to the list) in a class which has strongly typed method signatures. </p>\n\n<pre><code>BString GetString(BInteger);\nSetString(BInteger, BString);\n</code></pre>\n\n<p>Accept and return BStrings even though you internally store it in a BList of BItems. <em>(let me split before I make my 2 B or not 2 B)</em></p>\n" }, { "answer_id": 82040, "author": "John Christensen", "author_id": 1194, "author_profile": "https://Stackoverflow.com/users/1194", "pm_score": 0, "selected": false, "text": "<p>Hmm. I would actually argue that the first line of coded is more readable than the second - it takes a little longer to figure out what's going on it, but its more apparant that you're treating objects as BList or BDictionary. Applying the methods to the abstract class hides that detail, which can make it harder to figure out what your method is actually doing.</p>\n" }, { "answer_id": 82044, "author": "neaorin", "author_id": 15591, "author_profile": "https://Stackoverflow.com/users/15591", "pm_score": 1, "selected": false, "text": "<p>The way I see it, not all BItems are collections, thus not all BItems have indexers, so the indexer shouldn't be in BItem. I would derive another abstract class from BItem, let's name it BCollection, and put the indexers there, something like:</p>\n\n<pre><code>abstract class BCollection : BItem {\n\n public BItem this[int index] {get;}\n public BItem this[string index] {get;}\n}\n</code></pre>\n\n<p>and make BList and BDictionary inherit from BCollection.\nOr you could go the extra mile and make BCollection a generic class.</p>\n" }, { "answer_id": 82193, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you introduce generics, you can avoid casting.</p>\n\n<pre><code>class DecodedTorrent : BDictionary&lt;BDictionary&lt;BList&lt;BDictionary&lt;BInteger&gt;&gt;&gt;&gt;\n{\n}\n</code></pre>\n\n<hr>\n\n<pre><code>DecodedTorrent torrent = BItem.DecodeFile(\"mytorrent\");\nint x = torrent[\"info\"][\"files\"][0][\"length\"];\n</code></pre>\n\n<p>Hmm, but that probably won't work, as the types may depend on the path you take through the structure.</p>\n" }, { "answer_id": 82399, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Is it just me</p>\n\n<pre><code>BDictionary torrent = BItem.DecodeFile(\"my.torrent\");int filelength = (BInteger)((BDictionary)((BList)((BDictionary) torrent[\"info\"])[\"files\"])[0])[\"length\"];\n</code></pre>\n\n<p>You don't need the BDictionary cast 'torrent' is declared as a BDictionary</p>\n\n<pre><code>public BItem this[int index]{&amp;nbsp; &amp;nbsp; get { return ((BList)this)[index]; }}public BItem this[string index]{&amp;nbsp; &amp;nbsp; get { return ((BDictionary)this)[index]; }}\n</code></pre>\n\n<p>These don't acheive the desired result as the return type is still the abstrat version, so you still have to cast.</p>\n\n<p>The rewritten code would have to be</p>\n\n<pre><code>BDictionary torrent = BItem.DecodeFile(\"my.torrent\");int filelength = (BInteger)((BList)((BDictionary)torrent[\"info\"][\"files\"])[0])[\"length\"];\n</code></pre>\n\n<p>Which is the just as bad as the first lot</p>\n" }, { "answer_id": 86393, "author": "Thomas Eyde", "author_id": 3282, "author_profile": "https://Stackoverflow.com/users/3282", "pm_score": 1, "selected": false, "text": "<p>My recommendation would be to introduce more abstractions. I find it confusing that a BItem has a DecodeFile() which returns a BDictionary. This may be a reasonable thing to do in the torrent domain, I don't know.</p>\n\n<p>However, I would find an api like the following more reasonable:</p>\n\n<pre><code>BFile torrent = BFile.DecodeFile(\"my.torrent\");\nint filelength = torrent.Length;\n</code></pre>\n" } ]
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 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?</p>\n" }, { "answer_id": 82194, "author": "bastos.sergio", "author_id": 12772, "author_profile": "https://Stackoverflow.com/users/12772", "pm_score": 2, "selected": false, "text": "<p>What is the actual SQL you're using? I don't see anything wrong with the example you put up. Try looking for misplaced commas and/or quotes that could be triggering the error.</p>\n" }, { "answer_id": 82283, "author": "Swati", "author_id": 12682, "author_profile": "https://Stackoverflow.com/users/12682", "pm_score": 0, "selected": false, "text": "<p>Does it work with just:</p>\n\n<pre><code>SELECT t.foo, t.bar, t.problemcolumn\nFROM problemtable t\nWHERE t.problemcolumn = 'x'\n</code></pre>\n" }, { "answer_id": 93478, "author": "boes", "author_id": 17746, "author_profile": "https://Stackoverflow.com/users/17746", "pm_score": 0, "selected": false, "text": "<p>Please run the next SQL statements. For me it works fine. If you still have this strange error, it will be a DB2 bug. I had some problems once with copying code from UNIX editors into Windows and vice versa. The SQL would not run, although it looked ok. Retyping the statement fixed my problem then.</p>\n\n<p>create table problemtable (\n foo varchar(10),\n bar int,\n problemcolumn varchar(10) \n);</p>\n\n<p>SELECT t.foo, t.bar, t.problemcolumn \n FROM problemtable t\n WHERE t.bar &lt; 60;</p>\n\n<p>SELECT t.foo, t.bar, t.problemcolumn\n FROM problemtable t\n WHERE t.problemcolumn = 'x'\n AND t.bar &lt; 60;</p>\n" }, { "answer_id": 163333, "author": "Fuangwith S.", "author_id": 24550, "author_profile": "https://Stackoverflow.com/users/24550", "pm_score": 0, "selected": false, "text": "<p>It think it should be work in DB2.\nWhat is your font-ent software?</p>\n" }, { "answer_id": 1107682, "author": "SO User", "author_id": 39289, "author_profile": "https://Stackoverflow.com/users/39289", "pm_score": 0, "selected": false, "text": "<p>DB2 sometimes gives misleading errors. You can try these troubleshooting steps:</p>\n\n<ol>\n<li>Try executing the code through\nDBArtisan or DB2 Control Center and\nsee if you get a proper result/ error\nmessage.</li>\n<li>Try using schema_name.problemtable\ninstead of just problemtable</li>\n<li>Make sure that problemcolumn is of\nthe same data type that you are\ncomparing it with.</li>\n</ol>\n" } ]
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><code>&lt;?xml version=\"1.0\" encoding=\"Windows-1252\"?&gt;\n&lt;xml&gt;\n&lt;value&gt;&amp;#27544;&lt;/value&gt;\n&lt;/xml&gt;\n</code></pre>\n\n<p>Or are you wondering how to generate this XML programmatically? If so, what language/environment are you working in?</p>\n" }, { "answer_id": 82413, "author": "Richard Nienaber", "author_id": 9539, "author_profile": "https://Stackoverflow.com/users/9539", "pm_score": 4, "selected": true, "text": "<p>Okay I tested it with the following code:</p>\n\n<pre><code> string xml = \"&lt;?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?&gt;&lt;xml&gt;&lt;value&gt;受&lt;/value&gt;&lt;/xml&gt;\";\n\n XmlWriterSettings settings = new XmlWriterSettings { Encoding = Encoding.Default };\n MemoryStream ms = new MemoryStream();\n using (XmlWriter writer = XmlTextWriter.Create(ms, settings))\n XElement.Parse(xml).WriteTo(writer);\n\n string value = Encoding.Default.GetString(ms.ToArray());\n</code></pre>\n\n<p>And it correctly escaped the unicode character thus:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"Windows-1252\"?&gt;&lt;xml&gt;&lt;value&gt;&amp;#x53D7;&lt;/value&gt;&lt;/xml&gt;\n</code></pre>\n\n<p>I must be doing something wrong somewhere else. Thanks for the help.</p>\n" } ]
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 installed. Have the DBA check this out.</p>\n" }, { "answer_id": 178790, "author": "Jim Hudson", "author_id": 8051, "author_profile": "https://Stackoverflow.com/users/8051", "pm_score": 0, "selected": false, "text": "<p>Once you get past the install issues, there are challenges in some Oracle versions when the schemas get big, particularly when you have schemas that include other schemas. I know we had that issue in 9.2, not sure about 10.2 or 11.</p>\n\n<p>For small schemas like your example, though, it should just work.</p>\n" }, { "answer_id": 5274406, "author": "Tomasz Żuk", "author_id": 655526, "author_profile": "https://Stackoverflow.com/users/655526", "pm_score": 2, "selected": false, "text": "<p>You must have <code>ALTER SESSION</code> privilege granted in order to register a schema.</p>\n" }, { "answer_id": 6367816, "author": "user272735", "author_id": 272735, "author_profile": "https://Stackoverflow.com/users/272735", "pm_score": 3, "selected": false, "text": "<p><strong>Update</strong></p>\n\n<p>XML Schema registration requires following privileges:</p>\n\n<pre><code>grant alter session to &lt;USER&gt;;\ngrant create type to &lt;USER&gt;; /* required when gentypes =&gt; true */\ngrant create table to &lt;USER&gt;; /* required when gentables =&gt; true */\n</code></pre>\n\n<p>For some reason it's not enough if those privileges are granted indirectly via roles, but the privileges need <em>to be granted directly to schema/user</em>.</p>\n\n<p><strong>Original Answer</strong></p>\n\n<p>I have also noticed that default values of parameters <code>gentables</code> and <code>gentypes</code> raise <code>insufficient privileges</code> 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.</p>\n\n<p>I'm running on Oracle Database 11g Release 11.2.0.1.0</p>\n\n<h2>gentypes => true, gentables => true</h2>\n\n<pre><code>dbms_xmlschema.registerschema(schemaurl =&gt; name,\n schemadoc =&gt; xmltype(schema),\n local =&gt; true\n --gentypes =&gt; false,\n --gentables =&gt; false\n );\n\nORA-01031: insufficient privileges\nORA-06512: at \"XDB.DBMS_XMLSCHEMA_INT\", line 55\nORA-06512: at \"XDB.DBMS_XMLSCHEMA\", line 159\nORA-06512: at \"JANI.XML_VALIDATOR\", line 38\nORA-06512: at line 7\n</code></pre>\n\n<h2>gentypes => false, gentables => true</h2>\n\n<pre><code>dbms_xmlschema.registerschema(schemaurl =&gt; name,\n schemadoc =&gt; xmltype(schema),\n local =&gt; true,\n gentypes =&gt; false\n --gentables =&gt; false\n );\n\nORA-31084: error while creating table \"JANI\".\"example873_TAB\" for element \"example\"\nORA-01031: insufficient privileges\nORA-06512: at \"XDB.DBMS_XMLSCHEMA_INT\", line 55\nORA-06512: at \"XDB.DBMS_XMLSCHEMA\", line 159\nORA-06512: at \"JANI.XML_VALIDATOR\", line 38\nORA-06512: at line 7\n</code></pre>\n\n<h2>gentypes => true, gentables => false</h2>\n\n<pre><code>dbms_xmlschema.registerschema(schemaurl =&gt; name,\n schemadoc =&gt; xmltype(schema),\n local =&gt; true,\n --gentypes =&gt; false\n gentables =&gt; false\n );\n\nORA-01031: insufficient privileges\nORA-06512: at \"XDB.DBMS_XMLSCHEMA_INT\", line 55\nORA-06512: at \"XDB.DBMS_XMLSCHEMA\", line 159\nORA-06512: at \"JANI.XML_VALIDATOR\", line 38\nORA-06512: at line 7\n</code></pre>\n\n<h2>gentypes => false, gentables => false</h2>\n\n<pre><code>dbms_xmlschema.registerschema(schemaurl =&gt; name,\n schemadoc =&gt; xmltype(schema),\n local =&gt; true,\n gentypes =&gt; false,\n gentables =&gt; false\n );\n\nPL/SQL procedure successfully completed.\n</code></pre>\n" }, { "answer_id": 12053644, "author": "Pierre-Gilles Levallois", "author_id": 2162529, "author_profile": "https://Stackoverflow.com/users/2162529", "pm_score": 2, "selected": false, "text": "<p>here is a piece of code that works for me.\nuser272735's answer is right, I wrote another answer as far as I can't write all the code in a comment (too long).</p>\n\n<pre><code>/* Formatted on 21/08/2012 12:52:47 (QP5 v5.115.810.9015) */\nDECLARE\n -- Local variables here\n res BOOLEAN;\n tempXML XMLTYPE;\n xmlDoc XMLTYPE;\n xmlSchema XMLTYPE;\n schemaURL VARCHAR2 (256) := 'testcase.xsd';\nBEGIN\n dbms_xmlSchema.deleteSchema (schemaURL, 4);\n -- Test statements here\n xmlSchema :=\n xmlType('&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xdb=\"http://xmlns.oracle.com/xdb\"\nelementFormDefault=\"qualified\" attributeFormDefault=\"unqualified\"&gt;\n&lt;xs:element name=\"root\" xdb:defaultTable=\"ROOT_TABLE\"&gt;\n&lt;xs:complexType&gt;\n&lt;xs:sequence&gt;\n&lt;xs:element name=\"child1\"/&gt;\n&lt;xs:element name=\"child2\"/&gt;\n&lt;/xs:sequence&gt;\n&lt;/xs:complexType&gt;\n&lt;/xs:element&gt;\n&lt;/xs:schema&gt;\n');\n -- http://stackoverflow.com/questions/82047/validating-xml-files-against-schema-in-oracle-pl-sql\n dbms_xmlschema.registerschema(schemaurl =&gt; schemaURL,\n schemadoc =&gt; xmlSchema,\n local =&gt; true,\n gentypes =&gt; false,\n gentables =&gt; false\n );\n xmlDoc :=\n xmltype('&lt;root xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"'\n || schemaURL\n || '\"&gt;&lt;child1&gt;foo&lt;/child1&gt;&lt;child2&gt;bar&lt;/child2&gt;&lt;/root&gt;');\n xmlDoc.schemaValidate ();\n -- if we are here, xml is valid\n DBMS_OUTPUT.put_line ('OK');\nexception\n when others then\n DBMS_OUTPUT.put_line (SQLErrm);\nEND;\n</code></pre>\n" }, { "answer_id": 48176686, "author": "Robin", "author_id": 6010174, "author_profile": "https://Stackoverflow.com/users/6010174", "pm_score": 0, "selected": false, "text": "<p>Registering the XSD leads to creation of tables, types and triggers. Therefore you need the following grants:</p>\n\n<pre><code>grant create table to &lt;user&gt;;\ngrant create type to &lt;user&gt;;\ngrant create trigger to &lt;user&gt;;\n</code></pre>\n" } ]
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:46 GMT+1000 (EST)</p>\n" }, { "answer_id": 82377, "author": "Sjoerd Visscher", "author_id": 5852, "author_profile": "https://Stackoverflow.com/users/5852", "pm_score": 4, "selected": false, "text": "<p>A JSON value is a string, number, object, array, true, false or null. So this is just a string. There is no official way to represent dates in JSON. This syntax is from the asp.net ajax implementation. Others use the ISO 8601 format.</p>\n\n<p>You can parse it like this:</p>\n\n<pre><code>var s = \"\\/Date(1221644506800-0700)\\/\";\nvar m = s.match(/^\\/Date\\((\\d+)([-+]\\d\\d)(\\d\\d)\\)\\/$/);\nvar date = null;\nif (m)\n date = new Date(1*m[1] + 3600000*m[2] + 60000*m[3]);\n</code></pre>\n" }, { "answer_id": 428857, "author": "Kyle Jones", "author_id": 53424, "author_profile": "https://Stackoverflow.com/users/53424", "pm_score": 3, "selected": false, "text": "<p>The regular expression used in the ASP.net AJAX deserialize method looks for a string that looks like \"/Date(1234)/\" (The string itself actually needs to contain the quotes and slashes). To get such a string, you will need to escape the quote and back slash characters, so the javascript code to create the string looks like \"\\\"\\/Date(1234)\\/\\\"\".</p>\n\n<p>This will work.</p>\n\n<pre><code>Sys.Serialization.JavaScriptSerializer.deserialize(\"\\\"\\\\/Date(1221644506800)\\\\/\\\"\")\n</code></pre>\n\n<p>It's kind of weird, but I found I had to serialize a date, then serialize the string returned from that, then deserialize on the client side once.</p>\n\n<p>Something like this.</p>\n\n<pre><code>Script.Serialization.JavaScriptSerializer jss = new Script.Serialization.JavaScriptSerializer();\nstring script = string.Format(\"alert(Sys.Serialization.JavaScriptSerializer.deserialize({0}));\", jss.Serialize(jss.Serialize(DateTime.Now)));\nPage.ClientScript.RegisterStartupScript(this.GetType(), \"ClientScript\", script, true);\n</code></pre>\n" }, { "answer_id": 959092, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 6, "selected": true, "text": "<p>Provided you know the string is definitely a date I prefer to do this :</p>\n\n<pre><code> new Date(parseInt(value.replace(\"/Date(\", \"\").replace(\")/\",\"\"), 10))\n</code></pre>\n" }, { "answer_id": 1646987, "author": "Alex Nolasco", "author_id": 65694, "author_profile": "https://Stackoverflow.com/users/65694", "pm_score": 2, "selected": false, "text": "<p>For those who don't want to use Microsoft Ajax, simply add a prototype function to the string class.</p>\n\n<p>E.g.</p>\n\n<pre><code> String.prototype.dateFromJSON = function () {\n return eval(this.replace(/\\/Date\\((\\d+)\\)\\//gi, \"new Date($1)\"));\n};\n</code></pre>\n\n<p>Don't want to use eval? Try something simple like</p>\n\n<pre><code>var date = new Date(parseInt(jsonDate.substr(6)));\n</code></pre>\n\n<p>As a side note, I used to think Microsoft was misleading by using this format. However, the JSON specification is not very clear when it comes to defining a way to describe dates in JSON.</p>\n" }, { "answer_id": 2654571, "author": "ESV", "author_id": 150, "author_profile": "https://Stackoverflow.com/users/150", "pm_score": 4, "selected": false, "text": "<p>Bertrand LeRoy, who worked on ASP.NET Atlas/AJAX, <a href=\"http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx\" rel=\"noreferrer\">described the design of the JavaScriptSerializer DateTime output</a> and revealed the origin of the mysterious leading and trailing forward slashes. He made this recommendation:</p>\n\n<blockquote>\n <p>run a simple search for \"\\/Date((\\d+))\\/\" and replace with \"new Date($1)\" before the eval\n (but after validation)</p>\n</blockquote>\n\n<p>I implemented that as:</p>\n\n<pre><code>var serializedDateTime = \"\\/Date(1271389496563)\\/\";\ndocument.writeln(\"Serialized: \" + serializedDateTime + \"&lt;br /&gt;\");\n\nvar toDateRe = new RegExp(\"^/Date\\\\((\\\\d+)\\\\)/$\");\nfunction toDate(s) {\n if (!s) {\n return null;\n }\n var constructor = s.replace(toDateRe, \"new Date($1)\");\n if (constructor == s) {\n throw 'Invalid serialized DateTime value: \"' + s + '\"';\n }\n return eval(constructor);\n}\n\ndocument.writeln(\"Deserialized: \" + toDate(serializedDateTime) + \"&lt;br /&gt;\");\n</code></pre>\n\n<p>This is very close to the many of the other answers:</p>\n\n<ul>\n<li>Use an anchored RegEx as Sjoerd Visscher did -- don't forget the ^ and $.</li>\n<li>Avoid string.replace, and the 'g' or 'i' options on your RegEx. \"/Date(1271389496563)//Date(1271389496563)/\" shouldn't work at all.</li>\n</ul>\n" }, { "answer_id": 41367697, "author": "tavo", "author_id": 3545581, "author_profile": "https://Stackoverflow.com/users/3545581", "pm_score": 2, "selected": false, "text": "<p>Actually, momentjs supports this kind of format, you might do something like:</p>\n\n<pre><code> var momentValue = moment(value);\n\n momentValue.toDate();\n</code></pre>\n\n<p>This returns the value in a javascript date format</p>\n" } ]
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 a special case of a valid version number. Otherwise, it starts with a number. Then there are zero, one, or two \".nn\" sequences, followed by an optional \".*\". This regex would accept 1.2.3.* which may or may not be permitted in your application.</p>\n\n<p>The code for retrieving the matched sequences, especially the <code>(\\.\\d+){0,2}</code> part, will depend on your particular regex library.</p>\n" }, { "answer_id": 82152, "author": "Paweł Hajdan", "author_id": 9403, "author_profile": "https://Stackoverflow.com/users/9403", "pm_score": 5, "selected": false, "text": "<p><strong>Use regex and now you have two problems.</strong> I would split the thing on dots (\".\"), then make sure that each part is either a wildcard or set of digits (regex is perfect now). If the thing is valid, you just return correct chunk of the split.</p>\n" }, { "answer_id": 82205, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 8, "selected": true, "text": "<p>I'd express the format as:</p>\n\n<blockquote>\n <p>\"1-3 dot-separated components, each numeric except that the last one may be *\"</p>\n</blockquote>\n\n<p>As a regexp, that's:\n</p>\n\n<pre><code>^(\\d+\\.)?(\\d+\\.)?(\\*|\\d+)$\n</code></pre>\n\n<p>[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. </p>\n\n<p>In my solution, the groups capture the <code>\".\"</code> characters. This can be dealt with using non-capturing groups as in ajborley's answer.</p>\n\n<p>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.</p>\n\n<p>Perl code to deal with both issues after the regexp could be something like this:</p>\n\n<pre><code>@version = ();\n@groups = ($1, $2, $3);\nforeach (@groups) {\n next if !defined;\n s/\\.//;\n push @version, $_;\n}\n($major, $minor, $mod) = (@version, \"*\", \"*\");\n</code></pre>\n\n<p>Which isn't really any shorter than splitting on <code>\".\"</code>\n]</p>\n" }, { "answer_id": 82237, "author": "FrankS", "author_id": 3134, "author_profile": "https://Stackoverflow.com/users/3134", "pm_score": 2, "selected": false, "text": "<p>Keep in mind regexp are greedy, so if you are just searching within the version number string and not within a bigger text, use ^ and $ to mark start and end of your string.\nThe regexp from Greg seems to work fine (just gave it a quick try in my editor), but depending on your library/language the first part can still match the \"*\" within the wrong version numbers. Maybe I am missing something, as I haven't used Regexp for a year or so.</p>\n\n<p>This should make sure you can only find correct version numbers:</p>\n\n<p>^(\\*|\\d+(\\.\\d+)*(\\.\\*)?)$</p>\n\n<p>edit: actually greg added them already and even improved his solution, I am too slow :)</p>\n" }, { "answer_id": 82262, "author": "svrist", "author_id": 86, "author_profile": "https://Stackoverflow.com/users/86", "pm_score": 3, "selected": false, "text": "<p>I tend to agree with split suggestion.</p>\n\n<p>Ive created a \"tester\" for your problem in perl</p>\n\n<pre><code>#!/usr/bin/perl -w\n\n\n@strings = ( \"1.2.3\", \"1.2.*\", \"1.*\",\"*\" );\n\n%regexp = ( svrist =&gt; qr/(?:(\\d+)\\.(\\d+)\\.(\\d+)|(\\d+)\\.(\\d+)|(\\d+))?(?:\\.\\*)?/,\n onebyone =&gt; qr/^(\\d+\\.)?(\\d+\\.)?(\\*|\\d+)$/,\n greg =&gt; qr/^(\\*|\\d+(\\.\\d+){0,2}(\\.\\*)?)$/,\n vonc =&gt; qr/^((?:\\d+(?!\\.\\*)\\.)+)(\\d+)?(\\.\\*)?$|^(\\d+)\\.\\*$|^(\\*|\\d+)$/,\n ajb =&gt; qr/^(?:(\\d+)\\.)?(?:(\\d+)\\.)?(\\*|\\d+)$/,\n jrudolph =&gt; qr/^(((\\d+)\\.)?(\\d+)\\.)?(\\d+|\\*)$/\n );\n\n foreach my $r (keys %regexp){\n my $reg = $regexp{$r};\n print \"Using $r regexp\\n\";\nforeach my $s (@strings){\n print \"$s : \";\n\n if ($s =~m/$reg/){\n my ($main, $maj, $min,$rev,$ex1,$ex2,$ex3) = (\"any\",\"any\",\"any\",\"any\",\"any\",\"any\",\"any\");\n $main = $1 if ($1 &amp;&amp; $1 ne \"*\") ;\n $maj = $2 if ($2 &amp;&amp; $2 ne \"*\") ;\n $min = $3 if ($3 &amp;&amp; $3 ne \"*\") ;\n $rev = $4 if ($4 &amp;&amp; $4 ne \"*\") ;\n $ex1 = $5 if ($5 &amp;&amp; $5 ne \"*\") ;\n $ex2 = $6 if ($6 &amp;&amp; $6 ne \"*\") ;\n $ex3 = $7 if ($7 &amp;&amp; $7 ne \"*\") ;\n print \"$main $maj $min $rev $ex1 $ex2 $ex3\\n\";\n\n }else{\n print \" nomatch\\n\";\n }\n }\nprint \"------------------------\\n\";\n}\n</code></pre>\n\n<p>Current output:</p>\n\n<pre><code>&gt; perl regex.pl\nUsing onebyone regexp\n1.2.3 : 1. 2. 3 any any any any\n1.2.* : 1. 2. any any any any any\n1.* : 1. any any any any any any\n* : any any any any any any any\n------------------------\nUsing svrist regexp\n1.2.3 : 1 2 3 any any any any\n1.2.* : any any any 1 2 any any\n1.* : any any any any any 1 any\n* : any any any any any any any\n------------------------\nUsing vonc regexp\n1.2.3 : 1.2. 3 any any any any any\n1.2.* : 1. 2 .* any any any any\n1.* : any any any 1 any any any\n* : any any any any any any any\n------------------------\nUsing ajb regexp\n1.2.3 : 1 2 3 any any any any\n1.2.* : 1 2 any any any any any\n1.* : 1 any any any any any any\n* : any any any any any any any\n------------------------\nUsing jrudolph regexp\n1.2.3 : 1.2. 1. 1 2 3 any any\n1.2.* : 1.2. 1. 1 2 any any any\n1.* : 1. any any 1 any any any\n* : any any any any any any any\n------------------------\nUsing greg regexp\n1.2.3 : 1.2.3 .3 any any any any any\n1.2.* : 1.2.* .2 .* any any any any\n1.* : 1.* any .* any any any any\n* : any any any any any any any\n------------------------\n</code></pre>\n" }, { "answer_id": 82271, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 2, "selected": false, "text": "<pre><code>(?ms)^((?:\\d+(?!\\.\\*)\\.)+)(\\d+)?(\\.\\*)?$|^(\\d+)\\.\\*$|^(\\*|\\d+)$\n</code></pre>\n\n<p>Does exactly match your 6 first examples, and rejects the 4 others</p>\n\n<ul>\n<li>group 1: major or major.minor or '*'</li>\n<li>group 2 if exists: minor or *</li>\n<li>group 3 if exists: *</li>\n</ul>\n\n<p>You can remove '(?ms)'<br>\nI used it to indicate to this regexp to be applied on multi-lines through <a href=\"http://bastian-bergerhoff.com/eclipse/features/web/QuickREx/toc.html\" rel=\"nofollow noreferrer\">QuickRex</a></p>\n" }, { "answer_id": 82296, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 3, "selected": false, "text": "<p>Don't know what platform you're on but in .NET there's the System.Version class that will parse \"n.n.n.n\" version numbers for you.</p>\n" }, { "answer_id": 82328, "author": "Victor", "author_id": 14514, "author_profile": "https://Stackoverflow.com/users/14514", "pm_score": 2, "selected": false, "text": "<p>This matches 1.2.3.* too</p>\n\n<blockquote>\n <p>^(*|\\d+(.\\d+){0,2}(.*)?)$</p>\n</blockquote>\n\n<p>I would propose the less elegant:</p>\n\n<p>(*|\\d+(.\\d+)?(.*)?)|\\d+.\\d+.\\d+)</p>\n" }, { "answer_id": 82427, "author": "Andrew Borley", "author_id": 7271, "author_profile": "https://Stackoverflow.com/users/7271", "pm_score": 4, "selected": false, "text": "<p>Thanks for all the responses! This is ace :)</p>\n\n<p>Based on OneByOne's answer (which looked the simplest to me), I added some non-capturing groups (the '(?:' parts - thanks to VonC for introducing me to non-capturing groups!), so the groups that do capture only contain the digits or * character. </p>\n\n<pre><code>^(?:(\\d+)\\.)?(?:(\\d+)\\.)?(\\*|\\d+)$\n</code></pre>\n\n<p>Many thanks everyone!</p>\n" }, { "answer_id": 82472, "author": "jrudolph", "author_id": 7647, "author_profile": "https://Stackoverflow.com/users/7647", "pm_score": 2, "selected": false, "text": "<p>Another try:</p>\n\n<pre><code>^(((\\d+)\\.)?(\\d+)\\.)?(\\d+|\\*)$\n</code></pre>\n\n<p>This gives the three parts in groups 4,5,6 BUT:\nThey are aligned to the right. So the first non-null one of 4,5 or 6 gives the version field.</p>\n\n<ul>\n<li>1.2.3 gives 1,2,3</li>\n<li>1.2.* gives 1,2,*</li>\n<li>1.2 gives null,1,2</li>\n<li>*** gives null,null,*</li>\n<li>1.* gives null,1,*</li>\n</ul>\n" }, { "answer_id": 82488, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 2, "selected": false, "text": "<p>It seems pretty hard to have a regex that does exactly what you want (i.e. accept only the cases that you need and reject <strong>all</strong> others <em>and</em> return some groups for the three components). I've give it a try and come up with this:</p>\n\n<pre><code>^(\\*|(\\d+(\\.(\\d+(\\.(\\d+|\\*))?|\\*))?))$\n</code></pre>\n\n<p>IMO (I've not tested extensively) this should work fine as a validator for the input, but the problem is that this regex doesn't offer a way of retrieving the components. For that you still have to do a split on period.</p>\n\n<p>This solution is not all-in-one, but most times in programming it doesn't need to. Of course this depends on other restrictions that you might have in your code.</p>\n" }, { "answer_id": 82598, "author": "ofaurax", "author_id": 15209, "author_profile": "https://Stackoverflow.com/users/15209", "pm_score": 3, "selected": false, "text": "<pre><code>^(?:(\\d+)\\.)?(?:(\\d+)\\.)?(\\*|\\d+)$\n</code></pre>\n\n<p>Perhaps a more concise one could be :</p>\n\n<pre><code>^(?:(\\d+)\\.){0,2}(\\*|\\d+)$\n</code></pre>\n\n<p>This can then be enhanced to 1.2.3.4.5.* or restricted exactly to X.Y.Z using * or {2} instead of {0,2}</p>\n" }, { "answer_id": 2619727, "author": "nomuus", "author_id": 314179, "author_profile": "https://Stackoverflow.com/users/314179", "pm_score": 3, "selected": false, "text": "<p>This should work for what you stipulated. It hinges on the wild card position and is a nested regex:</p>\n\n<pre><code>^((\\*)|([0-9]+(\\.((\\*)|([0-9]+(\\.((\\*)|([0-9]+)))?)))?))$\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/wAazA.png\" alt=\"http://imgur.com/3E492.png\"></p>\n" }, { "answer_id": 16540907, "author": "Israel Romero", "author_id": 1485676, "author_profile": "https://Stackoverflow.com/users/1485676", "pm_score": 3, "selected": false, "text": "<p>I've seen a lot of answers, but... i have a new one. It works for me at least. I've added a new restriction. Version numbers can't start (major, minor or patch) with any zeros followed by others.</p>\n\n<blockquote>\n <p>01.0.0 is not valid\n 1.0.0 is valid\n 10.0.10 is valid \n 1.0.0000 is not valid</p>\n</blockquote>\n\n<pre><code>^(?:(0\\\\.|([1-9]+\\\\d*)\\\\.))+(?:(0\\\\.|([1-9]+\\\\d*)\\\\.))+((0|([1-9]+\\\\d*)))$\n</code></pre>\n\n<p>It's based in a previous one. But i see this solution better... for me ;)</p>\n\n<p>Enjoy!!!</p>\n" }, { "answer_id": 27540795, "author": "Sudhanshu Mishra", "author_id": 190476, "author_profile": "https://Stackoverflow.com/users/190476", "pm_score": 4, "selected": false, "text": "<p>My 2 cents: I had this scenario: I had to parse version numbers out of a string literal.\n(I know this is very different from the original question, but googling to find a regex for parsing version number showed this thread at the top, so adding this answer here)</p>\n\n<p>So the string literal would be something like: \"Service version 1.2.35.564 is running!\"</p>\n\n<p>I had to parse the 1.2.35.564 out of this literal. Taking a cue from @ajborley, my regex is as follows:</p>\n\n<pre><code>(?:(\\d+)\\.)?(?:(\\d+)\\.)?(?:(\\d+)\\.\\d+)\n</code></pre>\n\n<p>A small C# snippet to test this looks like below:</p>\n\n<pre><code>void Main()\n{\n Regex regEx = new Regex(@\"(?:(\\d+)\\.)?(?:(\\d+)\\.)?(?:(\\d+)\\.\\d+)\", RegexOptions.Compiled);\n\n Match version = regEx.Match(\"The Service SuperService 2.1.309.0) is Running!\");\n version.Value.Dump(\"Version using RegEx\"); // Prints 2.1.309.0 \n}\n</code></pre>\n" }, { "answer_id": 39345000, "author": "Oleksandr Yarushevskyi", "author_id": 4262975, "author_profile": "https://Stackoverflow.com/users/4262975", "pm_score": 2, "selected": false, "text": "<p>One more solution:</p>\n\n<pre><code>^[1-9][\\d]*(.[1-9][\\d]*)*(.\\*)?|\\*$\n</code></pre>\n" }, { "answer_id": 41364868, "author": "Emmerson", "author_id": 3159257, "author_profile": "https://Stackoverflow.com/users/3159257", "pm_score": 2, "selected": false, "text": "<p>Specifying XSD elements:</p>\n\n<pre><code>&lt;xs:simpleType&gt;\n &lt;xs:restriction base=\"xs:string\"&gt;\n &lt;xs:pattern value=\"[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}(\\..*)?\"/&gt;\n &lt;/xs:restriction&gt;\n&lt;/xs:simpleType&gt;\n</code></pre>\n" }, { "answer_id": 44088487, "author": "vitaly-t", "author_id": 1102051, "author_profile": "https://Stackoverflow.com/users/1102051", "pm_score": 2, "selected": false, "text": "<p>My take on this, as a good exercise - <a href=\"https://github.com/vitaly-t/vparse\" rel=\"nofollow noreferrer\">vparse</a>, which has a <a href=\"https://github.com/vitaly-t/vparse/blob/master/index.js\" rel=\"nofollow noreferrer\">tiny source</a>, with a simple function:</p>\n\n<pre><code>function parseVersion(v) {\n var m = v.match(/\\d*\\.|\\d+/g) || [];\n v = {\n major: +m[0] || 0,\n minor: +m[1] || 0,\n patch: +m[2] || 0,\n build: +m[3] || 0\n };\n v.isEmpty = !v.major &amp;&amp; !v.minor &amp;&amp; !v.patch &amp;&amp; !v.build;\n v.parsed = [v.major, v.minor, v.patch, v.build];\n v.text = v.parsed.join('.');\n return v;\n}\n</code></pre>\n" }, { "answer_id": 44500980, "author": "Shiva", "author_id": 2068802, "author_profile": "https://Stackoverflow.com/users/2068802", "pm_score": 3, "selected": false, "text": "<p>I had a requirement to search/match for version numbers, that follows maven convention or even just single digit. But no qualifier in any case. It was peculiar, it took me time then I came up with this:</p>\n\n<pre><code>'^[0-9][0-9.]*$'\n</code></pre>\n\n<p>This makes sure the version,</p>\n\n<ol>\n<li>Starts with a digit</li>\n<li>Can have any number of digit</li>\n<li>Only digits and '.' are allowed</li>\n</ol>\n\n<p>One drawback is that version can even end with '.' But it can handle indefinite length of version (crazy versioning if you want to call it that)</p>\n\n<p>Matches:</p>\n\n<ul>\n<li>1.2.3</li>\n<li>1.09.5</li>\n<li>3.4.4.5.7.8.8.</li>\n<li>23.6.209.234.3</li>\n</ul>\n\n<p>If you are not unhappy with '.' ending, may be you can combine with endswith logic</p>\n" }, { "answer_id": 62344454, "author": "Pau Ballada", "author_id": 1542507, "author_profile": "https://Stackoverflow.com/users/1542507", "pm_score": 3, "selected": false, "text": "<p>For parsing version numbers that follow these rules:\n - Are only digits and dots\n - Cannot start or end with a dot\n - Cannot be two dots together</p>\n\n<p>This one did the trick to me.</p>\n\n<pre><code>^(\\d+)((\\.{1}\\d+)*)(\\.{0})$\n</code></pre>\n\n<p>Valid cases are:</p>\n\n<p>1, 0.1, 1.2.1</p>\n" }, { "answer_id": 64274924, "author": "Marc Ruef", "author_id": 6424520, "author_profile": "https://Stackoverflow.com/users/6424520", "pm_score": 2, "selected": false, "text": "<p>Sometimes version numbers might contain alphanumeric minor information (e.g. <em>1.2.0b</em> or <em>1.2.0-beta</em>). In this case I am using this regex:</p>\n<pre><code>([0-9]{1,4}(\\.[0-9a-z]{1,6}){1,5})\n</code></pre>\n" }, { "answer_id": 64784354, "author": "Or Assayag", "author_id": 4442606, "author_profile": "https://Stackoverflow.com/users/4442606", "pm_score": 1, "selected": false, "text": "<p>I found this, and it works for me:</p>\n<pre><code>/(\\^|\\~?)(\\d|x|\\*)+\\.(\\d|x|\\*)+\\.(\\d|x|\\*)+\n</code></pre>\n" }, { "answer_id": 70575435, "author": "山茶树和葡萄树", "author_id": 5819157, "author_profile": "https://Stackoverflow.com/users/5819157", "pm_score": 1, "selected": false, "text": "<pre><code>/^([1-9]{1}\\d{0,3})(\\.)([0-9]|[1-9]\\d{1,3})(\\.)([0-9]|[1-9]\\d{1,3})(\\-(alpha|beta|rc|HP|CP|SP|hp|cp|sp)[1-9]\\d*)?(\\.C[0-9a-zA-Z]+(-U[1-9]\\d*)?)?(\\.[0-9a-zA-Z]+)?$/\n</code></pre>\n<ul>\n<li>A normal version: <code>([1-9]{1}\\d{0,3})(\\.)([0-9]|[1-9]\\d{1,3})(\\.)([0-9]|[1-9]\\d{1,3})</code></li>\n<li>A Pre-release or patched version: <code>(\\-(alpha|beta|rc|EP|HP|CP|SP|ep|hp|cp|sp)[1-9]\\d*)?</code> (Extension Pack, Hotfix Pack, Coolfix Pack, Service Pack)</li>\n<li>Customized version: <code>(\\.C[0-9a-zA-Z]+(-U[1-9]\\d*)?)?</code></li>\n<li>Internal version: <code>(\\.[0-9a-zA-Z]+)?</code></li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/Qnquk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Qnquk.png\" alt=\"enter image description here\" /></a></p>\n" } ]
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 themselves from the list.</p>\n\n<p>In response to the comment, the implementation of the subject-observer pattern should allow for dynamic addition / removal of observers. In C#, the event system is a subject/observer pattern where observers are added using <code>event += observer</code> and removed using <code>event -= observer</code>.</p>\n" }, { "answer_id": 102984, "author": "QBziZ", "author_id": 11572, "author_profile": "https://Stackoverflow.com/users/11572", "pm_score": 3, "selected": true, "text": "<p>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. \nSo the Observer object should have a lifetime that isn't ended before that of the data source.</p>\n\n<p>This can be done by only adding Observers, but never removing them. \nYou could have each observer not do the core implementation itself, but have it delegate this task to an ObserverImpl object. \nYou 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 )</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>Optimization :\nIf 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.\nWorst 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 )</p>\n" } ]
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, unless you have a strong reason to do it so.</p>\n" }, { "answer_id": 82132, "author": "Aleksi Yrttiaho", "author_id": 11427, "author_profile": "https://Stackoverflow.com/users/11427", "pm_score": 6, "selected": true, "text": "<p>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 <code>ObjectStreamField</code> named <code>serialPersistentFields</code>. <a href=\"http://java.sun.com/developer/technicalArticles/ALT/serialization/#2\" rel=\"noreferrer\">See Oracle documentation</a></p>\n\n<p>Added content: \nAs you use <a href=\"http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Logger.html#getLogger(java.lang.String)\" rel=\"noreferrer\">getLogger(getClass())</a>, 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. </p>\n" }, { "answer_id": 82138, "author": "Philip Helger", "author_id": 15254, "author_profile": "https://Stackoverflow.com/users/15254", "pm_score": 2, "selected": false, "text": "<p>Try making the Logger static instead. Than you don't have to care about serialization because it is handled by the class loader.</p>\n" }, { "answer_id": 82275, "author": "MB.", "author_id": 11961, "author_profile": "https://Stackoverflow.com/users/11961", "pm_score": 0, "selected": false, "text": "<p>If you want the Logger to be per-instance then yes, you would want to make it transient if you're going to serialize your objects. Log4J Loggers aren't serializable, not in the version of Log4J that I'm using anyway, so if you don't make your Logger fields transient you'll get exceptions on serialization.</p>\n" }, { "answer_id": 82304, "author": "Glever", "author_id": 15504, "author_profile": "https://Stackoverflow.com/users/15504", "pm_score": 0, "selected": false, "text": "<p>Loggers are not serializable so you must use transient when storing them in instance fields.\nIf you want to restore the logger after deserialization you can store the Level (String) indide your object which does get serialized.</p>\n" }, { "answer_id": 82551, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>These kinds of cases, particularly in EJB, are generally best handled via thread local state. Usually the use case is something like you have a particular transaction which is encountering a problem and you need to elevate logging to debug for that operation so you can generate detailed logging on the problem operation. Carry some thread local state across the transaction and use that to select the correct logger. Frankly I don't know where it would be beneficial to set the level on an INSTANCE in this environment because the mapping of instances into the transaction should be a container level function, you won't actually have control of which instance is used in a given transaction anyway.</p>\n\n<p>Even in cases where you're dealing with a DTO it is not generally a good idea to design your system in such a way that a given specific instance is required because the design can easily evolve in ways that make that a bad choice. You could come along a month from now and decide that efficiency considerations (caching or some other life cycle changing optimization) will break your assumption about the mapping of instances into units of work. </p>\n" }, { "answer_id": 82552, "author": "user9189", "author_id": 9189, "author_profile": "https://Stackoverflow.com/users/9189", "pm_score": 3, "selected": false, "text": "<p>Either declare your logger field as static or as transient. </p>\n\n<p>Both ways ensure the writeObject() method will not attempt to write the field to the output stream during serialization.</p>\n\n<p>Usually logger fields are declared static, but if you need it to be an instance field just declare it transient, as its usually done for any non-serializable field. Upon deserialization the logger field will be null, though, so you have to implement a readObject() method to initialize it properly.</p>\n" }, { "answer_id": 82565, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 3, "selected": false, "text": "<p>If you <em>really</em> want to go the transient approach you will need to reset the log when your object is deserialized. The way to do that is to implement the method:</p>\n\n<pre><code> private void readObject(java.io.ObjectInputStream in) \n throws IOException, ClassNotFoundException;\n</code></pre>\n\n<p>The javadocs for <a href=\"http://java.sun.com/javase/6/docs/api/java/io/Serializable.html\" rel=\"noreferrer\">Serializable</a> has information on this method. </p>\n\n<p>Your implementation of it will look something like:</p>\n\n<pre><code> private void readObject(java.io.ObjectInputStream in) \n throws IOException, ClassNotFoundException {\n log = Logger.getLogger(...);\n in.defaultReadObject();\n }\n</code></pre>\n\n<p>If you do not do this then log will be null after deserializing your object.</p>\n" }, { "answer_id": 84187, "author": "James A. N. Stauffer", "author_id": 6770, "author_profile": "https://Stackoverflow.com/users/6770", "pm_score": 0, "selected": false, "text": "<p>There are good reasons to use an instance logger. One very good use case is so you can declare the logger in a super-class and use it in all sub-classes (the only downside is that logs from the super-class are attributed to the sub-class but it is usually easy to see that).</p>\n\n<p>(Like others have mentioned use static or transient).</p>\n" } ]
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 following:</p>\n\n<pre><code> IDesignEngine engine = null;\n DesignConfig dConfig = new DesignConfig();\n EngineConfig config = new EngineConfig();\n IDesignEngineFactory factory = null;\n config.setLogConfig(LOG_DIRECTORY, Level.FINE);\n HttpServletRequest servletRequest = (HttpServletRequest) FacesContext.getCurrentInstance()\n .getExternalContext().getRequest();\n\n String u = servletRequest.getSession().getServletContext().getRealPath(\"/\");\n File f = new File(u + PATH_TO_ENGINE_HOME);\n\n log.debug(\"setting engine home to:\"+f.getAbsolutePath());\n config.setEngineHome(f.getAbsolutePath());\n\n Platform.startup(config);\n factory = (IDesignEngineFactory) Platform.createFactoryObject(IDesignEngineFactory.EXTENSION_DESIGN_ENGINE_FACTORY);\n engine = factory.createDesignEngine(dConfig);\n SessionHandle session = engine.newSessionHandle(null);\n\n this.design = session.openDesign(u + PATH_TO_MAIN_DESIGN);\n</code></pre>\n\n<p>Perhaps you can solve your problem by comparing this code snippet and your own code. btw my PATH_TO_ENGINE_HOME is \"/WEB-INF/platform\". [edit]I used the complete \"platform\"-folder from the WebViewerExample of the birt-runtime-2_1_1. atm birt-runtime-2_3_0 is actual.[/edit]</p>\n\n<p>If this doesn't help please give a few more details (for example a code snippet).</p>\n" }, { "answer_id": 93278, "author": "Scott Rosenbaum", "author_id": 5412, "author_profile": "https://Stackoverflow.com/users/5412", "pm_score": 2, "selected": true, "text": "<p>Just a thought, but I wonder if your use of a forward slash when setting the logger is causing a problem? instead of</p>\n\n<pre><code>config.setLogConfig(\"d:/temp\", Level.FINEST);\n</code></pre>\n\n<p>you should use </p>\n\n<pre><code> config.setLogConfig(\"/temp\", Level.FINEST);\n</code></pre>\n\n<p>or</p>\n\n<pre><code> config.setLogConfig(\"d:\\\\temp\", Level.FINEST);\n</code></pre>\n\n<p>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. </p>\n\n<p>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. </p>\n\n<p>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:</p>\n\n<pre><code>http://longlake.minnovent.com/repos/birt_example\n</code></pre>\n\n<p>The projects that you need are:</p>\n\n<pre><code>birt_api_example\nbirt_runtime_lib\nscript.lib\n</code></pre>\n\n<p>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: <a href=\"http://birtworld.blogspot.com/2008/04/testing-and-debug-of-reports.html\" rel=\"nofollow noreferrer\">Testing And Debug of Reports</a></p>\n" } ]
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-authentication/tree/master\" rel=\"nofollow noreferrer\">restful_authentication plugin</a>. Maybe it will help.</p>\n" }, { "answer_id": 83039, "author": "Codebeef", "author_id": 12037, "author_profile": "https://Stackoverflow.com/users/12037", "pm_score": 2, "selected": true, "text": "<p>OK, I think I have a solution:</p>\n\n<ul>\n<li>Generate the plugin via script/generate plugin</li>\n<li>change the Rakefile, and add</li>\n</ul>\n\n<p><code>\n require 'spec/rake/spectask'</p>\n\n<pre><code>desc 'Test the PLUGIN_NAME plugin.'\nSpec::Rake::SpecTask.new(:spec) do |t|\n t.libs &lt;&lt; 'lib'\n t.verbose = true\nend\n</code></pre>\n\n<p></code></p>\n\n<ul>\n<li>Create a spec directory, and begin adding specs in *_spec.rb files, as normal</li>\n</ul>\n\n<p>You can also modify the default task to run spec instead of test, too.</p>\n" } ]
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-authentication/tree/master\" rel=\"nofollow noreferrer\">restful_authentication plugin</a>. Maybe it will help.</p>\n" }, { "answer_id": 83039, "author": "Codebeef", "author_id": 12037, "author_profile": "https://Stackoverflow.com/users/12037", "pm_score": 2, "selected": true, "text": "<p>OK, I think I have a solution:</p>\n\n<ul>\n<li>Generate the plugin via script/generate plugin</li>\n<li>change the Rakefile, and add</li>\n</ul>\n\n<p><code>\n require 'spec/rake/spectask'</p>\n\n<pre><code>desc 'Test the PLUGIN_NAME plugin.'\nSpec::Rake::SpecTask.new(:spec) do |t|\n t.libs &lt;&lt; 'lib'\n t.verbose = true\nend\n</code></pre>\n\n<p></code></p>\n\n<ul>\n<li>Create a spec directory, and begin adding specs in *_spec.rb files, as normal</li>\n</ul>\n\n<p>You can also modify the default task to run spec instead of test, too.</p>\n" } ]
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.oracle.com/forums/thread.jspa?threadID=612075\" rel=\"nofollow noreferrer\">oracle forums</a> and please check the following:</p>\n\n<ul>\n<li>The field in the database should be TIMESTAMP_TZ and not just TIMESTAMP</li>\n<li>Try adding the annotation @Temporal(value = TemporalType.TIMESTAMP)</li>\n<li>If you don't really need the timezone, put in a date or timestamp field.</li>\n</ul>\n" }, { "answer_id": 85329, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 3, "selected": true, "text": "<p>You should not use a Calendar for accessing dates from the database, for this exact reason. You should use <code>java.util.Date</code> as so:</p>\n\n<pre><code>@Temporal(TemporalType.TIMESTAMP)\n@Column(name=\"activationDate\")\npublic Date getActivationDate() {\n return this.activationDate;\n}\n</code></pre>\n\n<p><code>java.util.Date</code> points to a moment in time, irrespective of any timezones. Calendar can be used to format a date for a particular timezone or locale.</p>\n" } ]
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.out\n\n# end script\n</code></pre>\n\n<p>Then use sudo to run the script:</p>\n\n<pre><code>sudo ./myscript\n</code></pre>\n" }, { "answer_id": 82276, "author": "Penfold", "author_id": 11952, "author_profile": "https://Stackoverflow.com/users/11952", "pm_score": 5, "selected": false, "text": "<p>Make sudo run a shell, like this:</p>\n\n<pre><code>sudo sh -c \"echo foo &gt; ~root/out\"\n</code></pre>\n" }, { "answer_id": 82278, "author": "Cristian Ciupitu", "author_id": 12892, "author_profile": "https://Stackoverflow.com/users/12892", "pm_score": 12, "selected": true, "text": "<p>Your command does not work because the redirection is performed by your shell which does not have the permission to write to <code>/root/test.out</code>. The redirection of the output <strong>is not</strong> performed by sudo.</p>\n\n<p>There are multiple solutions:</p>\n\n<ul>\n<li><p>Run a shell with sudo and give the command to it by using the <code>-c</code> option:</p>\n\n<pre><code>sudo sh -c 'ls -hal /root/ &gt; /root/test.out'\n</code></pre></li>\n<li><p>Create a script with your commands and run that script with sudo:</p>\n\n<pre><code>#!/bin/sh\nls -hal /root/ &gt; /root/test.out\n</code></pre>\n\n<p>Run <code>sudo ls.sh</code>. See Steve Bennett's <a href=\"https://stackoverflow.com/a/16514624/12892\">answer</a> if you don't want to create a temporary file.</p></li>\n<li><p>Launch a shell with <code>sudo -s</code> then run your commands:</p>\n\n<pre><code>[nobody@so]$ sudo -s\n[root@so]# ls -hal /root/ &gt; /root/test.out\n[root@so]# ^D\n[nobody@so]$\n</code></pre></li>\n<li><p>Use <code>sudo tee</code> (if you have to escape a lot when using the <code>-c</code> option):</p>\n\n<pre><code>sudo ls -hal /root/ | sudo tee /root/test.out &gt; /dev/null\n</code></pre>\n\n<p>The redirect to <code>/dev/null</code> is needed to stop <a href=\"http://pubs.opengroup.org/onlinepubs/9699919799/utilities/tee.html\" rel=\"noreferrer\"><strong>tee</strong></a> from outputting to the screen. To <em>append</em> instead of overwriting the output file \n(<code>&gt;&gt;</code>), use <code>tee -a</code> or <code>tee --append</code> (the last one is specific to <a href=\"https://www.gnu.org/software/coreutils/manual/html_node/tee-invocation.html\" rel=\"noreferrer\">GNU coreutils</a>).</p></li>\n</ul>\n\n<p>Thanks go to <a href=\"https://stackoverflow.com/a/82274/12892\">Jd</a>, <a href=\"https://stackoverflow.com/a/82279/12892\">Adam J. Forster</a> and <a href=\"https://stackoverflow.com/a/82553/12892\">Johnathan</a> for the second, third and fourth solutions.</p>\n" }, { "answer_id": 82279, "author": "Adam J. Forster", "author_id": 15676, "author_profile": "https://Stackoverflow.com/users/15676", "pm_score": 3, "selected": false, "text": "<p>Whenever I have to do something like this I just become root:</p>\n\n<pre><code># sudo -s\n# ls -hal /root/ &gt; /root/test.out\n# exit\n</code></pre>\n\n<p>It's probably not the best way, but it works.</p>\n" }, { "answer_id": 82331, "author": "user15453", "author_id": 15453, "author_profile": "https://Stackoverflow.com/users/15453", "pm_score": 1, "selected": false, "text": "<p>Maybe you been given sudo access to only some programs/paths? Then there is no way to do what you want. (unless you will hack it somehow)</p>\n\n<p>If it is not the case then maybe you can write bash script:</p>\n\n<pre><code>cat &gt; myscript.sh\n#!/bin/sh\nls -hal /root/ &gt; /root/test.out \n</code></pre>\n\n<p>Press <kbd>ctrl</kbd> + <kbd>d</kbd> :</p>\n\n<pre><code>chmod a+x myscript.sh\nsudo myscript.sh\n</code></pre>\n\n<p>Hope it help.</p>\n" }, { "answer_id": 82553, "author": "Jonathan", "author_id": 6910, "author_profile": "https://Stackoverflow.com/users/6910", "pm_score": 7, "selected": false, "text": "<p>Someone here has just suggested sudoing tee:</p>\n\n<pre><code>sudo ls -hal /root/ | sudo tee /root/test.out &gt; /dev/null\n</code></pre>\n\n<p>This could also be used to redirect any command, to a directory that you do not have access to. It works because the tee program is effectively an \"echo to a file\" program, and the redirect to /dev/null is to stop it also outputting to the screen to keep it the same as the original contrived example above.</p>\n" }, { "answer_id": 120174, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 6, "selected": false, "text": "<p>The problem is that the <strong>command</strong> gets run under <code>sudo</code>, but the <strong>redirection</strong> gets run under your user. This is done by the shell and there is very little you can do about it.</p>\n<pre><code>sudo command &gt; /some/file.log\n`-----v-----'`-------v-------'\n command redirection\n</code></pre>\n<p>The usual ways of bypassing this are:</p>\n<ul>\n<li><p>Wrap the commands in a script which you call under sudo.</p>\n<p>If the commands and/or log file changes, you can make the\nscript take these as arguments. For example:</p>\n<pre><code>sudo log_script command /log/file.txt\n</code></pre>\n</li>\n<li><p>Call a shell and pass the command line as a parameter with <code>-c</code></p>\n<p>This is especially useful for one off compound commands.\nFor example:</p>\n<pre><code>sudo bash -c &quot;{ command1 arg; command2 arg; } &gt; /log/file.txt&quot;\n</code></pre>\n</li>\n<li><p>Arrange a pipe/subshell with required rights (i.e. sudo)</p>\n<pre><code># Read and append to a file\ncat ./'file1.txt' | sudo tee -a '/log/file.txt' &gt; '/dev/null';\n\n# Store both stdout and stderr streams in a file\n{ command1 arg; command2 arg; } |&amp; sudo tee -a '/log/file.txt' &gt; '/dev/null';\n</code></pre>\n</li>\n</ul>\n" }, { "answer_id": 8213307, "author": "rhlee", "author_id": 420540, "author_profile": "https://Stackoverflow.com/users/420540", "pm_score": 7, "selected": false, "text": "<p>A trick I figured out myself was</p>\n\n<pre><code>sudo ls -hal /root/ | sudo dd of=/root/test.out\n</code></pre>\n" }, { "answer_id": 16131140, "author": "fardjad", "author_id": 303270, "author_profile": "https://Stackoverflow.com/users/303270", "pm_score": 3, "selected": false, "text": "<p>I would do it this way:</p>\n\n<pre><code>sudo su -c 'ls -hal /root/ &gt; /root/test.out'\n</code></pre>\n" }, { "answer_id": 16514624, "author": "Steve Bennett", "author_id": 263268, "author_profile": "https://Stackoverflow.com/users/263268", "pm_score": 5, "selected": false, "text": "<p>Yet another variation on the theme:</p>\n\n<pre><code>sudo bash &lt;&lt;EOF\nls -hal /root/ &gt; /root/test.out\nEOF\n</code></pre>\n\n<p>Or of course:</p>\n\n<pre><code>echo 'ls -hal /root/ &gt; /root/test.out' | sudo bash\n</code></pre>\n\n<p>They have the (tiny) advantage that you don't need to remember any arguments to <code>sudo</code> or <code>sh</code>/<code>bash</code></p>\n" }, { "answer_id": 19738137, "author": "jg3", "author_id": 2094009, "author_profile": "https://Stackoverflow.com/users/2094009", "pm_score": 5, "selected": false, "text": "<p><em>Clarifying a bit on why the tee option is preferable</em></p>\n\n<p>Assuming you have appropriate permission to execute the command that creates the output, if you pipe the output of your command to tee, you only need to elevate tee's privledges with sudo and direct tee to write (or append) to the file in question.</p>\n\n<p>in the example given in the question that would mean:</p>\n\n<pre><code>ls -hal /root/ | sudo tee /root/test.out\n</code></pre>\n\n<p>for a couple more practical examples:</p>\n\n<pre><code># kill off one source of annoying advertisements\necho 127.0.0.1 ad.doubleclick.net | sudo tee -a /etc/hosts\n\n# configure eth4 to come up on boot, set IP and netmask (centos 6.4)\necho -e \"ONBOOT=\\\"YES\\\"\\nIPADDR=10.42.84.168\\nPREFIX=24\" | sudo tee -a /etc/sysconfig/network-scripts/ifcfg-eth4\n</code></pre>\n\n<p>In each of these examples you are taking the output of a non-privileged command and writing to a file that is usually only writable by root, which is the origin of your question.</p>\n\n<p>It is a good idea to do it this way because the command that generates the output is not executed with elevated privileges. It doesn't seem to matter here with <code>echo</code> but when the source command is a script that you don't completely trust, it is crucial.</p>\n\n<p>Note you can use the -a option to tee to append append (like <code>&gt;&gt;</code>) to the target file rather than overwrite it (like <code>&gt;</code>).</p>\n" }, { "answer_id": 20234210, "author": "jamadagni", "author_id": 1503120, "author_profile": "https://Stackoverflow.com/users/1503120", "pm_score": 2, "selected": false, "text": "<p>This is based on the answer involving <code>tee</code>. To make things easier I wrote a small script (I call it <code>suwrite</code>) and put it in <code>/usr/local/bin/</code> with <code>+x</code> permission:</p>\n\n<pre><code>#! /bin/sh\nif [ $# = 0 ] ; then\n echo \"USAGE: &lt;command writing to stdout&gt; | suwrite [-a] &lt;output file 1&gt; ...\" &gt;&amp;2\n exit 1\nfi\nfor arg in \"$@\" ; do\n if [ ${arg#/dev/} != ${arg} ] ; then\n echo \"Found dangerous argument ‘$arg’. Will exit.\"\n exit 2\n fi\ndone\nsudo tee \"$@\" &gt; /dev/null\n</code></pre>\n\n<p>As shown in the <strong>USAGE</strong> in the code, all you have to do is to pipe the output to this script followed by the desired superuser-accessible filename and it will automatically prompt you for your password if needed (since it includes <code>sudo</code>).</p>\n\n<pre><code>echo test | suwrite /root/test.txt\n</code></pre>\n\n<p>Note that since this is a simple wrapper for <code>tee</code>, it will also accept tee's <code>-a</code> option to append, and also supports writing to multiple files at the same time.</p>\n\n<pre><code>echo test2 | suwrite -a /root/test.txt\necho test-multi | suwrite /root/test-a.txt /root/test-b.txt\n</code></pre>\n\n<p>It also has some simplistic protection against writing to <code>/dev/</code> devices which was a concern mentioned in one of the comments on this page.</p>\n" }, { "answer_id": 38021076, "author": "Nikola Petkanski", "author_id": 581062, "author_profile": "https://Stackoverflow.com/users/581062", "pm_score": 4, "selected": false, "text": "<p>The way I would go about this issue is:</p>\n\n<p>If you need to write/replace the file:</p>\n\n<pre><code>echo \"some text\" | sudo tee /path/to/file\n</code></pre>\n\n<p>If you need to append to the file:</p>\n\n<pre><code>echo \"some text\" | sudo tee -a /path/to/file\n</code></pre>\n" }, { "answer_id": 38632314, "author": "haridsv", "author_id": 95750, "author_profile": "https://Stackoverflow.com/users/95750", "pm_score": 4, "selected": false, "text": "<p>Don't mean to beat a dead horse, but there are too many answers here that use <code>tee</code>, which means you have to redirect <code>stdout</code> to <code>/dev/null</code> unless you want to see a copy on the screen. </p>\n\n<p>A simpler solution is to just use <code>cat</code> like this:</p>\n\n<pre><code>sudo ls -hal /root/ | sudo bash -c \"cat &gt; /root/test.out\"\n</code></pre>\n\n<p>Notice how the redirection is put inside quotes so that it is evaluated by a shell started by <code>sudo</code> instead of the one running it.</p>\n" }, { "answer_id": 46342096, "author": "user8648126", "author_id": 8648126, "author_profile": "https://Stackoverflow.com/users/8648126", "pm_score": 2, "selected": false, "text": "<pre><code>sudo at now \nat&gt; echo test &gt; /tmp/test.out \nat&gt; &lt;EOT&gt; \njob 1 at Thu Sep 21 10:49:00 2017 \n</code></pre>\n" } ]
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 Ruby for more complex things.</p>\n" }, { "answer_id": 82293, "author": "Onorio Catenacci", "author_id": 2820, "author_profile": "https://Stackoverflow.com/users/2820", "pm_score": 0, "selected": false, "text": "<p>From what I've seen I'd start with Awk for this sort of thing and then if you need something more complex, I'd progress to Python.</p>\n" }, { "answer_id": 82300, "author": "Cetra", "author_id": 15087, "author_profile": "https://Stackoverflow.com/users/15087", "pm_score": 0, "selected": false, "text": "<p>I would use sed:</p>\n\n<pre><code> # print section of file between two regular expressions (inclusive)\n sed -n '/Iowa/,/Montana/p' # case sensitive\n</code></pre>\n" }, { "answer_id": 82330, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Since you have cygwin, I'd go with Perl. It's the easiest to learn (check out the O'Reily book: <a href=\"http://books.google.com/books?id=bS--s5DAIHsC&amp;dq=%22learning+perl%22&amp;pg=PP1&amp;ots=udTVanap5Y&amp;sig=gJW55LqGpEXCHqRMgHfTJ8nmP70&amp;hl=en&amp;sa=X&amp;oi=book_result&amp;resnum=1&amp;ct=result\" rel=\"nofollow noreferrer\">Learning Perl</a>) and widely applicable.</p>\n" }, { "answer_id": 82353, "author": "Weidenrinde", "author_id": 11344, "author_profile": "https://Stackoverflow.com/users/11344", "pm_score": 2, "selected": true, "text": "<p>I don't like sed too much, but it works for such things:</p>\n\n<pre><code>var=\"Name2\";sed -n \"1p;s/\\([^ ]*\\) .*$var=\\([^ ,]*\\).*/\\1 \\2/p\" &lt; filename\n</code></pre>\n\n<p>Gives you:</p>\n\n<pre><code> A B\n a Val2\n c Val7\n</code></pre>\n" }, { "answer_id": 82557, "author": "deterb", "author_id": 15585, "author_profile": "https://Stackoverflow.com/users/15585", "pm_score": 0, "selected": false, "text": "<p>I would use Perl. Write a small module (or more than one) for dealing with the different formats. You could then run perl oneliners using that library. Example for what it would\nlook like as follows:</p>\n\n<pre><code>perl -e 'use Parser;' -e 'parser(\"in.input\").get(\"Name2\");'\n</code></pre>\n\n<p>Don't quote me on the syntax, but that's the general idea. Abstract the task at hand to allow you to think in terms of what you need to do, not how you need to do it. Ruby would be another option, it tends to have a cleaner syntax, but either language would work.</p>\n" } ]
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</a> has some support for working with WAV's etc. if you are willing to go down that route. It is designed to work with C# for game programming, so might just take care of what you need.</p>\n" }, { "answer_id": 82364, "author": "moobaa", "author_id": 3569, "author_profile": "https://Stackoverflow.com/users/3569", "pm_score": 1, "selected": false, "text": "<p>There's a bit of a tutorial (with - presumably - working code you can leverage) over at <a href=\"http://www.codeproject.com/KB/audio-video/WaveEdit.aspx\" rel=\"nofollow noreferrer\">CodeProject</a>.</p>\n\n<p>The only thing you have to be a little careful of is that it's perfectly \"normal\" for a WAV file to be composed of multiple chunks - so you have to scoot over the entire file to ensure that all chunks are accounted for.</p>\n" }, { "answer_id": 82379, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>What exactly is your application doing with compressed WAVs? Compressed WAV files are always tricky - I always try and use an alternative container format in this case such as OGG or WMA files. The XNA libraries tend to be designed to work with specific formats - although it is possible that within XACT you'll find a more generic wav playback method. A possible alternative is to look into the SDL C# port, although I've only ever used it to play uncompressed WAVs - once opened you can query the number of samples to determine the length.</p>\n" }, { "answer_id": 82394, "author": "Cetra", "author_id": 15087, "author_profile": "https://Stackoverflow.com/users/15087", "pm_score": 2, "selected": false, "text": "<p>In the .net framework there is a mediaplayer class:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.media.mediaplayer_members.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.windows.media.mediaplayer_members.aspx</a></p>\n\n<p>Here is an example:</p>\n\n<p><a href=\"http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2667714&amp;SiteID=1&amp;pageid=0#2685871\" rel=\"nofollow noreferrer\">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2667714&amp;SiteID=1&amp;pageid=0#2685871</a></p>\n" }, { "answer_id": 82408, "author": "Jan Zich", "author_id": 15716, "author_profile": "https://Stackoverflow.com/users/15716", "pm_score": 6, "selected": true, "text": "<p>You may consider using the mciSendString(...) function (error checking is omitted for clarity):</p>\n\n<pre><code>using System;\nusing System.Text;\nusing System.Runtime.InteropServices;\n\nnamespace Sound\n{\n public static class SoundInfo\n {\n [DllImport(\"winmm.dll\")]\n private static extern uint mciSendString(\n string command,\n StringBuilder returnValue,\n int returnLength,\n IntPtr winHandle);\n\n public static int GetSoundLength(string fileName)\n {\n StringBuilder lengthBuf = new StringBuilder(32);\n\n mciSendString(string.Format(\"open \\\"{0}\\\" type waveaudio alias wave\", fileName), null, 0, IntPtr.Zero);\n mciSendString(\"status wave length\", lengthBuf, lengthBuf.Capacity, IntPtr.Zero);\n mciSendString(\"close wave\", null, 0, IntPtr.Zero);\n\n int length = 0;\n int.TryParse(lengthBuf.ToString(), out length);\n\n return length;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 82439, "author": "sieben", "author_id": 1147, "author_profile": "https://Stackoverflow.com/users/1147", "pm_score": 1, "selected": false, "text": "<p>I'm gonna have to say <a href=\"http://mediainfo.sourceforge.net/en\" rel=\"nofollow noreferrer\">MediaInfo</a>, I have been using it for over a year with a audio/video encoding application I'm working on. It gives all the information for wav files along with almost every other format.</p>\n\n<p><a href=\"http://sourceforge.net/project/showfiles.php?group_id=86862&amp;package_id=90614\" rel=\"nofollow noreferrer\">MediaInfoDll</a> Comes with sample C# code on how to get it working.</p>\n" }, { "answer_id": 83276, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I'm going to assume that you're somewhat familiar with the structure of a .WAV file : it contains a WAVEFORMATEX header struct, followed by a number of other structs (or \"chunks\") containing various kinds of information. See <a href=\"http://en.wikipedia.org/wiki/WAV\" rel=\"nofollow noreferrer\">Wikipedia</a> for more info on the file format.</p>\n\n<p>First, iterate through the .wav file and add up the the unpadded lengths of the \"data\" chunks (the \"data\" chunk contains the audio data for the file; usually there is only one of these, but it's possible that there could be more than one). You now have the total size, in bytes, of the audio data.</p>\n\n<p>Next, get the \"average bytes per second\" member of the WAVEFORMATEX header struct of the file.</p>\n\n<p>Finally, divide the total size of the audio data by the average bytes per second - this will give you the duration of the file, in seconds.</p>\n\n<p>This works reasonably well for uncompressed and compressed files.</p>\n" }, { "answer_id": 396113, "author": "Lars", "author_id": 42809, "author_profile": "https://Stackoverflow.com/users/42809", "pm_score": 3, "selected": false, "text": "<p>I had difficulties with the example of the MediaPlayer-class above. It could take some time, before the player has opened the file. In the \"real world\" you have to register for the MediaOpened-event, after that has fired, the NaturalDuration is valid.\nIn a console-app you just have to wait a few seconds after the open.</p>\n\n<pre><code>using System;\nusing System.Text;\nusing System.Windows.Media;\nusing System.Windows;\n\nnamespace ConsoleApplication2\n{\n class Program\n {\n static void Main(string[] args)\n {\n if (args.Length == 0)\n return;\n Console.Write(args[0] + \": \");\n MediaPlayer player = new MediaPlayer();\n Uri path = new Uri(args[0]);\n player.Open(path);\n TimeSpan maxWaitTime = TimeSpan.FromSeconds(10);\n DateTime end = DateTime.Now + maxWaitTime;\n while (DateTime.Now &lt; end)\n {\n System.Threading.Thread.Sleep(100);\n Duration duration = player.NaturalDuration;\n if (duration.HasTimeSpan)\n {\n Console.WriteLine(duration.TimeSpan.ToString());\n break;\n }\n }\n player.Close();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 2009777, "author": "Josh Stodola", "author_id": 54420, "author_profile": "https://Stackoverflow.com/users/54420", "pm_score": 3, "selected": false, "text": "<p>Not to take anything away from the answer already accepted, but I was able to get the duration of an audio file (several different formats, including AC3, which is what I needed at the time) using the <code>Microsoft.DirectX.AudioVideoPlayBack</code> namespace. This is part of <a href=\"http://msdn.microsoft.com/en-us/library/bb318658(VS.85).aspx\" rel=\"noreferrer\">DirectX 9.0 for Managed Code</a>. Adding a reference to that made my code as simple as this...</p>\n\n<pre><code>Public Shared Function GetDuration(ByVal Path As String) As Integer\n If File.Exists(Path) Then\n Return CInt(New Audio(Path, False).Duration)\n Else\n Throw New FileNotFoundException(\"Audio File Not Found: \" &amp; Path)\n End If\nEnd Function\n</code></pre>\n\n<p>And it's pretty fast, too! Here's a reference for the <a href=\"http://msdn.microsoft.com/en-us/library/bb324224(VS.85).aspx\" rel=\"noreferrer\">Audio</a> class.</p>\n" }, { "answer_id": 8181938, "author": "Monti Pal", "author_id": 1053726, "author_profile": "https://Stackoverflow.com/users/1053726", "pm_score": 5, "selected": false, "text": "<p>Download NAudio.dll\nfrom the link\n<a href=\"https://www.dll-files.com/naudio.dll.html\" rel=\"nofollow noreferrer\">https://www.dll-files.com/naudio.dll.html</a></p>\n<p>and then use this function</p>\n<pre><code>public static TimeSpan GetWavFileDuration(string fileName) \n{ \n WaveFileReader wf = new WaveFileReader(fileName);\n return wf.TotalTime; \n}\n</code></pre>\n<p>you will get the Duration</p>\n" }, { "answer_id": 12416165, "author": "Neoheurist", "author_id": 1670042, "author_profile": "https://Stackoverflow.com/users/1670042", "pm_score": -1, "selected": false, "text": "<pre><code>Imports System.IO\nImports System.Text\n\nImports System.Math\nImports System.BitConverter\n\nPublic Class PulseCodeModulation\n ' Pulse Code Modulation WAV (RIFF) file layout\n\n ' Header chunk\n\n ' Type Byte Offset Description\n ' Dword 0 Always ASCII \"RIFF\"\n ' Dword 4 Number of bytes in the file after this value (= File Size - 8)\n ' Dword 8 Always ASCII \"WAVE\"\n\n ' Format Chunk\n\n ' Type Byte Offset Description\n ' Dword 12 Always ASCII \"fmt \"\n ' Dword 16 Number of bytes in this chunk after this value\n ' Word 20 Data format PCM = 1 (i.e. Linear quantization)\n ' Word 22 Channels Mono = 1, Stereo = 2\n ' Dword 24 Sample Rate per second e.g. 8000, 44100\n ' Dword 28 Byte Rate per second (= Sample Rate * Channels * (Bits Per Sample / 8))\n ' Word 32 Block Align (= Channels * (Bits Per Sample / 8))\n ' Word 34 Bits Per Sample e.g. 8, 16\n\n ' Data Chunk\n\n ' Type Byte Offset Description\n ' Dword 36 Always ASCII \"data\"\n ' Dword 40 The number of bytes of sound data (Samples * Channels * (Bits Per Sample / 8))\n ' Buffer 44 The sound data\n\n Dim HeaderData(43) As Byte\n\n Private AudioFileReference As String\n\n Public Sub New(ByVal AudioFileReference As String)\n Try\n Me.HeaderData = Read(AudioFileReference, 0, Me.HeaderData.Length)\n Catch Exception As Exception\n Throw\n End Try\n\n 'Validate file format\n\n Dim Encoder As New UTF8Encoding()\n\n If \"RIFF\" &lt;&gt; Encoder.GetString(BlockCopy(Me.HeaderData, 0, 4)) Or _\n \"WAVE\" &lt;&gt; Encoder.GetString(BlockCopy(Me.HeaderData, 8, 4)) Or _\n \"fmt \" &lt;&gt; Encoder.GetString(BlockCopy(Me.HeaderData, 12, 4)) Or _\n \"data\" &lt;&gt; Encoder.GetString(BlockCopy(Me.HeaderData, 36, 4)) Or _\n 16 &lt;&gt; ToUInt32(BlockCopy(Me.HeaderData, 16, 4), 0) Or _\n 1 &lt;&gt; ToUInt16(BlockCopy(Me.HeaderData, 20, 2), 0) _\n Then\n Throw New InvalidDataException(\"Invalid PCM WAV file\")\n End If\n\n Me.AudioFileReference = AudioFileReference\n End Sub\n\n ReadOnly Property Channels() As Integer\n Get\n Return ToUInt16(BlockCopy(Me.HeaderData, 22, 2), 0) 'mono = 1, stereo = 2\n End Get\n End Property\n\n ReadOnly Property SampleRate() As Integer\n Get\n Return ToUInt32(BlockCopy(Me.HeaderData, 24, 4), 0) 'per second\n End Get\n End Property\n\n ReadOnly Property ByteRate() As Integer\n Get\n Return ToUInt32(BlockCopy(Me.HeaderData, 28, 4), 0) 'sample rate * channels * (bits per channel / 8)\n End Get\n End Property\n\n ReadOnly Property BlockAlign() As Integer\n Get\n Return ToUInt16(BlockCopy(Me.HeaderData, 32, 2), 0) 'channels * (bits per sample / 8)\n End Get\n End Property\n\n ReadOnly Property BitsPerSample() As Integer\n Get\n Return ToUInt16(BlockCopy(Me.HeaderData, 34, 2), 0)\n End Get\n End Property\n\n ReadOnly Property Duration() As Integer\n Get\n Dim Size As Double = ToUInt32(BlockCopy(Me.HeaderData, 40, 4), 0)\n Dim ByteRate As Double = ToUInt32(BlockCopy(Me.HeaderData, 28, 4), 0)\n Return Ceiling(Size / ByteRate)\n End Get\n End Property\n\n Public Sub Play()\n Try\n My.Computer.Audio.Play(Me.AudioFileReference, AudioPlayMode.Background)\n Catch Exception As Exception\n Throw\n End Try\n End Sub\n\n Public Sub Play(playMode As AudioPlayMode)\n Try\n My.Computer.Audio.Play(Me.AudioFileReference, playMode)\n Catch Exception As Exception\n Throw\n End Try\n End Sub\n\n Private Function Read(AudioFileReference As String, ByVal Offset As Long, ByVal Bytes As Long) As Byte()\n Dim inputFile As System.IO.FileStream\n\n Try\n inputFile = IO.File.Open(AudioFileReference, IO.FileMode.Open)\n Catch Exception As FileNotFoundException\n Throw New FileNotFoundException(\"PCM WAV file not found\")\n Catch Exception As Exception\n Throw\n End Try\n\n Dim BytesRead As Long\n Dim Buffer(Bytes - 1) As Byte\n\n Try\n BytesRead = inputFile.Read(Buffer, Offset, Bytes)\n Catch Exception As Exception\n Throw\n Finally\n Try\n inputFile.Close()\n Catch Exception As Exception\n 'Eat the second exception so as to not mask the previous exception\n End Try\n End Try\n\n If BytesRead &lt; Bytes Then\n Throw New InvalidDataException(\"PCM WAV file read failed\")\n End If\n\n Return Buffer\n End Function\n\n Private Function BlockCopy(ByRef Source As Byte(), ByVal Offset As Long, ByVal Bytes As Long) As Byte()\n Dim Destination(Bytes - 1) As Byte\n\n Try\n Buffer.BlockCopy(Source, Offset, Destination, 0, Bytes)\n Catch Exception As Exception\n Throw\n End Try\n\n Return Destination\n End Function\nEnd Class\n</code></pre>\n" }, { "answer_id": 21500321, "author": "Aleks", "author_id": 3258422, "author_profile": "https://Stackoverflow.com/users/3258422", "pm_score": 2, "selected": false, "text": "<p>Try code below from <a href=\"http://alvas.net/alvas.audio,tips.aspx#tip25\" rel=\"nofollow\">How to determine the length of a .wav file in C#</a></p>\n\n<pre><code> string path = @\"c:\\test.wav\";\n WaveReader wr = new WaveReader(File.OpenRead(path));\n int durationInMS = wr.GetDurationInMS();\n wr.Close();\n</code></pre>\n" }, { "answer_id": 40933199, "author": "Manish Nayak", "author_id": 4732757, "author_profile": "https://Stackoverflow.com/users/4732757", "pm_score": 3, "selected": false, "text": "<p>Yes, There is a free library that can be used to get time duration of Audio file. This library also provides many more functionalities.</p>\n\n<p><a href=\"http://taglib.org/\" rel=\"noreferrer\"><strong>TagLib</strong></a></p>\n\n<p>TagLib is distributed under the GNU Lesser General Public License (LGPL) and Mozilla Public License (MPL).</p>\n\n<p>I implemented below code that returns time duration in seconds.</p>\n\n<pre><code>using TagLib.Mpeg;\n\npublic static double GetSoundLength(string FilePath)\n{\n AudioFile ObjAF = new AudioFile(FilePath);\n return ObjAF.Properties.Duration.TotalSeconds;\n}\n</code></pre>\n" }, { "answer_id": 52929705, "author": "Martin Abilev", "author_id": 7424574, "author_profile": "https://Stackoverflow.com/users/7424574", "pm_score": 1, "selected": false, "text": "<p>time = FileLength / (Sample Rate * Channels * Bits per sample /8)</p>\n" }, { "answer_id": 54192641, "author": "item.wu", "author_id": 10915057, "author_profile": "https://Stackoverflow.com/users/10915057", "pm_score": 2, "selected": false, "text": "<p>i have tested blew code would fail,file formats are like \"\\\\ip\\dir\\*.wav'</p>\n\n<pre><code> public static class SoundInfo\n {\n [DllImport(\"winmm.dll\")]\n private static extern uint mciSendString\n (\n string command,\n StringBuilder returnValue,\n int returnLength,\n IntPtr winHandle\n );\n\n public static int GetSoundLength(string fileName)\n {\n StringBuilder lengthBuf = new StringBuilder(32);\n\n mciSendString(string.Format(\"open \\\"{0}\\\" type waveaudio alias wave\", fileName), null, 0, IntPtr.Zero);\n mciSendString(\"status wave length\", lengthBuf, lengthBuf.Capacity, IntPtr.Zero);\n mciSendString(\"close wave\", null, 0, IntPtr.Zero);\n\n int length = 0;\n int.TryParse(lengthBuf.ToString(), out length);\n\n return length;\n }\n}\n</code></pre>\n\n<p>while naudio works</p>\n\n<pre><code> public static int GetSoundLength(string fileName)\n {\n using (WaveFileReader wf = new WaveFileReader(fileName))\n {\n return (int)wf.TotalTime.TotalMilliseconds;\n }\n }`\n</code></pre>\n" } ]
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 windows width (either by name, or with a RelativeSource ancestor search). </p>\n\n<pre><code>//I know I borrowed this from someone, sorry I forgot to add a comment from whom\npublic class ScaledValueConverter : IValueConverter\n{\n public Object Convert(Object value, Type targetType, Object parameter, System.Globalization.CultureInfo culture)\n {\n Double scalingFactor = 0;\n if (parameter != null)\n {\n Double.TryParse((String)(parameter), out scalingFactor);\n }\n\n if (scalingFactor == 0.0d)\n {\n return Double.NaN;\n }\n\n return (Double)value * scalingFactor;\n }\n\n public Object ConvertBack(Object value, Type targetType, Object parameter, System.Globalization.CultureInfo culture)\n {\n throw new Exception(\"The method or operation is not implemented.\");\n }\n}\n</code></pre>\n" }, { "answer_id": 157780, "author": "Christopher Bennage", "author_id": 6855, "author_profile": "https://Stackoverflow.com/users/6855", "pm_score": 4, "selected": true, "text": "<p>I think the XAML-only approach is somewhat circuitous, but here is a way to do it.</p>\n\n<pre><code>&lt;Page xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:sys=\"clr-namespace:System;assembly=mscorlib\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" &gt;\n\n &lt;!-- This contains our real grid, and a reference grid for binding the layout--&gt;\n &lt;Grid x:Name=\"Container\"&gt;\n\n &lt;!-- hidden because it's behind the grid below --&gt;\n &lt;Grid x:Name=\"LayoutReference\"&gt;\n &lt;Grid.ColumnDefinitions&gt;\n &lt;ColumnDefinition Width=\"*\"/&gt;\n &lt;ColumnDefinition Width=\"*\"/&gt;\n &lt;ColumnDefinition Width=\"*\"/&gt;\n &lt;/Grid.ColumnDefinitions&gt;\n &lt;!-- We need the border, because the column doesn't have an ActualWidth --&gt;\n &lt;Border x:Name=\"ReferenceBorder\" \n Background=\"Black\" /&gt;\n &lt;Border Background=\"White\" Grid.Column=\"1\" /&gt;\n &lt;Border Background=\"Black\" Grid.Column=\"2\" /&gt;\n &lt;/Grid&gt;\n\n &lt;!-- I made this transparent, so we can see the reference --&gt;\n &lt;Grid Opacity=\"0.9\"&gt;\n &lt;Grid.ColumnDefinitions&gt;\n &lt;ColumnDefinition x:Name=\"Column1\" \n MaxWidth=\"{Binding ElementName=ReferenceBorder,Path=ActualWidth}\"/&gt;\n &lt;ColumnDefinition x:Name=\"Column2\" \n MinWidth=\"50\" /&gt;\n &lt;ColumnDefinition x:Name=\"Column3\" \n Width=\"{ Binding ElementName=Column1, Path=Width }\"/&gt;\n &lt;/Grid.ColumnDefinitions&gt;\n\n &lt;Label Grid.Column=\"0\" Background=\"Green\"/&gt;\n &lt;GridSplitter Grid.Column=\"0\" Width=\"5\" /&gt;\n &lt;Label Grid.Column=\"1\" Background=\"Yellow\" /&gt;\n &lt;Label Grid.Column=\"2\" Background=\"Red\" /&gt;\n &lt;/Grid&gt;\n &lt;/Grid&gt;\n\n&lt;/Page&gt;\n</code></pre>\n" } ]
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 = SomeOutlookObject.GetType();\nstring messageClass = t.InvokeMember(\"MessageClass\",\n BindingFlags.Public | \n BindingFlags.GetField | \n BindingFlags.GetProperty,\n null,\n SomeOutlookObject,\n new object[]{}).ToString();\nConsole.WriteLine(\"\\tType: \" + messageClass);\n</code></pre>\n\n<p>I don't know if that helps with an olEmbedded item, but it seems to identify regular messages, calendar items, etc.</p>\n" }, { "answer_id": 13089961, "author": "Duane Wright", "author_id": 1759318, "author_profile": "https://Stackoverflow.com/users/1759318", "pm_score": 0, "selected": false, "text": "<p>Working with email attachments that are also emails which in turn contains user defined properties that I want to access, then I perform the following steps:</p>\n\n<pre><code>Outlook.Application mailApplication = new Outlook.Application();\nOutlook.NameSpace mailNameSpace = mailApplication.GetNamespace(“mapi”);\n// make sure it is an embedded item\nIf(myAttachment.Type == Outlook.OlAttachmentType.olEmbeddeditem)\n{\n myAttachment.Type.SaveAsFile(“temp.msg”);\n Outlook.MailItem attachedEmail = (Outlook.MailItem)mailNameSpace.OpenSharedItem(“temp.msg”);\n String customProperty = attachedEmail.PropertyAccessor.GetProperty(\n “http://schemas.microsoft.com/mapi/string/{00020329-0000-0000-c000-000000000046}/myProp\n}\n</code></pre>\n\n<p>If you open the MailItem using, then I will not have access to the properties as mentioned above:</p>\n\n<pre><code>Outlook.MailItem attachedEmail = (Outlook.MailItem)mailApplication.CreateFromTemplate(“temp.msg”); \n</code></pre>\n" } ]
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 holder for fine-graner beans or collections of beans) into the request scope within our Action.perform() implementation. This view-specific bean would then be rendered by the view.</p>\n" }, { "answer_id": 82517, "author": "Olaf Kock", "author_id": 13447, "author_profile": "https://Stackoverflow.com/users/13447", "pm_score": 1, "selected": true, "text": "<p>As <code>Struts 1.3</code> 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.</p>\n\n<p>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.</p>\n" } ]
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 resources files</a>.</p>\n\n<p>Very efficient, very simple.</p>\n" }, { "answer_id": 82704, "author": "Hrvoje Hudo", "author_id": 1407, "author_profile": "https://Stackoverflow.com/users/1407", "pm_score": 1, "selected": false, "text": "<ol>\n<li>Use urlrewriteing.net for asp.net webforms, or routing with mvc. Rewrite www.site.com/en/something.aspx to url: page.aspx?lang=en.<br>\nUrlRewriteing.net can be easily configured via regex in web.config. You can also use routing with webforms now, it's probably similar...</li>\n<li>with webforms, let every aspx page inherits from BasePage class, which then inherits from Page class.<br>\nIn BasePage class override \"InitializeCulture()\" and set culture info to thread, like you described in question.<br>\nIt's good to do that in this order: 1. check url for Lang param, 2. check cookie, 3. set default lang</li>\n<li>For static content (text, pics url) on pages use LocalResources,or Global if content is repeating across site. You can watch videocast on using global/local res. on www.asp.net</li>\n<li>Prepare db for multiple languages. But that's another story. </li>\n</ol>\n" }, { "answer_id": 84689, "author": "ceetheman", "author_id": 16154, "author_profile": "https://Stackoverflow.com/users/16154", "pm_score": 0, "selected": false, "text": "<p>UrlRewriting is the way to go.</p>\n\n<p>There is a good article on MSDN on the best ways to do it.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms972974.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms972974.aspx</a></p>\n" }, { "answer_id": 87156, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 4, "selected": true, "text": "<p>I decided to go with the new ASP.net Routing.<br>\nWhy not urlRewriting? Because I don't want to change the clean URL that routing gives to you.</p>\n\n<p>Here is the code:</p>\n\n<pre><code>Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)\n ' Code that runs on application startup\n RegisterRoutes(RouteTable.Routes)\nEnd Sub\n\n\nPublic Sub RegisterRoutes(ByVal routes As RouteCollection)\n Dim reportRoute As Route\n Dim DefaultLang As String = \"es\"\n\n reportRoute = New Route(\"{lang}/{page}\", New LangRouteHandler)\n '* if you want, you can contrain the values\n 'reportRoute.Constraints = New RouteValueDictionary(New With {.lang = \"[a-z]{2}\"})\n reportRoute.Defaults = New RouteValueDictionary(New With {.lang = DefaultLang, .page = \"home\"})\n\n routes.Add(reportRoute)\nEnd Sub\n</code></pre>\n\n<p>Then LangRouteHandler.vb class:</p>\n\n<pre><code>Public Class LangRouteHandler\n Implements IRouteHandler\n\n Public Function GetHttpHandler(ByVal requestContext As System.Web.Routing.RequestContext) As System.Web.IHttpHandler _\n Implements System.Web.Routing.IRouteHandler.GetHttpHandler\n\n 'Fill the context with the route data, just in case some page needs it\n For Each value In requestContext.RouteData.Values\n HttpContext.Current.Items(value.Key) = value.Value\n Next\n\n Dim VirtualPath As String\n VirtualPath = \"~/\" + requestContext.RouteData.Values(\"page\") + \".aspx\"\n\n Dim redirectPage As IHttpHandler\n redirectPage = BuildManager.CreateInstanceFromVirtualPath(VirtualPath, GetType(Page))\n Return redirectPage\n\n End Function\nEnd Class\n</code></pre>\n\n<p>Finally I use the default.aspx in the root to redirect to the default lang used in the browser list.<br>\nMaybe this can be done with the route.Defaults, but don't work inside Visual Studio (maybe it works in the server)</p>\n\n<pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)\n Dim DefaultLang As String = \"es\"\n Dim SupportedLangs As String() = {\"en\", \"es\"}\n Dim BrowserLang As String = Mid(Request.UserLanguages(0).ToString(), 1, 2).ToLower\n If SupportedLangs.Contains(BrowserLang) Then DefaultLang = BrowserLang\n\n Response.Redirect(DefaultLang + \"/\")\nEnd Sub\n</code></pre>\n\n<p>Some sources:<br>\n * <a href=\"http://blogs.msdn.com/mikeormond/archive/2008/05/14/using-asp-net-routing-independent-of-mvc.aspx\" rel=\"noreferrer\">Mike Ormond's blog</a><br>\n * <a href=\"http://chriscavanagh.wordpress.com/2008/04/25/systemwebrouting-with-webforms-sample/\" rel=\"noreferrer\">Chris Cavanagh’s Blog</a><br>\n * <a href=\"http://msdn.microsoft.com/en-us/library/cc668201.aspx\" rel=\"noreferrer\">MSDN</a> </p>\n" }, { "answer_id": 186773, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 0, "selected": false, "text": "<p>Kind of a tangent, but I'd actually avoid doing this with different paths unless the different languages are completely content separate from each other.</p>\n\n<p>For Google rank, or for users sharing URLs (one of the big advantages of ‘clean’ URLs), you want the address to stay as constant as possible.</p>\n\n<p>You can find users’ language preferences from their browser settings:</p>\n\n<pre><code>CultureInfo.CurrentUICulture\n</code></pre>\n\n<p>Then your URL for English or Spanish:</p>\n\n<blockquote>\n <p>www.domain.com/products/newproduct</p>\n</blockquote>\n\n<p>Same address for any language, but the user gets the page in their chosen language.</p>\n\n<p>We use this in Canada to provide systems in English and French at the same time.</p>\n" }, { "answer_id": 273628, "author": "Armstrongest", "author_id": 26931, "author_profile": "https://Stackoverflow.com/users/26931", "pm_score": 0, "selected": false, "text": "<p>To do this with URL Routing, refer to this post:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/266719/url-routing-how-to-handle-spaces-and-illegal-characters-for-friendly-urls#271568\">Friendly URLS with URL Routing</a></p>\n" }, { "answer_id": 374210, "author": "msqr", "author_id": 32146, "author_profile": "https://Stackoverflow.com/users/32146", "pm_score": 0, "selected": false, "text": "<p>Also, watch out new IIS 7.0 - URL Rewriting. Excellent article here <a href=\"http://learn.iis.net/page.aspx/496/iis-url-rewriting-and-aspnet-routing/\" rel=\"nofollow noreferrer\">http://learn.iis.net/page.aspx/496/iis-url-rewriting-and-aspnet-routing/</a></p>\n\n<p>I liked this part \n<strong>Which Option Should You Use?</strong></p>\n\n<ol>\n<li><p>If you are developing a new ASP.NET Web application that uses either ASP.NET MVC or ASP.NET Dynamic Data technologies, use ASP.NET routing. Your application will benefit from native support for clean URLs, including generation of clean URLs for the links in your Web pages. Note that ASP.NET routing does not support standard Web Forms applications yet, although there are plans to support it in the future.</p></li>\n<li><p>If you already have a legacy ASP.NET Web application and do not want to change it, use the URL-rewrite module. The URL-rewrite module allows you to translate search-engine-friendly URLs into a format that your application currently uses. Also, it allows you to create redirect rules that can be used to redirect search-engine crawlers to clean URLs. \n<a href=\"http://learn.iis.net/page.aspx/496/iis-url-rewriting-and-aspnet-routing/\" rel=\"nofollow noreferrer\">http://learn.iis.net/page.aspx/496/iis-url-rewriting-and-aspnet-routing/</a></p></li>\n</ol>\n\n<p>Thanks,\nMaulik.</p>\n" } ]
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 use to keep the dataset resident and loop through it, if you then add a waitfor inside the loop you're hogging resources for longer.</p>\n\n<p>But I may be wrong here, what I would suggest is to use perfmon to check the server's performance under both conditions, and then make a decision whether it is worth-it or not to add the wait.</p>\n\n<p>Looking at the tag, I'm assuming you're using MS SQL Server, and not any of the other flavours.</p>\n" }, { "answer_id": 82796, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You could delay the procedure, but that might or might not help you. It depends on how the procedure works. Is it in a transaction, why a cursor (horribly inefficient in SQL Server), where is the slowdown, etc. Perhaps reworking the procedure would make more sense.</p>\n" }, { "answer_id": 82966, "author": "hova", "author_id": 2170, "author_profile": "https://Stackoverflow.com/users/2170", "pm_score": 0, "selected": false, "text": "<p>Ever since SQL 2005 included windowing functions and other neat features, I've been able to eliminate cursors in almost all instances. Perhaps your problem would best be served by eliminating the cursor itself? </p>\n\n<p>Definitely check out Ranking functions <a href=\"http://msdn.microsoft.com/en-us/library/ms189798.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms189798.aspx</a> and Aggregate window functions <a href=\"http://msdn.microsoft.com/en-us/library/ms189461.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms189461.aspx</a></p>\n" }, { "answer_id": 83229, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>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.</p>\n\n<pre><code>declare @minid int, @maxid int, @somevalue int \nselect @minid = 1, @maxid = 5\nwhile @minid &lt;= @maxid\nbegin\n set @somevalue = null\n select @somevalue = somefield from sometable where id = @minid\n print @somevalue\n set @minid = @minid + 1\n waitfor delay '00:00:00.1'\nend\n</code></pre>\n" }, { "answer_id": 453233, "author": "MatBailie", "author_id": 53341, "author_profile": "https://Stackoverflow.com/users/53341", "pm_score": 0, "selected": false, "text": "<p>I'm guessing that whatever code you have means that the other processes can't access the table your cursor is derived from.</p>\n\n<p>Provided that you make the cursor READONLY FASTWORD you should not lock the tables the cursor is derived from.</p>\n\n<p>If, however, you need to write, then WAITFOR wouldn't help. Once you've locked the table, it's locked.</p>\n\n<p>An option would be to snapshot the tables into a temp table, then cursor/loop through that instead. You would then not be locking the underlying tables, but equally the tables could change while you're processing the snapshot...</p>\n\n<p>Dems</p>\n" } ]
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 functionality that you need in the empty constructor and returns the new object.</p>\n\n<pre><code>// Add new partial class to extend functionality\npublic partial class User {\n\n // Add additional constructor\n public User(int id) {\n ID = id;\n }\n\n // Add static method to initialize new object\n public User GetNewUser() {\n // functionality\n User user = new User();\n user.Name = \"NewName\";\n return user;\n }\n}\n</code></pre>\n\n<p>Then elsewhere in your code, instead of using the default empty constructor, do one of the following:</p>\n\n<pre><code>User user1 = new User(1);\nUser user2 = User.GetNewUser();\n</code></pre>\n" }, { "answer_id": 83844, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 5, "selected": true, "text": "<p>The default constructor which is generated by the O/R-Designer, calls a partial function called <code>OnCreated</code> - so the best practice is not to override the default constructor, but instead implement the partial function <code>OnCreated</code> in <code>MyDataClasses.cs</code> to initialize items:</p>\n\n<pre><code>partial void OnCreated()\n{\n Name = \"\";\n}\n</code></pre>\n\n<p>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.</p>\n" }, { "answer_id": 22935888, "author": "Baga", "author_id": 2742356, "author_profile": "https://Stackoverflow.com/users/2742356", "pm_score": 1, "selected": false, "text": "<p>Setting DataContext Connection property to 'None' worked for me. Steps below.</p>\n\n<p>Open the dbml -> Right Click Properties -> Update Connection in DataContext properties to 'None'. This will remove the empty constructor from the generated code file. -> Create a new partial class for the DataContext with an empty constructor like below</p>\n\n<pre><code>Partial Class MyDataContext \n Public Sub New() \n MyBase.New(ConfigurationManager.ConnectionStrings(\"MyConnectionString\").ConnectionString, mappingSource)\n OnCreated() \n End Sub \nEnd Class\n</code></pre>\n" }, { "answer_id": 51161554, "author": "CoolBreeze", "author_id": 1303233, "author_profile": "https://Stackoverflow.com/users/1303233", "pm_score": 0, "selected": false, "text": "<p>Here's the C# version:</p>\n\n<pre><code>public partial class PENCILS_LinqToSql_DataClassesDataContext\n{\n public PENCILS_LinqToSql_DataClassesDataContext() : base(ConnectionString(), mappingSource)\n {\n }\n\n public static String ConnectionString()\n {\n String CS;\n String Key;\n\n Key = System.Configuration.ConfigurationManager.AppSettings[\"DefaultConnectionString\"].ToString();\n\n /// Get the actual connection string.\n CS = System.Configuration.ConfigurationManager.ConnectionStrings[Key].ToString();\n\n return CS;\n }\n}\n</code></pre>\n" } ]
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 ended up making two versions of the report.</p>\n" }, { "answer_id": 86991, "author": "Liron Yahdav", "author_id": 62, "author_profile": "https://Stackoverflow.com/users/62", "pm_score": 3, "selected": true, "text": "<p>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.</p>\n\n<p>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:</p>\n\n<pre><code>ReportViewer1.ServerReport.SetParameters(New ReportParameter() {New ReportParameter(\"ExportView\", \"True\")})\nReportViewer1.ServerReport.Refresh()\n</code></pre>\n\n<p>Then you need to programmatically export the report. See <a href=\"http://weblogs.asp.net/srkirkland/archive/2007/10/29/exporting-a-sql-server-reporting-services-2005-report-directly-to-pdf-or-excel.aspx\" rel=\"nofollow noreferrer\">this page</a> for an example of how to do that (ignore the first few lines of code that create and initialize a ReportViewer).</p>\n" } ]
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, you have to keep supporting the underlying interface. If you could add a setter, you would effectively be adding a new method, which would remain invisible to the outside world, as far as your classes' interface was concerned.</p>\n\n<p>True, adding a new method would not be breaking compatibility per se, but since it would remain hidden, decision to disallow this makes perfect sense.</p>\n" }, { "answer_id": 82469, "author": "petr k.", "author_id": 15497, "author_profile": "https://Stackoverflow.com/users/15497", "pm_score": -1, "selected": false, "text": "<p>Because that would break the concept of encapsulation and implementation hiding. Consider the case when you create a class, ship it, and then the consumer of your class makes himself able to set a property for which you originally provide a getter only. It would effectively disrupt any invariants of your class which you can depend on in your implementation.</p>\n" }, { "answer_id": 82473, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": -1, "selected": true, "text": "<p>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.</p>\n\n<p>I'm with Microsoft on this one.<br>\nLet'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).\nNow with your derivation, my code may break. e.g.</p>\n\n<pre><code>public class BarProvider\n{ BaseClass _source;\n Bar _currentBar;\n\n public void setSource(BaseClass b)\n {\n _source = b;\n _currentBar = b.Bar;\n }\n\n public Bar getBar()\n { return _currentBar; }\n}\n</code></pre>\n\n<p>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 '<em>Be Open, avoid doing sneaky things and surprising people</em>'</p>\n\n<p><strong>Update</strong>: <em>Ilya Ryzhenkov asks 'Why don't interfaces play by the same rules then?'</em>\nHmm.. this gets muddier as I think about it.<br>\nAn interface is a contract that says 'expect an implementation to have a read property named Bar.' <strong>Personally</strong> 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'.</p>\n" }, { "answer_id": 82649, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 2, "selected": false, "text": "<p>You could perhaps go around the problem by creating a new property:</p>\n\n<pre><code>public new int Bar \n{ \n get { return 0; }\n set {} \n}\n\nint IBase.Bar { \n get { return Bar; }\n}\n</code></pre>\n" }, { "answer_id": 83037, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": -1, "selected": false, "text": "<p>Because a class that has a read-only property (no setter) probably has a good reason for it. There might not be any underlying datastore, for example. Allowing you to create a setter breaks the contract set forth by the class. It's just bad OOP.</p>\n" }, { "answer_id": 107900, "author": "Thomas Danecker", "author_id": 9632, "author_profile": "https://Stackoverflow.com/users/9632", "pm_score": 2, "selected": false, "text": "<p>I can understand all your points, but effectively, C# 3.0's automatic properties get useless in that case.</p>\n\n<p>You can't do anything like that:</p>\n\n<pre><code>public class ConcreteClass : BaseClass\n{\n public override int Bar\n {\n get;\n private set;\n }\n}\n</code></pre>\n\n<p>IMO, C# should not restrict such scenarios. It's the responsibility of the developer to use it accordingly.</p>\n" }, { "answer_id": 2571197, "author": "Roman Starkov", "author_id": 33080, "author_profile": "https://Stackoverflow.com/users/33080", "pm_score": 5, "selected": false, "text": "<p>I think the main reason is simply that the syntax is too explicit for this to work any other way. This code:</p>\n<pre><code>public override int MyProperty { get { ... } set { ... } }\n</code></pre>\n<p>is quite explicit that both the <code>get</code> and the <code>set</code> are overrides. There is no <code>set</code> in the base class, so the compiler complains. Just like you can't override a method that's not defined in the base class, you can't override a setter either.</p>\n<p>You might say that the compiler should guess your intention and only apply the override to the method that can be overridden (i.e. the getter in this case), but this goes against one of the C# design principles - that the compiler must not guess your intentions, because it may guess wrong without you knowing.</p>\n<p>I think the following syntax might do nicely, but as Eric Lippert keeps saying, implementing even a minor feature like this is still a major amount of effort...</p>\n<pre><code>public int MyProperty\n{\n override get { ... } // not valid C#\n set { ... }\n}\n</code></pre>\n<p>or, for autoimplemented properties,</p>\n<pre><code>public int MyProperty { override get; set; } // not valid C#\n</code></pre>\n" }, { "answer_id": 3538759, "author": "mbolt35", "author_id": 427137, "author_profile": "https://Stackoverflow.com/users/427137", "pm_score": -1, "selected": false, "text": "<p>This is not impossible. You simply have to use the \"new\" keyword in your property. For example,</p>\n\n<pre><code>namespace {\n public class Base {\n private int _baseProperty = 0;\n\n public virtual int BaseProperty {\n get {\n return _baseProperty;\n }\n }\n\n }\n\n public class Test : Base {\n private int _testBaseProperty = 5;\n\n public new int BaseProperty {\n get {\n return _testBaseProperty;\n }\n set {\n _testBaseProperty = value;\n }\n }\n }\n}\n</code></pre>\n\n<p>It appears as if this approach satisfies both sides of this discussion. Using \"new\" breaks the contract between the base class implementation and the subclass implementation. This is necessary when a Class can have multiple contracts (either via interface or base class). </p>\n\n<p>Hope this helps</p>\n" }, { "answer_id": 3678456, "author": "JJJ", "author_id": 5547, "author_profile": "https://Stackoverflow.com/users/5547", "pm_score": 4, "selected": false, "text": "<p>I stumbled across the very same problem today and I think I have a very valid reason for wanting this.</p>\n<p>First I'd like to argue that having a get-only property doesn't necessarily translate into read-only. I interpret it as &quot;From this interface/abstract class you can get this value&quot;, that doesn't mean that some implementation of that interface/abstract class won't need the user/program to set this value explicitly. Abstract classes serve the purpose of implementing part of the needed functionality. I see absolutely no reason why an inherited class couldn't add a setter without violating any contracts.</p>\n<p>The following is a simplified example of what I needed today. I ended up having to add a setter in my interface just to get around this. The reason for adding the setter and not adding, say, a SetProp method is that one particular implementation of the interface used DataContract/DataMember for serialization of Prop, which would have been made needlessly complicated if I had to add another property just for the purpose of serialization.</p>\n<pre><code>interface ITest\n{\n // Other stuff\n string Prop { get; }\n}\n\n// Implements other stuff\nabstract class ATest : ITest\n{\n abstract public string Prop { get; }\n}\n\n// This implementation of ITest needs the user to set the value of Prop\nclass BTest : ATest\n{\n string foo = &quot;BTest&quot;;\n public override string Prop\n {\n get { return foo; }\n set { foo = value; } // Not allowed. 'BTest.Prop.set': cannot override because 'ATest.Prop' does not have an overridable set accessor\n }\n}\n\n// This implementation of ITest generates the value for Prop itself\nclass CTest : ATest\n{\n string foo = &quot;CTest&quot;;\n public override string Prop\n {\n get { return foo; }\n // set; // Not needed\n }\n}\n</code></pre>\n<p>I know this is just a &quot;my 2 cents&quot; post, but I feel with the original poster and trying to rationalize that this is a good thing seems odd to me, especially considering that the same limitations doesn't apply when inheriting directly from an interface.</p>\n<p>Also the mention about using new instead of override does not apply here, it simply doesn't work and even if it did it wouldn't give you the result wanted, namely a virtual getter as described by the interface.</p>\n" }, { "answer_id": 8556640, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 1, "selected": false, "text": "<p>The problem is that for whatever reason Microsoft decided that there should be three distinct types of properties: read-only, write-only, and read-write, only one of which may exist with a given signature in a given context; properties may only be overridden by identically-declared properties. To do what you want it would be necessary to create two properties with the same name and signature--one of which was read-only, and one of which was read-write.</p>\n\n<p>Personally, I wish that the whole concept of \"properties\" could be abolished, except that property-ish syntax could be used as syntactic sugar to call \"get\" and \"set\" methods. This would not only facilitate the 'add set' option, but would also allow for 'get' to return a different type from 'set'. While such an ability wouldn't be used terribly often, it could sometimes be useful to have a 'get' method return a wrapper object while the 'set' could accept either a wrapper or actual data.</p>\n" }, { "answer_id": 11470747, "author": "Remco te Wierik", "author_id": 778986, "author_profile": "https://Stackoverflow.com/users/778986", "pm_score": -1, "selected": false, "text": "<p>A read-only property in the base class indicates that this property represents a value that can always be determined from within the class (for example an enum value matching the (db-)context of an object). So the responsibillity of determining the value stays within the class. </p>\n\n<p>Adding a setter would cause an awkward issue here: \nA validation error should occur if you set the value to anything else than the single possible value it already has.</p>\n\n<p>Rules often have exceptions, though. It is very well possible that for example in one derived class the context narrows the possible enum values down to 3 out of 10, yet the user of this object still needs to decide which one is correct. The derived class needs to delegate the responsibillity of determining the value to the user of this object.\n<strong>Important to realize</strong> is that the user of this object <strong>should be well aware of this exception</strong> and assume the responsibillity to set the correct value.</p>\n\n<p>My solution in these kind of situations would be to leave the property read-only and add a new read-write property to the derived class to support the exception.\nThe override of the original property will simply return the value of the new property.\nThe new property can have a proper name indicating the context of this exception properly.</p>\n\n<p>This also supports the valid remark: \"make it as hard as possible for misunderstandings to crop up\" by Gishu.</p>\n" }, { "answer_id": 12414581, "author": "T.Tobler", "author_id": 1669770, "author_profile": "https://Stackoverflow.com/users/1669770", "pm_score": 4, "selected": false, "text": "<p>I agree that not being able to override a getter in a derived type is an anti-pattern. Read-Only specifies lack of implementation, not a contract of a pure functional (implied by the top vote answer).</p>\n\n<p>I suspect Microsoft had this limitation either because the same misconception was promoted, or perhaps because of simplifying grammar; though, now that scope can be applied to get or set individually, perhaps we can hope override can be too.</p>\n\n<p>The misconception indicated by the top vote answer, that a read-only property should somehow be more \"pure\" than a read/write property is ridiculous. Simply look at many common read only properties in the framework; the value is not a constant / purely functional; for example, DateTime.Now is read-only, but anything but a pure functional value. An attempt to 'cache' a value of a read only property assuming it will return the same value next time is risky.</p>\n\n<p>In any case, I've used one of the following strategies to overcome this limitation; both are less than perfect, but will allow you to limp beyond this language deficiency:</p>\n\n<pre><code> class BaseType\n {\n public virtual T LastRequest { get {...} }\n }\n\n class DerivedTypeStrategy1\n {\n /// get or set the value returned by the LastRequest property.\n public bool T LastRequestValue { get; set; }\n\n public override T LastRequest { get { return LastRequestValue; } }\n }\n\n class DerivedTypeStrategy2\n {\n /// set the value returned by the LastRequest property.\n public bool SetLastRequest( T value ) { this._x = value; }\n\n public override T LastRequest { get { return _x; } }\n\n private bool _x;\n }\n</code></pre>\n" }, { "answer_id": 17267865, "author": "user2514880", "author_id": 2514880, "author_profile": "https://Stackoverflow.com/users/2514880", "pm_score": 0, "selected": false, "text": "<p>Here is a work-around in order to achieve this using Reflection:</p>\n\n<pre><code>var UpdatedGiftItem = // object value to update;\n\nforeach (var proInfo in UpdatedGiftItem.GetType().GetProperties())\n{\n var updatedValue = proInfo.GetValue(UpdatedGiftItem, null);\n var targetpropInfo = this.GiftItem.GetType().GetProperty(proInfo.Name);\n targetpropInfo.SetValue(this.GiftItem, updatedValue,null);\n}\n</code></pre>\n\n<p>This way we can set object value on a property that is readonly. Might not work in all the scenarios though!</p>\n" }, { "answer_id": 22210422, "author": "Nat", "author_id": 1755715, "author_profile": "https://Stackoverflow.com/users/1755715", "pm_score": 5, "selected": false, "text": "<h1>It's possible.</h1>\n<p><strong><em>tl;dr</em>–</strong> You can override a get-only method with a setter if you want. It's basically just:</p>\n<ol>\n<li><p>Create a <code>new</code> property that has both a <code>get</code> and a <code>set</code> using the same name.</p>\n</li>\n<li><p><code>override</code> the prior <code>get</code> to alias the new <code>get</code>.</p>\n</li>\n</ol>\n<p>This enables us to override properties with <code>get</code>/<code>set</code> even if they lacked a setter in their base definition.</p>\n<hr />\n<h3>Situation: Pre-existing <code>get</code>-only property.</h3>\n<p>You have some class structure that you can't modify. Maybe it's just one class, or it's a pre-existing inheritance tree. Whatever the case, you want to add a <code>set</code> method to a property, but can't.</p>\n<pre><code>public abstract class A // Pre-existing class; can't modify\n{\n public abstract int X { get; } // You want a setter, but can't add it.\n}\npublic class B : A // Pre-existing class; can't modify\n{\n public override int X { get { return 0; } }\n}\n</code></pre>\n<hr />\n<h3>Problem: Can't <code>override</code> the <code>get</code>-only with <code>get</code>/<code>set</code>.</h3>\n<p>You want to <code>override</code> with a <code>get</code>/<code>set</code> property, but it won't compile.</p>\n<pre><code>public class C : B\n{\n private int _x;\n public override int X\n {\n get { return _x; }\n set { _x = value; } // Won't compile\n }\n}\n</code></pre>\n<hr />\n<h3>Solution: Use an <code>abstract</code> intermediate layer.</h3>\n<p>While you can't directly <code>override</code> with a <code>get</code>/<code>set</code> property, you <em>can</em>:</p>\n<ol>\n<li><p>Create a <code>new</code> <code>get</code>/<code>set</code> property with the same name.</p>\n</li>\n<li><p><code>override</code> the old <code>get</code> method with an accessor to the new <code>get</code> method to ensure consistency.</p>\n</li>\n</ol>\n<p>So, first you write the <code>abstract</code> intermediate layer:</p>\n<pre><code>public abstract class C : B\n{\n // Seal off the old getter. From now on, its only job\n // is to alias the new getter in the base classes.\n public sealed override int X { get { return this.XGetter; } }\n protected abstract int XGetter { get; }\n}\n</code></pre>\n<p>Then, you write the class that wouldn't compile earlier. It'll compile this time because you're not actually <code>override</code>'ing the <code>get</code>-only property; instead, you're replacing it using the <code>new</code> keyword.</p>\n<pre><code>public class D : C\n{\n private int _x;\n public new virtual int X\n {\n get { return this._x; }\n set { this._x = value; }\n }\n\n // Ensure base classes (A,B,C) use the new get method.\n protected sealed override int XGetter { get { return this.X; } }\n}\n</code></pre>\n<hr />\n<h3>Result: Everything works!</h3>\n<pre><code>var d = new D();\n\nvar a = d as A;\nvar b = d as B;\nvar c = d as C;\n\nPrint(a.X); // Prints &quot;0&quot;, the default value of an int.\nPrint(b.X); // Prints &quot;0&quot;, the default value of an int.\nPrint(c.X); // Prints &quot;0&quot;, the default value of an int.\nPrint(d.X); // Prints &quot;0&quot;, the default value of an int.\n\n// a.X = 7; // Won't compile: A.X doesn't have a setter.\n// b.X = 7; // Won't compile: B.X doesn't have a setter.\n// c.X = 7; // Won't compile: C.X doesn't have a setter.\nd.X = 7; // Compiles, because D.X does have a setter.\n\nPrint(a.X); // Prints &quot;7&quot;, because 7 was set through D.X.\nPrint(b.X); // Prints &quot;7&quot;, because 7 was set through D.X.\nPrint(c.X); // Prints &quot;7&quot;, because 7 was set through D.X.\nPrint(d.X); // Prints &quot;7&quot;, because 7 was set through D.X.\n</code></pre>\n<hr />\n<h3>Discussion.</h3>\n<p>This method allows you to add <code>set</code> methods to <code>get</code>-only properties. You can also use it to do stuff like:</p>\n<ol>\n<li><p>Change any property into a <code>get</code>-only, <code>set</code>-only, or <code>get</code>-and-<code>set</code> property, regardless of what it was in a base class.</p>\n</li>\n<li><p>Change the return type of a method in derived classes.</p>\n</li>\n</ol>\n<p>The main drawbacks are that there's more coding to do and an extra <code>abstract class</code> in the inheritance tree. This can be a bit annoying with constructors that take parameters because those have to be copy/pasted in the intermediate layer.</p>\n<hr />\n<h3>Bonus: You can change the property's return-type.</h3>\n<p>As a bonus, you can also change the return type if you want.</p>\n<ul>\n<li><p>If the base definition was <code>get</code>-only, then you can use a more-derived return type.</p>\n</li>\n<li><p>If the base definition was <code>set</code>-only, then you can use a less-derived return type.</p>\n</li>\n<li><p>If the base definition was already <code>get</code>/<code>set</code>, then:</p>\n<ul>\n<li><p>you can use a more-derived return type <strong><em>if</em></strong> you make it <code>set</code>-only;</p>\n</li>\n<li><p>you can use a less-derived return type <strong><em>if</em></strong> you make it <code>get</code>-only.</p>\n</li>\n</ul>\n</li>\n</ul>\n<p>In all cases, you can keep the same return type if you want.</p>\n" }, { "answer_id": 33289850, "author": "Suamere", "author_id": 1831054, "author_profile": "https://Stackoverflow.com/users/1831054", "pm_score": 0, "selected": false, "text": "<p>You should alter your question title to either detail that your question is solely in regards to overriding an abstract property, or that your question is in regards to generally overriding a class's get-only property.</p>\n\n<hr>\n\n<p><strong>If the former</strong> (overriding an abstract property)</p>\n\n<p>That code is useless. A base class alone shouldn't tell you that you're forced to override a Get-Only property (Perhaps an Interface). A base class provides common functionality which may require specific input from an implementing class. Therefore, the common functionality may make calls to abstract properties or methods. In the given case, the common functionality methods should be asking for you to override an abstract method such as:</p>\n\n<pre><code>public int GetBar(){}\n</code></pre>\n\n<p>But if you have no control over that, and the functionality of the base class reads from its own public property (weird), then just do this:</p>\n\n<pre><code>public abstract class BaseClass\n{\n public abstract int Bar { get; }\n}\n\npublic class ConcreteClass : BaseClass\n{\n private int _bar;\n public override int Bar\n {\n get { return _bar; }\n }\n public void SetBar(int value)\n {\n _bar = value;\n }\n}\n</code></pre>\n\n<p>I want to point out the (weird) comment: I would say a best-practice is for a class to not use its own public properties, but to use its private/protected fields when they exist. So this is a better pattern:</p>\n\n<pre><code>public abstract class BaseClass {\n protected int _bar;\n public int Bar { get { return _bar; } }\n protected void DoBaseStuff()\n {\n SetBar();\n //Do something with _bar;\n }\n protected abstract void SetBar();\n}\n\npublic class ConcreteClass : BaseClass {\n protected override void SetBar() { _bar = 5; }\n}\n</code></pre>\n\n<hr>\n\n<p><strong>If the latter</strong> (overriding a class's get-only property)</p>\n\n<p>Every non-abstract property has a setter. Otherwise it's useless and you shouldn't care to use it. Microsoft doesn't have to allow you to do what you want. Reason being: the setter exists in some form or another, and you can accomplish what you want <strong>Veerryy</strong> easily.</p>\n\n<p>The base class, or any class where you can read a property with <code>{get;}</code>, has <strong>SOME</strong> sort of exposed setter for that property. The metadata will look like this:</p>\n\n<pre><code>public abstract class BaseClass\n{\n public int Bar { get; }\n}\n</code></pre>\n\n<p>But the implementation will have two ends of the spectrum of complexity:</p>\n\n<p>Least Complex:</p>\n\n<pre><code>public abstract class BaseClass\n{\n private int _bar;\n public int Bar { \n get{\n return _bar;\n }}\n public void SetBar(int value) { _bar = value; }\n}\n</code></pre>\n\n<p>Most Complex:</p>\n\n<pre><code>public abstract class BaseClass\n{\n private int _foo;\n private int _baz;\n private int _wtf;\n private int _kthx;\n private int _lawl;\n\n public int Bar\n {\n get { return _foo * _baz + _kthx; }\n }\n public bool TryDoSomethingBaz(MyEnum whatever, int input)\n {\n switch (whatever)\n {\n case MyEnum.lol:\n _baz = _lawl + input;\n return true;\n case MyEnum.wtf:\n _baz = _wtf * input;\n break;\n }\n return false;\n }\n public void TryBlowThingsUp(DateTime when)\n {\n //Some Crazy Madeup Code\n _kthx = DaysSinceEaster(when);\n }\n public int DaysSinceEaster(DateTime when)\n {\n return 2; //&lt;-- calculations\n }\n}\npublic enum MyEnum\n{\n lol,\n wtf,\n}\n</code></pre>\n\n<p>My point being, either way, you have the setter exposed. In your case, you may want to override <code>int Bar</code> because you don't want the base class to handle it, don't have access to review how it's handling it, or were tasked to hax some code real quick'n'dirty against your will.</p>\n\n<p><strong>In both Latter and Former</strong> (Conclusion)</p>\n\n<p>Long-Story Short: It isn't necessary for Microsoft to change anything. You can choose how your implementing class is set up and, sans the constructor, use all or none of the base class.</p>\n" }, { "answer_id": 46651924, "author": "lxa", "author_id": 167195, "author_profile": "https://Stackoverflow.com/users/167195", "pm_score": 0, "selected": false, "text": "<p>Solution for only a small subset of use cases, but nevertheless: in C# 6.0 \"readonly\" setter is automatically added for overridden getter-only properties.</p>\n\n<pre><code>public abstract class BaseClass\n{\n public abstract int Bar { get; }\n}\n\npublic class ConcreteClass : BaseClass\n{\n public override int Bar { get; }\n\n public ConcreteClass(int bar)\n {\n Bar = bar;\n }\n}\n</code></pre>\n" } ]
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&lt;SimpleObj&gt; is not in the inheritance tree of IQueryable&lt;IPrimaryKey&gt;</p>\n" }, { "answer_id": 85461, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 2, "selected": false, "text": "<p>Edit: <a href=\"https://stackoverflow.com/questions/82442/extension-methods-not-working-for-an-interface#85503\">Konrad</a>'s solution is better because its far simpler. The below solution works but is only required in situations similar to ObjectDataSource where a method of a class is retrieved through reflection without walking up the inheritance hierarchy. Obviously that's not happening here.</p>\n\n<p>This is possible, I've had to implement a similar pattern when I designed a custom entity framework solution for working with ObjectDataSource:</p>\n\n<pre><code>public interface IPrimaryKey&lt;T&gt; where T : IPrimaryKey&lt;T&gt;\n{\n int Id { get; }\n}\n\npublic static class IPrimaryKeyTExtension\n{\n public static IPrimaryKey&lt;T&gt; GetById&lt;T&gt;(this IQueryable&lt;T&gt; source, int id) where T : IPrimaryKey&lt;T&gt;\n {\n return source.Where(pk =&gt; pk.Id == id).SingleOrDefault();\n }\n}\n\npublic class Person : IPrimaryKey&lt;Person&gt;\n{\n public int Id { get; set; }\n}\n</code></pre>\n\n<p>Snippet of use:</p>\n\n<pre><code>var people = new List&lt;Person&gt;\n{\n new Person { Id = 1 },\n new Person { Id = 2 },\n new Person { Id = 3 }\n};\n\nvar personOne = people.AsQueryable().GetById(1);\n</code></pre>\n" }, { "answer_id": 85503, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": true, "text": "<p>It works, when done right. cfeduke's solution works. However, you don't have to make the <code>IPrimaryKey</code> interface generic, in fact, you don't have to change your original definition at all:</p>\n\n<pre><code>public static IPrimaryKey GetByID&lt;T&gt;(this IQueryable&lt;T&gt; source, int id) where T : IPrimaryKey\n{\n return source(obj =&gt; obj.ID == id);\n}\n</code></pre>\n" } ]
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 caught.</p>\n" }, { "answer_id": 82531, "author": "Mendelt", "author_id": 3320, "author_profile": "https://Stackoverflow.com/users/3320", "pm_score": 2, "selected": false, "text": "<p>You can use the AppDomain.CurrentDomain.UnhandledException to get an event.</p>\n" }, { "answer_id": 82536, "author": "Drejc", "author_id": 6482, "author_profile": "https://Stackoverflow.com/users/6482", "pm_score": 3, "selected": false, "text": "<p>The <strong>Global.asax</strong> class is your last line of defense.\nLook at: </p>\n\n<pre><code>protected void Application_Error(Object sender, EventArgs e)\n</code></pre>\n\n<p>method</p>\n" }, { "answer_id": 82558, "author": "petr k.", "author_id": 15497, "author_profile": "https://Stackoverflow.com/users/15497", "pm_score": 2, "selected": false, "text": "<p>You may also go with Application.ThreadException Event.</p>\n\n<p>Once I was developing a .NET app running inside a COM based application; this event was the very useful, as AppDomain.CurrentDomain.UnhandledException didn't work in this case.</p>\n" }, { "answer_id": 82583, "author": "hangy", "author_id": 11963, "author_profile": "https://Stackoverflow.com/users/11963", "pm_score": 1, "selected": false, "text": "<p>I think you should rather not even catch all Exception but better let them be shown to the user. The reason for this is that you should only catch Exceptions which you can actually handle. If you run into some Exception which causes the program to stop but still catch it, this might cause much more severe problems.\nAlso read <a href=\"http://blogs.msdn.com/fxcop/archive/2006/06/14/631923.aspx\" rel=\"nofollow noreferrer\">FAQ: Why does FxCop warn against catch(Exception)?</a>.</p>\n" }, { "answer_id": 82712, "author": "Peli", "author_id": 14403, "author_profile": "https://Stackoverflow.com/users/14403", "pm_score": 3, "selected": false, "text": "<p>Be aware that some exception are dangerous to catch - or mostly uncatchable, </p>\n\n<ul>\n<li>OutOfMemoryException: anything you do in the catch handler might allocate memory (in the managed or unmanaged side of the CLR) and thus trigger another OOM</li>\n<li>StackOverflowException: depending whether the CLR detected it sufficiently early, you might get notified. Worst case scenario, it simply kills the process.</li>\n</ul>\n" }, { "answer_id": 83357, "author": "Johnny Bravado", "author_id": 12222, "author_profile": "https://Stackoverflow.com/users/12222", "pm_score": 1, "selected": false, "text": "<p>Be aware that catching these unhandled exceptions can change the security requirements of your application. Your application may stop running correctly under certain contexts (when run from a network share, etc.). Be sure to test thoroughly.</p>\n" }, { "answer_id": 83391, "author": "Ricardo Amores", "author_id": 10136, "author_profile": "https://Stackoverflow.com/users/10136", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://www.codeproject.com/KB/exception/ExceptionHandling.aspx\" rel=\"noreferrer\">This article in codeproject by our host Jeff Atwood</a> is what you need. \nIncludes the code to catch unhandled exceptions and best pratices for showing information about the crash to the user.</p>\n" }, { "answer_id": 83745, "author": "Dario Solera", "author_id": 16026, "author_profile": "https://Stackoverflow.com/users/16026", "pm_score": 2, "selected": false, "text": "<p>Although catching <strong>all</strong> exceptions without the plan to properly handle them is surely a bad practice, I think that an application should fail in some graceful way. A crash should not scare the user to death, and at least it should display a description of the error, some information to report to the tech support stuff, and ideally a button to close the application and restart it. In an ideal world, the application should be able to dump on disk the user data, and then try to recover it (but I see that this is asking too much).</p>\n\n<p>Anyway, I usually use:</p>\n\n<pre><code>AppDomain.CurrentDomain.UnhandledException\n</code></pre>\n" }, { "answer_id": 83995, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "<p>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.</p>\n\n<p>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).</p>\n\n<p>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.</p>\n" }, { "answer_id": 306262, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 0, "selected": false, "text": "<p>it doesn't hurt to use both\n AppDomain.CurrentDomain.UnhandledException \n Application.ThreadException</p>\n\n<p>but keep in mind that exceptions on secondary threads are not caught by these handlers; use <a href=\"http://www.codeproject.com/KB/threads/SafeThread.aspx\" rel=\"nofollow noreferrer\">SafeThread</a> for secondary threads if needed</p>\n" } ]
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, "author": "Olaf Kock", "author_id": 13447, "author_profile": "https://Stackoverflow.com/users/13447", "pm_score": 0, "selected": false, "text": "<p>svn:// doesn't talk http, therefor there's nothing a http proxy could do.</p>\n\n<p>Any reason why http doesn't work? Have you considered https? If you really need it, you probably have to have port 3690 opened in your firewall.</p>\n" }, { "answer_id": 82587, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": "<p>If you can get SSH to it you can an SSH Port-forwarded SVN server. </p>\n\n<p>Use <code>SSHs -L</code> ( or <code>-R</code> , I forget, it always confuses me ) to make an ssh tunnel so that </p>\n\n<p><code>127.0.0.1:3690</code> is really connecting to remote:3690 over the ssh tunnel, and then you can use it via </p>\n\n<pre><code>svn co svn://127.0.0.1/....\n</code></pre>\n" }, { "answer_id": 82600, "author": "rami", "author_id": 9629, "author_profile": "https://Stackoverflow.com/users/9629", "pm_score": 7, "selected": true, "text": "<p>In <code>/etc/subversion/servers</code> you are setting <code>http-proxy-host</code>, which has nothing to do with <code>svn://</code> which connects to a different server usually running on port 3690 started by <code>svnserve</code> command.</p>\n\n<p>If you have access to the server, you can setup <code>svn+ssh://</code> as <a href=\"http://svnbook.red-bean.com/en/1.0/ch06s03.html\" rel=\"noreferrer\">explained here.</a></p>\n\n<p><strong>Update</strong>: You could also try using <a href=\"http://search.cpan.org/~book/Net-Proxy-0.12/script/connect-tunnel\" rel=\"noreferrer\"><code>connect-tunnel</code></a>, which uses your HTTPS proxy server to tunnel connections:</p>\n\n<pre><code>connect-tunnel -P proxy.company.com:8080 -T 10234:svn.example.com:3690\n</code></pre>\n\n<p>Then you would use</p>\n\n<pre><code>svn checkout svn://localhost:10234/path/to/trunk\n</code></pre>\n" }, { "answer_id": 82601, "author": "massimogentilini", "author_id": 11673, "author_profile": "https://Stackoverflow.com/users/11673", "pm_score": 0, "selected": false, "text": "<p>If you're using the standard SVN installation the svn:// connection will work on tcpip port 3690 and so it's basically impossible to connect unless you change your network configuration (you said only Http traffic is allowed) or you install the http module and Apache on the server hosting your SVN server.</p>\n" }, { "answer_id": 2861599, "author": "gadgetweb.de", "author_id": 344549, "author_profile": "https://Stackoverflow.com/users/344549", "pm_score": 1, "selected": false, "text": "<p>Okay, this topic is somewhat outdated, but as I found it on google and have a solution this might be interesting for someone:</p>\n\n<p>Basically (of course) this is not possible on every http proxy but works on proxies allowing http connect on port 3690. This method is used by http proxies on port 443 to provide a way for secure https connections. If your administrator configures the proxy to open port 3690 for http connect you can setup your local machine to establish a tunnel through the proxy.</p>\n\n<p>I just was in the need to check out some files from svn.openwrt.org within our companies network. An easy solution to create a tunnel is adding the following line to your /etc/hosts</p>\n\n<p>127.0.0.1 svn.openwrt.org</p>\n\n<p>Afterwards, you can use socat to create a tcp tunnel to a local port:</p>\n\n<p>while true; do socat tcp-listen:3690 proxy:proxy.at.your.company:svn.openwrt.org:3690; done</p>\n\n<p>You should execute the command as root. It opens the local port 3690 and on connection creates a tunnel to svn.openwrt.org on the same port.</p>\n\n<p>Just replace the port and server addresses on your own needs.</p>\n" }, { "answer_id": 3789496, "author": "dillera", "author_id": 457556, "author_profile": "https://Stackoverflow.com/users/457556", "pm_score": 6, "selected": false, "text": "<p>Ok, this should be really easy:</p>\n\n<pre><code>$ sudo vi /etc/subversion/servers\n</code></pre>\n\n<p>Edit the file:</p>\n\n<pre><code>[Global]\nhttp-proxy-host=my.proxy.com\nhttp-proxy-port=3128\n</code></pre>\n\n<p>Save it, run <code>svn</code> again and it will work.</p>\n" } ]
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": 37660167, "author": "dlabs", "author_id": 2000886, "author_profile": "https://Stackoverflow.com/users/2000886", "pm_score": 2, "selected": false, "text": "<p>I was able to properly use the macro BOOST_CLASS_VERSION until I encapsulated it inside a namespace. Compilation errors returned were:</p>\n\n<pre><code>error C2988: unrecognizable template declaration/definition\nerror C2143: syntax error: missing ';' before '&lt;'\nerror C2913: explicit specialization; 'Romer::RDS::Settings::boost::serialization::version' is not a specialization of a class template\nerror C2059: syntax error: '&lt;'\nerror C2143: syntax error: missing ';' before '{'\nerror C2447: '{': missing function header (old-style formal list?)\n</code></pre>\n\n<p>As suggested in a previous edit, moving BOOST_CLASS_VERSION to global scope solved the issue. I would prefer keeping the macro close to the referenced structure.</p>\n" }, { "answer_id": 70143058, "author": "alfC", "author_id": 225186, "author_profile": "https://Stackoverflow.com/users/225186", "pm_score": 0, "selected": false, "text": "<p>To avoid premature dependency of your library on Boost.Serialization you can forward declare:</p>\n<pre><code>namespace boost {\nnamespace serialization {\n\ntemplate&lt;typename T&gt; struct version;\n\n} // end namespace serialization\n} // end namespace boost\n</code></pre>\n<p>Instead of including the header.\nTo declare the version of you class you can do:</p>\n<pre><code>namespace boost {\nnamespace serialization {\ntemplate&lt;typename T, int D, class A&gt;\nstruct version&lt; your_type&lt;T, D, A&gt; &gt; {\n enum { value = 16 };\n};\n} // end namespace serialization\n} // end namespace boost\n</code></pre>\n<p>Since it doesn't use the <code>BOOST_CLASS_VERSION</code> macro still doesn't need premature inclusion of the Boost.Serialization headers.</p>\n<p>(for some reason <code>static const [constexpr] unsigned int value = 16;</code> doesn't work for me, in C++14).</p>\n" } ]
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" }, { "answer_id": 84448, "author": "bortzmeyer", "author_id": 15625, "author_profile": "https://Stackoverflow.com/users/15625", "pm_score": 2, "selected": false, "text": "<p>You probably mean RRSIG ANY (otherwise, the order is wrong, the class needs to be after the type)</p>\n\n<pre><code>&gt;&gt;&gt; print myresolver.query('sources.org', 'RRSIG', 'ANY')\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\n File \"/usr/lib/python2.5/site-packages/dns/resolver.py\", line 664, in query\n answer = Answer(qname, rdtype, rdclass, response)\n File \"/usr/lib/python2.5/site-packages/dns/resolver.py\", line 121, in __init__\n raise NoAnswer\ndns.resolver.NoAnswer\n</code></pre>\n" }, { "answer_id": 114923, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 0, "selected": false, "text": "<p>This looks like a probable bug in the Python DNS library, although I don't read Python well enough to find it.</p>\n\n<p>Note that in any case your EDNS0 buffer size parameter is not large enough to handle the RRSIG records for sources.org, so your client and server would have to fail over to TCP/IP.</p>\n" }, { "answer_id": 37234210, "author": "Babak Farrokhi", "author_id": 5711389, "author_profile": "https://Stackoverflow.com/users/5711389", "pm_score": 0, "selected": false, "text": "<p>You may want to use <code>raise_on_no_answer=False</code> and you will get the correct response:</p>\n\n<pre><code>resolver.query(hostname, dnsrecord, raise_on_no_answer=False)\n</code></pre>\n" }, { "answer_id": 42237591, "author": "Abhinandan Dubey", "author_id": 5102599, "author_profile": "https://Stackoverflow.com/users/5102599", "pm_score": 1, "selected": false, "text": "<p>RRSIG is not a record, it's a hashed digest of a valid DNS Record. You can query a DNSKEY record, set want_dnssec=True and get a DNSKEY Record, and an \"RRSIG of a DNSKEY Record\".</p>\n\n<p>More generally, RRSIG is just a signature of a valid record (such as a DS Record).</p>\n\n<p>So when you ask the server </p>\n\n<pre><code>myresolver.query('sources.org', 'RRSIG')\n</code></pre>\n\n<p>It doesn't know what you are asking for. RRSIG in itself has no meaning, you need to specify <em>RRSIG of what?</em></p>\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" }, { "answer_id": 84448, "author": "bortzmeyer", "author_id": 15625, "author_profile": "https://Stackoverflow.com/users/15625", "pm_score": 2, "selected": false, "text": "<p>You probably mean RRSIG ANY (otherwise, the order is wrong, the class needs to be after the type)</p>\n\n<pre><code>&gt;&gt;&gt; print myresolver.query('sources.org', 'RRSIG', 'ANY')\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\n File \"/usr/lib/python2.5/site-packages/dns/resolver.py\", line 664, in query\n answer = Answer(qname, rdtype, rdclass, response)\n File \"/usr/lib/python2.5/site-packages/dns/resolver.py\", line 121, in __init__\n raise NoAnswer\ndns.resolver.NoAnswer\n</code></pre>\n" }, { "answer_id": 114923, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 0, "selected": false, "text": "<p>This looks like a probable bug in the Python DNS library, although I don't read Python well enough to find it.</p>\n\n<p>Note that in any case your EDNS0 buffer size parameter is not large enough to handle the RRSIG records for sources.org, so your client and server would have to fail over to TCP/IP.</p>\n" }, { "answer_id": 37234210, "author": "Babak Farrokhi", "author_id": 5711389, "author_profile": "https://Stackoverflow.com/users/5711389", "pm_score": 0, "selected": false, "text": "<p>You may want to use <code>raise_on_no_answer=False</code> and you will get the correct response:</p>\n\n<pre><code>resolver.query(hostname, dnsrecord, raise_on_no_answer=False)\n</code></pre>\n" }, { "answer_id": 42237591, "author": "Abhinandan Dubey", "author_id": 5102599, "author_profile": "https://Stackoverflow.com/users/5102599", "pm_score": 1, "selected": false, "text": "<p>RRSIG is not a record, it's a hashed digest of a valid DNS Record. You can query a DNSKEY record, set want_dnssec=True and get a DNSKEY Record, and an \"RRSIG of a DNSKEY Record\".</p>\n\n<p>More generally, RRSIG is just a signature of a valid record (such as a DS Record).</p>\n\n<p>So when you ask the server </p>\n\n<pre><code>myresolver.query('sources.org', 'RRSIG')\n</code></pre>\n\n<p>It doesn't know what you are asking for. RRSIG in itself has no meaning, you need to specify <em>RRSIG of what?</em></p>\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 remove it from the MRU list. So if you temporarily rename an appropriate top level folder to fake the projects' disappearance, you can get rid of the projects one by one.</p>\n" }, { "answer_id": 82758, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I found the <a href=\"http://www.codeproject.com/KB/cs/VSProjectListEditorIII.aspx\" rel=\"nofollow noreferrer\">MRU editor</a> from <a href=\"http://www.codeproject.com\" rel=\"nofollow noreferrer\">Code Project</a> a great tool for that. No problems with it, and it works on 2003, 2005, and 2008.</p>\n" }, { "answer_id": 84797, "author": "Dusty Campbell", "author_id": 2174, "author_profile": "https://Stackoverflow.com/users/2174", "pm_score": 7, "selected": true, "text": "<p>There is an MSDN article <a href=\"http://msdn.microsoft.com/en-us/library/aa991991.aspx\" rel=\"noreferrer\">here</a> which suggests that you just move the projects to a new directory.</p>\n\n<p>However, as you mentioned, the list of projects is kept in the registry under this key:</p>\n\n<pre><code>HKEY_CURRENT_USER\\Software\\Microsoft\\VisualStudio\\&lt;version&gt;\\ProjectMRUList\n</code></pre>\n\n<p>and the list of recent files is kept in this key:</p>\n\n<pre><code>HKEY_CURRENT_USER\\Software\\Microsoft\\VisualStudio\\&lt;version&gt;\\FILEMRUList\n</code></pre>\n\n<p><strong>Note For Visual Studio 2015:</strong><br/>\nThe location has changed. You can check out <a href=\"https://stackoverflow.com/a/33945037/62195\">this answer</a> for details.</p>\n\n<p>Some people have automated clearing this registry key with their own tools:<br/>\n<a href=\"http://www.codeplex.com/vsrecentfiles\" rel=\"noreferrer\">Visual Studio Most Recent Files Utility</a> <br />\n<a href=\"http://code.msdn.microsoft.com/CleanRecentListAddIn\" rel=\"noreferrer\">Add-in for cleaning Visual Studio 2008 MRU Projects list</a></p>\n" }, { "answer_id": 4405952, "author": "CoderHawk", "author_id": 206766, "author_profile": "https://Stackoverflow.com/users/206766", "pm_score": 4, "selected": false, "text": "<h2><a href=\"https://visualstudiogallery.msdn.microsoft.com/e5f41ad9-4edc-4912-bca3-91147db95b99\" rel=\"noreferrer\">PowerCommands for Visual Studio 2008</a></h2>\n<h3>Features</h3>\n<ul>\n<li>Clear Recent File List</li>\n<li>Clear Recent Project List</li>\n<li>Clear All Panes</li>\n<li>Copy Path</li>\n<li>Email CodeSnippet</li>\n<li>Insert Guid Attribute</li>\n<li>Show All Files</li>\n<li>Undo Close</li>\n<li>Collapse Projects</li>\n<li>Copy Class</li>\n<li>Paste Class</li>\n<li>Copy References</li>\n<li>Paste References</li>\n<li>Copy As Project Reference</li>\n<li>Edit Project File</li>\n<li>Open Containing Folder</li>\n<li>Open Command Prompt</li>\n<li>Unload Projects</li>\n<li>Reload Projects</li>\n<li>Remove and Sort Usings</li>\n<li>Extract Constant</li>\n<li>Transform Templates</li>\n<li>Close All</li>\n</ul>\n<p><img src=\"https://i.stack.imgur.com/G8BFv.png\" alt=\"alt text\" /></p>\n" }, { "answer_id": 11399351, "author": "Metro Smurf", "author_id": 9664, "author_profile": "https://Stackoverflow.com/users/9664", "pm_score": 2, "selected": false, "text": "<p><strong>Note</strong>: This answer is specific to Visual Studio 2010.</p>\n\n<p>If you don't want to manually edit the registry, you can use <a href=\"http://visualstudiogallery.msdn.microsoft.com/e5f41ad9-4edc-4912-bca3-91147db95b99/\" rel=\"nofollow\">PowerCommands for Visual Studio 2010</a>. </p>\n\n<blockquote>\n <p>PowerCommands 10.0 is a set of useful extensions for the Visual Studio\n 2010 adding additional functionality to various areas of the IDE.</p>\n</blockquote>\n\n<p>The specific command for clearing the registry from the extension is:</p>\n\n<blockquote>\n <p><strong>Clear Recent Project List</strong> This command clears the Visual Studio recent project list. The Clear Recent Project List command brings up a\n Clear File dialog which allows any or all recent projects to be\n selected.</p>\n</blockquote>\n\n<p>The PowerCommands can be installed with the Visual Studio extension manager: Tools > Extension Manager > Online Gallery: search for <em>PowerCommands for Visual Studio 2010</em>.</p>\n" }, { "answer_id": 22906432, "author": "user3505772", "author_id": 3505772, "author_profile": "https://Stackoverflow.com/users/3505772", "pm_score": 0, "selected": false, "text": "<p>Try Recently Used Files: a free addin for Visual Studio that manages MRU files on a per-project basis:\nSupported for VS 2010, 2012, 2013.</p>\n\n<p>For Visual Studio 2012, 2013:\n<a href=\"http://visualstudiogallery.msdn.microsoft.com/a61cbd1d-b5a2-490b-a6bb-f0ea3ecf214a\" rel=\"nofollow\">http://visualstudiogallery.msdn.microsoft.com/a61cbd1d-b5a2-490b-a6bb-f0ea3ecf214a</a></p>\n\n<p>For Visual Studio 2010:\n<a href=\"http://visualstudiogallery.msdn.microsoft.com/45283881-5a62-4dc1-8ffb-4cbc02709947\" rel=\"nofollow\">http://visualstudiogallery.msdn.microsoft.com/45283881-5a62-4dc1-8ffb-4cbc02709947</a></p>\n" }, { "answer_id": 29203225, "author": "user3909793", "author_id": 3909793, "author_profile": "https://Stackoverflow.com/users/3909793", "pm_score": 0, "selected": false, "text": "<p>For Visual Studio 2013: \nOpen the Run dialog (Press Win + R)\ntype: regedit\nnavigate to: HKEY_CURRENT_USER > Software > Microsoft > VisualStudio\nclick 12.0 then the files will show up on the right side.\nLook for the \"LastLoadedSolution\", right click then click Modify\nchange the value to 0.</p>\n\n<p>This worked for me.</p>\n" }, { "answer_id": 31514199, "author": "Riegardt Steyn", "author_id": 1904753, "author_profile": "https://Stackoverflow.com/users/1904753", "pm_score": 2, "selected": false, "text": "<p>In Visual Studio 2015 all the history lists (including search history, file MRU and project MRU) are now located at:</p>\n\n<p><code>HKEY_CURRENT_USER\\Software\\Microsoft\\VisualStudio\\14.0\\MRUItems</code></p>\n\n<p>You will see a different GUID folder for each list, and a sub-folder called <code>Items</code> in each of them. Find the <code>Items</code> folder that contains the relevant list, and just delete its parent GUID folder.</p>\n\n<p>Visual Studio will re-create the GUID folder together with a new <code>Items</code> child folder, next time it wants to add something to the list again.</p>\n" }, { "answer_id": 34122343, "author": "shjeff", "author_id": 5558393, "author_profile": "https://Stackoverflow.com/users/5558393", "pm_score": 0, "selected": false, "text": "<p>I'm not sure if this solution has been posted somewhere here, but if you have VS 2013 Update 5 you can open start page, and right click project below \"Recent\" list, and choose \"Remove from list\". I don't know how about other VS versions, maybe this feature is available.</p>\n" }, { "answer_id": 46815292, "author": "Alex Konnen", "author_id": 6272737, "author_profile": "https://Stackoverflow.com/users/6272737", "pm_score": 0, "selected": false, "text": "<p>I had this issue as applied to VS 2017 where you do not have any MRU items in the registry as in the previous versions. The solution was, on the other hand, simple: go to \"Tools->Extensions and Updates\" and install \"Power Commands for Visual Studio\". After they have been installed, your File menu will look as shown below.</p>\n\n<p><a href=\"https://i.stack.imgur.com/vfZRC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vfZRC.png\" alt=\"enter image description here\"></a></p>\n\n<p>Just click the menu item to clear the project MRU.</p>\n" } ]
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": 82762, "author": "Onorio Catenacci", "author_id": 2820, "author_profile": "https://Stackoverflow.com/users/2820", "pm_score": 0, "selected": false, "text": "<p>Off the top of my head, I'd say you need to create a new table with the same structure as the existing table but with your text column set to not null and then run a query to move the records from one to the other. </p>\n\n<p>I realize that's sort of a pseudocode answer but I think that's really the only option you've got. </p>\n\n<p>If others with a better grip on the exact TSQL syntax care to supplement this answer, feel free. </p>\n" }, { "answer_id": 82779, "author": "mattruma", "author_id": 1768, "author_profile": "https://Stackoverflow.com/users/1768", "pm_score": 0, "selected": false, "text": "<p>I would update all the columns with NULL values and set it to an empty string, for example, ''. Then you should be able to run your ALTER TABLE script with no problems. A lot less work than creating a new column.</p>\n" }, { "answer_id": 82802, "author": "baldy", "author_id": 2012, "author_profile": "https://Stackoverflow.com/users/2012", "pm_score": 0, "selected": false, "text": "<p>Try to generate the change script from within Enterprise Manager to see how it is done there</p>\n" }, { "answer_id": 82862, "author": "Sixto Saez", "author_id": 9711, "author_profile": "https://Stackoverflow.com/users/9711", "pm_score": 3, "selected": true, "text": "<p>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:</p>\n\n<pre><code> /* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/\nBEGIN TRANSACTION\nSET QUOTED_IDENTIFIER ON\nSET ARITHABORT ON\nSET NUMERIC_ROUNDABORT OFF\nSET CONCAT_NULL_YIELDS_NULL ON\nSET ANSI_NULLS ON\nSET ANSI_PADDING ON\nSET ANSI_WARNINGS ON\nCOMMIT\nBEGIN TRANSACTION\nGO\nCREATE TABLE dbo.Tmp_TestTable\n (\n tableKey int NOT NULL,\n Description varchar(50) NOT NULL,\n TextData text NOT NULL\n ) ON [PRIMARY]\n TEXTIMAGE_ON [PRIMARY]\nGO\nIF EXISTS(SELECT * FROM dbo.TestTable)\n EXEC('INSERT INTO dbo.Tmp_TestTable (tableKey, Description, TextData)\n SELECT tableKey, Description, TextData FROM dbo.TestTable WITH (HOLDLOCK TABLOCKX)')\nGO\nDROP TABLE dbo.TestTable\nGO\nEXECUTE sp_rename N'dbo.Tmp_TestTable', N'TestTable', 'OBJECT' \nGO\nALTER TABLE dbo.TestTable ADD CONSTRAINT\n PK_TestTable PRIMARY KEY CLUSTERED \n (\n tableKey\n ) ON [PRIMARY]\n\nGO\nCOMMIT\n</code></pre>\n" }, { "answer_id": 82976, "author": "cheeves", "author_id": 15826, "author_profile": "https://Stackoverflow.com/users/15826", "pm_score": 1, "selected": false, "text": "<p>I think getting rid of the null values is the easist.</p>\n\n<p>(as raz0rf1sh has said)</p>\n\n<pre><code>CREATE TABLE tmp1( col1 INT identity ( 1, 1 ), col2 TEXT ) \nGO \n\nINSERT \nINTO tmp1 \nSELECT NULL \n\nGO 10 \n\nSELECT * \nFROM tmp1 \n\nUPDATE tmp1 \nSET col2 = '' \nWHERE col2 IS NULL \n\nALTER TABLE tmp1 \nALTER COLUMN col2 TEXT NOT NULL \n\nSELECT *\nFROM tmp1 \n\nDROP TABLE tmp1 \n</code></pre>\n" } ]
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</li>\n<li>Navigate to the Shared Service Provider</li>\n<li>Under <b>User Profiles and My Sites</b> navigate to Personalization services permissions .</li>\n<li>If the account doesn't already exist, add the account for which your sites App Domain is running under.</li>\n<li>Grant that user <b>Manage user profiles</b> permission.</li>\n</ol>\n\n<p>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.</p>\n" }, { "answer_id": 161580, "author": "Jan Tielens", "author_id": 11399, "author_profile": "https://Stackoverflow.com/users/11399", "pm_score": 2, "selected": false, "text": "<p>There are two ways I've actually managed to accomplish this:</p>\n\n<ol>\n<li>Put the code that uses the UserProfileManager behind a web services layer. The web service should use an application pool identity that has access to the User Profile services.</li>\n<li>Use the impersonation technique describe in the following article:\n<a href=\"http://www.dotnetjunkies.com/WebLog/victorv/archive/2005/06/30/128890.aspx\" rel=\"nofollow noreferrer\">http://www.dotnetjunkies.com/WebLog/victorv/archive/2005/06/30/128890.aspx</a></li>\n</ol>\n" }, { "answer_id": 161907, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 2, "selected": false, "text": "<p>Thanks for the Answers. One Caveat: if you run the Application Pool as \"Network Service\" instead of a Domain Account, you're screwed.</p>\n\n<p>But then again, it's recommended to use a domain account anyway (On a test server I used network service, but after changing it to a domain account it worked).</p>\n" }, { "answer_id": 509830, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Here's the answer. Its a stupid Microsoft bug, and there is a hotfix. I'm downloading now to test it.</p>\n\n<p><a href=\"http://support.microsoft.com/kb/952294/en-us\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/952294/en-us</a></p>\n" } ]
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 SOS to clean up the stack and post it here to help us along.</p>\n\n<p>Or you can use Visual Studio by enabling the trap of all exceptions. Go to \"Debug\" and then \"Exceptions\" and make sure you trap everything. Do this along with switching the debugger to mixed-mode (managed and unmanaged).</p>\n\n<p>Once you have the stack trace, we can determine the answer.</p>\n\n<p>A process doesn't exit on Windows without an exception. It's in there. Also, you might want to check the machine's Event Log to see if anything has shown up.</p>\n" }, { "answer_id": 83434, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 1, "selected": false, "text": "<p>The event viewer shows HRESULT 0xc0000005 \"Reading or writing to an inaccessible memory location.\" (STATUS_ACCESS_VIOLATION)</p>\n\n<p>See my edit above for more details; reproing this takes a while so I can't get a fresh crash dump for WinDBG for a little while.</p>\n" }, { "answer_id": 86848, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 0, "selected": false, "text": "<p>The solution is to use Microsoft.VisualBasic.Devices, which does not suffer from this bug. Since it's Vista only, and the Event Viewer even managed to fail midway through logging the crash (process id 0x**%9** should have a hex value there instead), I point the blame at the new sound code in Vista.</p>\n\n<p>BTW, connecting the VS debugger to the crashing process remotely managed to first hang Visual Studio, then cause a BSOD on my machine while killing the non-responsive devenv.exe. Wonderful!</p>\n" }, { "answer_id": 163516, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 0, "selected": false, "text": "<p>Pure speculation here, but the problem may be the using statement. Your code is like this (I think):</p>\n\n<pre><code>using (SoundPlayer myPlayer = new SoundPlayer(BEEPPURE))\n{ \n myPlayer.Play();\n}\n</code></pre>\n\n<p>The using block will call Dispose() on myPlayer, sometimes before it is done playing the sound (but rarely, because the sound is so short - with a longer sound, I'll bet you can reproduce the error every time). The error would be the result of the Windows API (which SoundPlayer wraps) trying to play a buffer which has already been disposed by .NET.</p>\n\n<p>I think if you do this:</p>\n\n<pre><code>SoundPlayer myPlayer = new SoundPlayer(BEEPPURE);\nmyPlayer.Play();\n</code></pre>\n\n<p>or even</p>\n\n<pre><code>(new SoundPlayer(BEEPPURE)).Play();\n</code></pre>\n\n<p>you will not see the error any more.</p>\n" }, { "answer_id": 405781, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>Actually, the above code (that is, new SoundPlayer(BEEPPURE)).Play(); was crashing for me.</p>\n\n<p>This article explains why, and provides an alternative to SoundPlayer that works flawlessly:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/audio-video/soundplayerbug.aspx?msg=2862832#xx2862832xx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/audio-video/soundplayerbug.aspx?msg=2862832#xx2862832xx</a></p>\n" } ]
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" }, { "answer_id": 82841, "author": "benefactual", "author_id": 6445, "author_profile": "https://Stackoverflow.com/users/6445", "pm_score": 8, "selected": false, "text": "<pre><code>import os\nos.path.exists(path) # Returns whether the path (directory or file) exists or not\nos.path.isfile(path) # Returns whether the file exists or not\n</code></pre>\n" }, { "answer_id": 82846, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 11, "selected": false, "text": "<p>Use <a href=\"https://docs.python.org/3/library/os.path.html#os.path.exists\" rel=\"noreferrer\"><code>os.path.exists</code></a> to check both files and directories:</p>\n<pre><code>import os.path\nos.path.exists(file_path)\n</code></pre>\n<p>Use <a href=\"https://docs.python.org/3/library/os.path.html#os.path.isfile\" rel=\"noreferrer\"><code>os.path.isfile</code></a> to check only files (note: follows <a href=\"https://en.wikipedia.org/wiki/Symbolic_link\" rel=\"noreferrer\">symbolic links</a>):</p>\n<pre><code>os.path.isfile(file_path)\n</code></pre>\n" }, { "answer_id": 82852, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 13, "selected": false, "text": "<p>If the reason you're checking is so you can do something like <code>if file_exists: open_it()</code>, it's safer to use a <code>try</code> 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.</p>\n\n<p>If you're not planning to open the file immediately, you can use <a href=\"https://docs.python.org/library/os.path.html#os.path.isfile\" rel=\"noreferrer\"><code>os.path.isfile</code></a></p>\n\n<blockquote>\n <p>Return <code>True</code> if path is an existing regular file. This follows symbolic links, so both <a href=\"https://docs.python.org/library/os.path.html#os.path.islink\" rel=\"noreferrer\">islink()</a> and <a href=\"https://docs.python.org/library/os.path.html#os.path.isfile\" rel=\"noreferrer\">isfile()</a> can be true for the same path.</p>\n</blockquote>\n\n<pre><code>import os.path\nos.path.isfile(fname) \n</code></pre>\n\n<p>if you need to be sure it's a file.</p>\n\n<p>Starting with Python 3.4, the <a href=\"https://docs.python.org/3/library/pathlib.html#pathlib.Path.is_file\" rel=\"noreferrer\"><code>pathlib</code> module</a> offers an object-oriented approach (backported to <code>pathlib2</code> in Python 2.7):</p>\n\n<pre><code>from pathlib import Path\n\nmy_file = Path(\"/path/to/file\")\nif my_file.is_file():\n # file exists\n</code></pre>\n\n<p>To check a directory, do:</p>\n\n<pre><code>if my_file.is_dir():\n # directory exists\n</code></pre>\n\n<p>To check whether a <code>Path</code> object exists independently of whether is it a file or directory, use <code>exists()</code>:</p>\n\n<pre><code>if my_file.exists():\n # path exists\n</code></pre>\n\n<p>You can also use <code>resolve(strict=True)</code> in a <code>try</code> block:</p>\n\n<pre><code>try:\n my_abs_path = my_file.resolve(strict=True)\nexcept FileNotFoundError:\n # doesn't exist\nelse:\n # exists\n</code></pre>\n" }, { "answer_id": 83012, "author": "zgoda", "author_id": 12138, "author_profile": "https://Stackoverflow.com/users/12138", "pm_score": 5, "selected": false, "text": "<p>Additionally, <code>os.access()</code>:</p>\n\n<pre><code>if os.access(\"myfile\", os.R_OK):\n with open(\"myfile\") as fp:\n return fp.read()\n</code></pre>\n\n<p>Being <code>R_OK</code>, <code>W_OK</code>, and <code>X_OK</code> the flags to test for permissions (<a href=\"https://docs.python.org/3/library/os.html#os.access\" rel=\"noreferrer\">doc</a>).</p>\n" }, { "answer_id": 84173, "author": "bortzmeyer", "author_id": 15625, "author_profile": "https://Stackoverflow.com/users/15625", "pm_score": 10, "selected": false, "text": "<p>Unlike <a href=\"https://docs.python.org/library/os.path.html#os.path.isfile\" rel=\"noreferrer\"><code>isfile()</code></a>, <a href=\"https://docs.python.org/library/os.path.html#os.path.exists\" rel=\"noreferrer\"><code>exists()</code></a> will return <code>True</code> for directories. So depending on if you want only plain files or also directories, you'll use <code>isfile()</code> or <code>exists()</code>. Here is some simple <a href=\"https://en.wikipedia.org/wiki/Read-eval-print_loop\" rel=\"noreferrer\">REPL</a> output:</p>\n<pre><code>&gt;&gt;&gt; os.path.isfile(&quot;/etc/password.txt&quot;)\nTrue\n&gt;&gt;&gt; os.path.isfile(&quot;/etc&quot;)\nFalse\n&gt;&gt;&gt; os.path.isfile(&quot;/does/not/exist&quot;)\nFalse\n&gt;&gt;&gt; os.path.exists(&quot;/etc/password.txt&quot;)\nTrue\n&gt;&gt;&gt; os.path.exists(&quot;/etc&quot;)\nTrue\n&gt;&gt;&gt; os.path.exists(&quot;/does/not/exist&quot;)\nFalse\n</code></pre>\n" }, { "answer_id": 1671095, "author": "pkoch", "author_id": 5128, "author_profile": "https://Stackoverflow.com/users/5128", "pm_score": 7, "selected": false, "text": "<p>Prefer the try statement. It's considered better style and avoids race conditions.</p>\n<p>Don't take my word for it. There's plenty of support for this theory. Here's a couple:</p>\n<ul>\n<li>Style: Section &quot;Handling unusual conditions&quot; of <a href=\"http://allendowney.com/sd/notes/notes11.txt\" rel=\"nofollow noreferrer\">these course notes for <em>Software Design</em></a> (2007)</li>\n<li><a href=\"https://developer.apple.com/library/mac/#documentation/security/conceptual/SecureCodingGuide/Articles/RaceConditions.html#//apple_ref/doc/uid/TP40002585-SW8\" rel=\"nofollow noreferrer\">Avoiding Race Conditions</a></li>\n</ul>\n" }, { "answer_id": 4799818, "author": "philberndt", "author_id": 589765, "author_profile": "https://Stackoverflow.com/users/589765", "pm_score": 6, "selected": false, "text": "<p>You could try this (safer):</p>\n\n<pre><code>try:\n # http://effbot.org/zone/python-with-statement.htm\n # 'with' is safer to open a file\n with open('whatever.txt') as fh:\n # Do something with 'fh'\nexcept IOError as e:\n print(\"({})\".format(e))\n</code></pre>\n\n<p>The ouput would be:</p>\n\n<blockquote>\n <p>([Errno 2] No such file or directory:\n 'whatever.txt')</p>\n</blockquote>\n\n<p>Then, depending on the result, your program can just keep running from there or you can code to stop it if you want.</p>\n" }, { "answer_id": 7201731, "author": "Jesvin Jose", "author_id": 604511, "author_profile": "https://Stackoverflow.com/users/604511", "pm_score": 3, "selected": false, "text": "<pre><code>import os\npath = /path/to/dir\n\nroot,dirs,files = os.walk(path).next()\nif myfile in files:\n print \"yes it exists\"\n</code></pre>\n\n<p>This is helpful when checking for several files. Or you want to do a set intersection/ subtraction with an existing list.</p>\n" }, { "answer_id": 8876254, "author": "Yugal Jindle", "author_id": 731963, "author_profile": "https://Stackoverflow.com/users/731963", "pm_score": 9, "selected": false, "text": "<p>Use <a href=\"https://docs.python.org/3.3/library/os.path.html?highlight=os.path#os.path.isfile\" rel=\"noreferrer\"><code>os.path.isfile()</code></a> with <a href=\"https://docs.python.org/3.3/library/os.html?highlight=os.access#os.access\" rel=\"noreferrer\"><code>os.access()</code></a>:</p>\n\n<pre><code>import os\n\nPATH = './file.txt'\nif os.path.isfile(PATH) and os.access(PATH, os.R_OK):\n print(\"File exists and is readable\")\nelse:\n print(\"Either the file is missing or not readable\")\n</code></pre>\n" }, { "answer_id": 17344732, "author": "un33k", "author_id": 103734, "author_profile": "https://Stackoverflow.com/users/103734", "pm_score": 7, "selected": false, "text": "<p>This is the simplest way to check if a file exists. Just <strong>because</strong> the file existed when you checked doesn't <strong>guarantee</strong> that it will be there when you need to open it.</p>\n\n<pre><code>import os\nfname = \"foo.txt\"\nif os.path.isfile(fname):\n print(\"file does exist at this time\")\nelse:\n print(\"no such file exists at this time\")\n</code></pre>\n" }, { "answer_id": 18994918, "author": "chad", "author_id": 225730, "author_profile": "https://Stackoverflow.com/users/225730", "pm_score": 6, "selected": false, "text": "<p>It doesn't seem like there's a meaningful functional difference between try/except and <code>isfile()</code>, so you should use which one makes sense.</p>\n<p>If you want to read a file, if it exists, do</p>\n<pre><code>try:\n f = open(filepath)\nexcept IOError:\n print 'Oh dear.'\n</code></pre>\n<p>But if you just wanted to rename a file if it exists, and therefore don't need to open it, do</p>\n<pre><code>if os.path.isfile(filepath):\n os.rename(filepath, filepath + '.old')\n</code></pre>\n<p>If you want to write to a file, if it doesn't exist, do</p>\n<pre><code># Python 2\nif not os.path.isfile(filepath):\n f = open(filepath, 'w')\n\n# Python 3: x opens for exclusive creation, failing if the file already exists\ntry:\n f = open(filepath, 'wx')\nexcept IOError:\n print 'file already exists'\n</code></pre>\n<p>If you need file locking, that's a different matter.</p>\n" }, { "answer_id": 21641213, "author": "Cody Piersall", "author_id": 1612701, "author_profile": "https://Stackoverflow.com/users/1612701", "pm_score": 8, "selected": false, "text": "<p><strong>Python 3.4+</strong> has an object-oriented path module: <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"noreferrer\"><strong>pathlib</strong></a>. Using this new module, you can check whether a file exists like this:</p>\n<pre><code>import pathlib\np = pathlib.Path('path/to/file')\nif p.is_file(): # or p.is_dir() to see if it is a directory\n # do stuff\n</code></pre>\n<p>You can (and usually should) still use a <code>try/except</code> block when opening files:</p>\n<pre><code>try:\n with p.open() as f:\n # do awesome stuff\nexcept OSError:\n print('Well darn.')\n</code></pre>\n<p>The pathlib module has lots of cool stuff in it: convenient globbing, checking file's owner, easier path joining, etc. It's worth checking out. If you're on an older Python (version 2.6 or later), you can still install pathlib with pip:</p>\n<pre><code># installs pathlib2 on older Python versions\n# the original third-party module, pathlib, is no longer maintained.\npip install pathlib2\n</code></pre>\n<p>Then import it as follows:</p>\n<pre><code># Older Python versions\nimport pathlib2 as pathlib\n</code></pre>\n" }, { "answer_id": 21688350, "author": "Chris", "author_id": 476266, "author_profile": "https://Stackoverflow.com/users/476266", "pm_score": 4, "selected": false, "text": "<p>You can write Brian's suggestion without the <code>try:</code>.</p>\n\n<pre><code>from contextlib import suppress\n\nwith suppress(IOError), open('filename'):\n process()\n</code></pre>\n\n<p><code>suppress</code> is part of Python 3.4. In older releases you can quickly write your own suppress:</p>\n\n<pre><code>from contextlib import contextmanager\n\n@contextmanager\ndef suppress(*exceptions):\n try:\n yield\n except exceptions:\n pass\n</code></pre>\n" }, { "answer_id": 23826292, "author": "Zaheer", "author_id": 3197473, "author_profile": "https://Stackoverflow.com/users/3197473", "pm_score": 3, "selected": false, "text": "<p>You can use the following open method to check if a file exists + readable:</p>\n\n<pre><code>file = open(inputFile, 'r')\nfile.close()\n</code></pre>\n" }, { "answer_id": 26335110, "author": "bergercookie", "author_id": 2843583, "author_profile": "https://Stackoverflow.com/users/2843583", "pm_score": 5, "selected": false, "text": "<p>If the file is for opening you could use one of the following techniques:</p>\n<pre><code>with open('somefile', 'xt') as f: # Using the x-flag, Python 3.3 and above\n f.write('Hello\\n')\n\nif not os.path.exists('somefile'): \n with open('somefile', 'wt') as f:\n f.write(&quot;Hello\\n&quot;)\nelse:\n print('File already exists!')\n</code></pre>\n<hr />\n<p>Note: This finds either a file <strong>or</strong> a directory with the given name.</p>\n" }, { "answer_id": 26433646, "author": "Hanson", "author_id": 3901280, "author_profile": "https://Stackoverflow.com/users/3901280", "pm_score": 3, "selected": false, "text": "<p>To check if a file exists, </p>\n\n<pre><code>from sys import argv\n\nfrom os.path import exists\nscript, filename = argv\ntarget = open(filename)\nprint \"file exists: %r\" % exists(filename)\n</code></pre>\n" }, { "answer_id": 27581592, "author": "Pradip Das", "author_id": 2230891, "author_profile": "https://Stackoverflow.com/users/2230891", "pm_score": 4, "selected": false, "text": "<p>You can use the \"OS\" library of Python:</p>\n\n<pre><code>&gt;&gt;&gt; import os\n&gt;&gt;&gt; os.path.exists(\"C:\\\\Users\\\\####\\\\Desktop\\\\test.txt\") \nTrue\n&gt;&gt;&gt; os.path.exists(\"C:\\\\Users\\\\####\\\\Desktop\\\\test.tx\")\nFalse\n</code></pre>\n" }, { "answer_id": 27661444, "author": "Zizouz212", "author_id": 4293417, "author_profile": "https://Stackoverflow.com/users/4293417", "pm_score": 6, "selected": false, "text": "<p>Although I always recommend using <code>try</code> and <code>except</code> statements, here are a few possibilities for you (my personal favourite is using <code>os.access</code>):</p>\n\n<ol>\n<li><p>Try opening the file:</p>\n\n<p>Opening the file will always verify the existence of the file. You can make a function just like so:</p>\n\n<pre><code>def File_Existence(filepath):\n f = open(filepath)\n return True\n</code></pre>\n\n<p>If it's False, it will stop execution with an unhanded IOError\nor OSError in later versions of Python. To catch the exception,\nyou have to use a try except clause. Of course, you can always\nuse a <code>try</code> except` statement like so (thanks to <a href=\"https://stackoverflow.com/users/3256073/hsandt\">hsandt</a>\nfor making me think):</p>\n\n<pre><code>def File_Existence(filepath):\n try:\n f = open(filepath)\n except IOError, OSError: # Note OSError is for later versions of Python\n return False\n\n return True\n</code></pre></li>\n<li><p>Use <code>os.path.exists(path)</code>:</p>\n\n<p>This will check the existence of what you specify. However, it checks for files <em>and</em> directories so beware about how you use it.</p>\n\n<pre><code>import os.path\n&gt;&gt;&gt; os.path.exists(\"this/is/a/directory\")\nTrue\n&gt;&gt;&gt; os.path.exists(\"this/is/a/file.txt\")\nTrue\n&gt;&gt;&gt; os.path.exists(\"not/a/directory\")\nFalse\n</code></pre></li>\n<li><p>Use <code>os.access(path, mode)</code>:</p>\n\n<p>This will check whether you have access to the file. It will check for permissions. Based on the os.py documentation, typing in <code>os.F_OK</code>, it will check the existence of the path. However, using this will create a security hole, as someone can attack your file using the time between checking the permissions and opening the file. You should instead go directly to opening the file instead of checking its permissions. (<a href=\"https://docs.python.org/2/glossary.html#term-eafp\" rel=\"noreferrer\">EAFP</a> vs <a href=\"https://docs.python.org/2/glossary.html#term-lbyl\" rel=\"noreferrer\">LBYP</a>). If you're not going to open the file afterwards, and only checking its existence, then you can use this.</p>\n\n<p>Anyway, here:</p>\n\n<pre><code>&gt;&gt;&gt; import os\n&gt;&gt;&gt; os.access(\"/is/a/file.txt\", os.F_OK)\nTrue\n</code></pre></li>\n</ol>\n\n<p>I should also mention that there are two ways that you will not be able to verify the existence of a file. Either the issue will be <code>permission denied</code> or <code>no such file or directory</code>. If you catch an <code>IOError</code>, set the <code>IOError as e</code> (like my first option), and then type in <code>print(e.args)</code> so that you can hopefully determine your issue. I hope it helps! :)</p>\n" }, { "answer_id": 29909391, "author": "Pedro Lobito", "author_id": 797495, "author_profile": "https://Stackoverflow.com/users/797495", "pm_score": 5, "selected": false, "text": "<pre><code>if os.path.isfile(path_to_file):\n try:\n open(path_to_file)\n pass\n except IOError as e:\n print &quot;Unable to open file&quot;\n</code></pre>\n<blockquote>\n<p>Raising exceptions is considered to be an acceptable, and Pythonic,\napproach for flow control in your program. Consider handling missing\nfiles with IOErrors. In this situation, an IOError exception will be\nraised if the file exists but the user does not have read permissions.</p>\n</blockquote>\n<p>Source: <em><a href=\"http://www.pfinn.net/python-check-if-file-exists.html\" rel=\"nofollow noreferrer\">Using Python: How To Check If A File Exists</a></em></p>\n" }, { "answer_id": 30444116, "author": "karlzafiris", "author_id": 4141689, "author_profile": "https://Stackoverflow.com/users/4141689", "pm_score": 7, "selected": false, "text": "<p>Use:</p>\n<pre><code>import os\n#Your path here e.g. &quot;C:\\Program Files\\text.txt&quot;\n#For access purposes: &quot;C:\\\\Program Files\\\\text.txt&quot;\nif os.path.exists(&quot;C:\\...&quot;):\n print &quot;File found!&quot;\nelse:\n print &quot;File not found!&quot;\n</code></pre>\n<p>Importing <code>os</code> makes it easier to navigate and perform standard actions with your operating system.</p>\n<p>For reference, also see <em><a href=\"/q/82831\">How do I check whether a file exists without exceptions?</a></em>.</p>\n<p>If you need high-level operations, use <code>shutil</code>.</p>\n" }, { "answer_id": 31824912, "author": "Khaled.K", "author_id": 2128327, "author_profile": "https://Stackoverflow.com/users/2128327", "pm_score": 4, "selected": false, "text": "<pre><code>import os.path\n\ndef isReadableFile(file_path, file_name):\n full_path = file_path + \"/\" + file_name\n try:\n if not os.path.exists(file_path):\n print \"File path is invalid.\"\n return False\n elif not os.path.isfile(full_path):\n print \"File does not exist.\"\n return False\n elif not os.access(full_path, os.R_OK):\n print \"File cannot be read.\"\n return False\n else:\n print \"File can be read.\"\n return True\n except IOError as ex:\n print \"I/O error({0}): {1}\".format(ex.errno, ex.strerror)\n except Error as ex:\n print \"Error({0}): {1}\".format(ex.errno, ex.strerror)\n return False\n#------------------------------------------------------\n\npath = \"/usr/khaled/documents/puzzles\"\nfileName = \"puzzle_1.txt\"\n\nisReadableFile(path, fileName)\n</code></pre>\n" }, { "answer_id": 31932925, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 7, "selected": false, "text": "<blockquote>\n <h2>How do I check whether a file exists, using Python, without using a try statement?</h2>\n</blockquote>\n\n<p>Now available since Python 3.4, import and instantiate a <code>Path</code> object with the file name, and check the <code>is_file</code> method (note that this returns True for symlinks pointing to regular files as well):</p>\n\n<pre><code>&gt;&gt;&gt; from pathlib import Path\n&gt;&gt;&gt; Path('/').is_file()\nFalse\n&gt;&gt;&gt; Path('/initrd.img').is_file()\nTrue\n&gt;&gt;&gt; Path('/doesnotexist').is_file()\nFalse\n</code></pre>\n\n<p>If you're on Python 2, you can backport the pathlib module from pypi, <a href=\"https://pypi.python.org/pypi/pathlib2/\" rel=\"noreferrer\"><code>pathlib2</code></a>, or otherwise check <code>isfile</code> from the <code>os.path</code> module:</p>\n\n<pre><code>&gt;&gt;&gt; import os\n&gt;&gt;&gt; os.path.isfile('/')\nFalse\n&gt;&gt;&gt; os.path.isfile('/initrd.img')\nTrue\n&gt;&gt;&gt; os.path.isfile('/doesnotexist')\nFalse\n</code></pre>\n\n<p>Now the above is probably the best pragmatic direct answer here, but there's the possibility of a race condition (depending on what you're trying to accomplish), and the fact that the underlying implementation uses a <code>try</code>, but Python uses <code>try</code> everywhere in its implementation. </p>\n\n<p>Because Python uses <code>try</code> everywhere, there's really no reason to avoid an implementation that uses it.</p>\n\n<p>But the rest of this answer attempts to consider these caveats.</p>\n\n<h2>Longer, much more pedantic answer</h2>\n\n<p>Available since Python 3.4, use the new <code>Path</code> object in <code>pathlib</code>. Note that <code>.exists</code> is not quite right, because directories are not files (except in the unix sense that <em>everything</em> is a file).</p>\n\n<pre><code>&gt;&gt;&gt; from pathlib import Path\n&gt;&gt;&gt; root = Path('/')\n&gt;&gt;&gt; root.exists()\nTrue\n</code></pre>\n\n<p>So we need to use <code>is_file</code>:</p>\n\n<pre><code>&gt;&gt;&gt; root.is_file()\nFalse\n</code></pre>\n\n<p>Here's the help on <code>is_file</code>:</p>\n\n<pre><code>is_file(self)\n Whether this path is a regular file (also True for symlinks pointing\n to regular files).\n</code></pre>\n\n<p>So let's get a file that we know is a file:</p>\n\n<pre><code>&gt;&gt;&gt; import tempfile\n&gt;&gt;&gt; file = tempfile.NamedTemporaryFile()\n&gt;&gt;&gt; filepathobj = Path(file.name)\n&gt;&gt;&gt; filepathobj.is_file()\nTrue\n&gt;&gt;&gt; filepathobj.exists()\nTrue\n</code></pre>\n\n<p>By default, <code>NamedTemporaryFile</code> deletes the file when closed (and will automatically close when no more references exist to it).</p>\n\n<pre><code>&gt;&gt;&gt; del file\n&gt;&gt;&gt; filepathobj.exists()\nFalse\n&gt;&gt;&gt; filepathobj.is_file()\nFalse\n</code></pre>\n\n<p>If you dig into <a href=\"https://github.com/python/cpython/blob/master/Lib/pathlib.py#L1318\" rel=\"noreferrer\">the implementation</a>, though, you'll see that <code>is_file</code> uses <code>try</code>:</p>\n\n<pre><code>def is_file(self):\n \"\"\"\n Whether this path is a regular file (also True for symlinks pointing\n to regular files).\n \"\"\"\n try:\n return S_ISREG(self.stat().st_mode)\n except OSError as e:\n if e.errno not in (ENOENT, ENOTDIR):\n raise\n # Path doesn't exist or is a broken symlink\n # (see https://bitbucket.org/pitrou/pathlib/issue/12/)\n return False\n</code></pre>\n\n<h2>Race Conditions: Why we like try</h2>\n\n<p>We like <code>try</code> because it avoids race conditions. With <code>try</code>, you simply attempt to read your file, expecting it to be there, and if not, you catch the exception and perform whatever fallback behavior makes sense.</p>\n\n<p>If you want to check that a file exists before you attempt to read it, and you might be deleting it and then you might be using multiple threads or processes, or another program knows about that file and could delete it - you risk the chance of a <strong>race condition</strong> if you check it exists, because you are then <em>racing</em> to open it before its <em>condition</em> (its existence) changes. </p>\n\n<p>Race conditions are very hard to debug because there's a very small window in which they can cause your program to fail.</p>\n\n<p>But if this is your motivation, you <em>can</em> get the value of a <code>try</code> statement by using the <code>suppress</code> context manager.</p>\n\n<h2>Avoiding race conditions without a try statement: <code>suppress</code></h2>\n\n<p>Python 3.4 gives us the <a href=\"https://docs.python.org/3/library/contextlib.html#contextlib.suppress\" rel=\"noreferrer\"><code>suppress</code></a> context manager (previously the <a href=\"https://bugs.python.org/issue19266\" rel=\"noreferrer\"><code>ignore</code></a> context manager), which does semantically exactly the same thing in fewer lines, while also (at least superficially) meeting the original ask to avoid a <code>try</code> statement:</p>\n\n<pre><code>from contextlib import suppress\nfrom pathlib import Path\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>&gt;&gt;&gt; with suppress(OSError), Path('doesnotexist').open() as f:\n... for line in f:\n... print(line)\n... \n&gt;&gt;&gt;\n&gt;&gt;&gt; with suppress(OSError):\n... Path('doesnotexist').unlink()\n... \n&gt;&gt;&gt; \n</code></pre>\n\n<p>For earlier Pythons, you could roll your own <code>suppress</code>, but without a <code>try</code> will be more verbose than with. I do believe <strong>this actually is the only answer that doesn't use <code>try</code> at any level in the Python</strong> that can be applied to prior to Python 3.4 because it uses a context manager instead:</p>\n\n<pre><code>class suppress(object):\n def __init__(self, *exceptions):\n self.exceptions = exceptions\n def __enter__(self):\n return self\n def __exit__(self, exc_type, exc_value, traceback):\n if exc_type is not None:\n return issubclass(exc_type, self.exceptions)\n</code></pre>\n\n<p>Perhaps easier with a try:</p>\n\n<pre><code>from contextlib import contextmanager\n\n@contextmanager\ndef suppress(*exceptions):\n try:\n yield\n except exceptions:\n pass\n</code></pre>\n\n<h2>Other options that don't meet the ask for \"without try\":</h2>\n\n<p><strong>isfile</strong></p>\n\n<pre><code>import os\nos.path.isfile(path)\n</code></pre>\n\n<p>from the <a href=\"https://docs.python.org/library/os.path.html#os.path.isfile\" rel=\"noreferrer\">docs</a>:</p>\n\n<blockquote>\n <p><code>os.path.isfile(path)</code></p>\n \n <p>Return True if path is an existing regular file. This follows symbolic\n links, so both <code>islink()</code> and <code>isfile()</code> can be true for the same path.</p>\n</blockquote>\n\n<p>But if you examine the <a href=\"https://hg.python.org/cpython/file/tip/Lib/genericpath.py#l25\" rel=\"noreferrer\">source</a> of this function, you'll see it actually does use a try statement:</p>\n\n<blockquote>\n<pre><code># This follows symbolic links, so both islink() and isdir() can be true\n# for the same path on systems that support symlinks\ndef isfile(path):\n \"\"\"Test whether a path is a regular file\"\"\"\n try:\n st = os.stat(path)\n except os.error:\n return False\n return stat.S_ISREG(st.st_mode)\n</code></pre>\n</blockquote>\n\n<pre><code>&gt;&gt;&gt; OSError is os.error\nTrue\n</code></pre>\n\n<p>All it's doing is using the given path to see if it can get stats on it, catching <code>OSError</code> and then checking if it's a file if it didn't raise the exception.</p>\n\n<p>If you intend to do something with the file, I would suggest directly attempting it with a try-except to avoid a race condition:</p>\n\n<pre><code>try:\n with open(path) as f:\n f.read()\nexcept OSError:\n pass\n</code></pre>\n\n<p><strong>os.access</strong></p>\n\n<p>Available for Unix and Windows is <code>os.access</code>, but to use you must pass flags, and it does not differentiate between files and directories. This is more used to test if the real invoking user has access in an elevated privilege environment:</p>\n\n<pre><code>import os\nos.access(path, os.F_OK)\n</code></pre>\n\n<p>It also suffers from the same race condition problems as <code>isfile</code>. From the <a href=\"https://docs.python.org/2/library/os.html#os.access\" rel=\"noreferrer\">docs</a>:</p>\n\n<blockquote>\n <p>Note:\n Using access() to check if a user is authorized to e.g. open a file\n before actually doing so using open() creates a security hole, because\n the user might exploit the short time interval between checking and\n opening the file to manipulate it. It’s preferable to use EAFP\n techniques. For example:</p>\n\n<pre><code>if os.access(\"myfile\", os.R_OK):\n with open(\"myfile\") as fp:\n return fp.read()\nreturn \"some default data\"\n</code></pre>\n \n <p>is better written as:</p>\n\n<pre><code>try:\n fp = open(\"myfile\")\nexcept IOError as e:\n if e.errno == errno.EACCES:\n return \"some default data\"\n # Not a permission error.\n raise\nelse:\n with fp:\n return fp.read()\n</code></pre>\n</blockquote>\n\n<p>Avoid using <code>os.access</code>. It is a low level function that has more opportunities for user error than the higher level objects and functions discussed above.</p>\n\n<h3>Criticism of another answer:</h3>\n\n<p>Another answer says this about <code>os.access</code>:</p>\n\n<blockquote>\n <p>Personally, I prefer this one because under the hood, it calls native APIs (via \"${PYTHON_SRC_DIR}/Modules/posixmodule.c\"), but it also opens a gate for possible user errors, and it's not as Pythonic as other variants:</p>\n</blockquote>\n\n<p>This answer says it prefers a non-Pythonic, error-prone method, with no justification. It seems to encourage users to use low-level APIs without understanding them. </p>\n\n<p>It also creates a context manager which, by unconditionally returning <code>True</code>, allows all Exceptions (including <code>KeyboardInterrupt</code> and <code>SystemExit</code>!) to pass silently, which is a good way to hide bugs.</p>\n\n<p>This seems to encourage users to adopt poor practices.</p>\n" }, { "answer_id": 32288118, "author": "Love and peace - Joe Codeswell", "author_id": 601770, "author_profile": "https://Stackoverflow.com/users/601770", "pm_score": 4, "selected": false, "text": "<p>Here's a one-line Python command for the Linux command line environment. I find this <em>very handy</em> since I'm not such a hot Bash guy.</p>\n<pre><code>python -c &quot;import os.path; print os.path.isfile('/path_to/file.xxx')&quot;\n</code></pre>\n" }, { "answer_id": 35602588, "author": "KaiBuxe", "author_id": 5968477, "author_profile": "https://Stackoverflow.com/users/5968477", "pm_score": 6, "selected": false, "text": "<p>In 2016 the best way is still using <code>os.path.isfile</code>:</p>\n\n<pre><code>&gt;&gt;&gt; os.path.isfile('/path/to/some/file.txt')\n</code></pre>\n\n<p>Or in Python 3 you can use <code>pathlib</code>:</p>\n\n<pre><code>import pathlib\npath = pathlib.Path('/path/to/some/file.txt')\nif path.is_file():\n ...\n</code></pre>\n" }, { "answer_id": 37050053, "author": "Mike McKerns", "author_id": 2379433, "author_profile": "https://Stackoverflow.com/users/2379433", "pm_score": 4, "selected": false, "text": "<p>I'm the author of a package that's been around for about 10 years, and it has a function that addresses this question directly. Basically, if you are on a non-Windows system, it uses <code>Popen</code> to access <code>find</code>. However, if you are on Windows, it replicates <code>find</code> with an efficient filesystem walker.</p>\n\n<p>The code itself does not use a <code>try</code> block… except in determining the operating system and thus steering you to the \"Unix\"-style <code>find</code> or the hand-buillt <code>find</code>. Timing tests showed that the <code>try</code> was faster in determining the OS, so I did use one there (but nowhere else).</p>\n\n<pre><code>&gt;&gt;&gt; import pox\n&gt;&gt;&gt; pox.find('*python*', type='file', root=pox.homedir(), recurse=False)\n['/Users/mmckerns/.python']\n</code></pre>\n\n<p>And the doc…</p>\n\n<pre><code>&gt;&gt;&gt; print pox.find.__doc__\nfind(patterns[,root,recurse,type]); Get path to a file or directory\n\n patterns: name or partial name string of items to search for\n root: path string of top-level directory to search\n recurse: if True, recurse down from root directory\n type: item filter; one of {None, file, dir, link, socket, block, char}\n verbose: if True, be a little verbose about the search\n\n On some OS, recursion can be specified by recursion depth (an integer).\n patterns can be specified with basic pattern matching. Additionally,\n multiple patterns can be specified by splitting patterns with a ';'\n For example:\n &gt;&gt;&gt; find('pox*', root='..')\n ['/Users/foo/pox/pox', '/Users/foo/pox/scripts/pox_launcher.py']\n\n &gt;&gt;&gt; find('*shutils*;*init*')\n ['/Users/foo/pox/pox/shutils.py', '/Users/foo/pox/pox/__init__.py']\n\n&gt;&gt;&gt;\n</code></pre>\n\n<p>The implementation, if you care to look, is here:\n<a href=\"https://github.com/uqfoundation/pox/blob/89f90fb308f285ca7a62eabe2c38acb87e89dad9/pox/shutils.py#L190\" rel=\"noreferrer\">https://github.com/uqfoundation/pox/blob/89f90fb308f285ca7a62eabe2c38acb87e89dad9/pox/shutils.py#L190</a></p>\n" }, { "answer_id": 37702905, "author": "iPhynx", "author_id": 5489173, "author_profile": "https://Stackoverflow.com/users/5489173", "pm_score": 3, "selected": false, "text": "<p>You can use os.listdir to check if a file is in a certain directory.</p>\n\n<pre><code>import os\nif 'file.ext' in os.listdir('dirpath'):\n #code\n</code></pre>\n" }, { "answer_id": 38793323, "author": "Marcel Wilson", "author_id": 2532408, "author_profile": "https://Stackoverflow.com/users/2532408", "pm_score": 4, "selected": false, "text": "<p>Adding one more slight variation which isn't exactly reflected in the other answers.</p>\n\n<p>This will handle the case of the <code>file_path</code> being <code>None</code> or empty string.</p>\n\n<p></p>\n\n<pre><code>def file_exists(file_path):\n if not file_path:\n return False\n elif not os.path.isfile(file_path):\n return False\n else:\n return True\n</code></pre>\n\n<p>Adding a variant based on suggestion from Shahbaz\n</p>\n\n<pre><code>def file_exists(file_path):\n if not file_path:\n return False\n else:\n return os.path.isfile(file_path)\n</code></pre>\n\n<p>Adding a variant based on suggestion from Peter Wood\n</p>\n\n<pre><code>def file_exists(file_path):\n return file_path and os.path.isfile(file_path):\n</code></pre>\n" }, { "answer_id": 39932496, "author": "Tom Fuller", "author_id": 5177604, "author_profile": "https://Stackoverflow.com/users/5177604", "pm_score": 7, "selected": false, "text": "<p>Testing for files and folders with <code>os.path.isfile()</code>, <code>os.path.isdir()</code> and <code>os.path.exists()</code></p>\n\n<p>Assuming that the \"path\" is a valid path, this table shows what is returned by each function for files and folders:</p>\n\n<p><a href=\"https://i.stack.imgur.com/tOs9p.png\"><img src=\"https://i.stack.imgur.com/tOs9p.png\" alt=\"enter image description here\"></a></p>\n\n<p>You can also test if a file is a certain type of file using <code>os.path.splitext()</code> to get the extension (if you don't already know it)</p>\n\n<pre><code>&gt;&gt;&gt; import os\n&gt;&gt;&gt; path = \"path to a word document\"\n&gt;&gt;&gt; os.path.isfile(path)\nTrue\n&gt;&gt;&gt; os.path.splitext(path)[1] == \".docx\" # test if the extension is .docx\nTrue\n</code></pre>\n" }, { "answer_id": 40926284, "author": "Taufiq Rahman", "author_id": 5401681, "author_profile": "https://Stackoverflow.com/users/5401681", "pm_score": 4, "selected": false, "text": "<blockquote>\n <p><strong>How do I check whether a file exists, without using the try statement?</strong></p>\n</blockquote>\n\n<p>In 2016, this is still arguably the easiest way to check if both a file exists and if it is a file:</p>\n\n<pre><code>import os\nos.path.isfile('./file.txt') # Returns True if exists, else False\n</code></pre>\n\n<p><code>isfile</code> is actually just a helper method that internally uses <code>os.stat</code> and <code>stat.S_ISREG(mode)</code> underneath. This <code>os.stat</code> is a lower-level method that will provide you with detailed information about files, directories, sockets, buffers, and more. <a href=\"https://docs.python.org/2/library/os.html#os.stat\" rel=\"noreferrer\">More about os.stat here</a></p>\n\n<p><strong>Note:</strong> However, this approach will not lock the file in any way and therefore your code can become vulnerable to \"<strong>time of check to time of use</strong>\" (<em>TOCTTOU</em>) bugs.</p>\n\n<p>So raising exceptions is considered to be an acceptable, and Pythonic, approach for flow control in your program. And one should consider handling missing files with IOErrors, rather than <code>if</code> statements (<em>just an advice</em>).</p>\n" }, { "answer_id": 44661513, "author": "CristiFati", "author_id": 4788546, "author_profile": "https://Stackoverflow.com/users/4788546", "pm_score": 8, "selected": false, "text": "<p>Although almost every possible way has been listed in (at least one of) the existing answers (e.g. <em>Python 3.4</em> specific stuff was added), I'll try to group everything together.</p>\n<p><strong>Note</strong>: every piece of <em>Python</em> standard library code that I'm going to post, belongs to version <strong>3.5.3</strong>.</p>\n<p><strong>Problem statement</strong>:</p>\n<ol>\n<li>Check file (<em>arguable</em>: also folder (&quot;special&quot; file) ?) existence</li>\n<li>Don't use <em><strong>try</strong></em> / <em><strong>except</strong></em> / <em><strong>else</strong></em> / <em><strong>finally</strong></em> blocks</li>\n</ol>\n<p><strong>Possible solutions</strong>:</p>\n\n<ol>\n<li><p><a href=\"https://docs.python.org/3/library/os.path.html#os.path.exists\" rel=\"nofollow noreferrer\">[Python 3]: os.path.<strong>exists</strong>(<em>path</em>)</a> (also check other function family members like <code>os.path.isfile</code>, <code>os.path.isdir</code>, <code>os.path.lexists</code> for slightly different behaviors)</p>\n<pre class=\"lang-py prettyprint-override\"><code> os.path.exists(path)\n</code></pre>\n<blockquote>\n<p>Return <code>True</code> if <em>path</em> refers to an existing path or an open file descriptor. Returns <code>False</code> for broken symbolic links. On some platforms, this function may return <code>False</code> if permission is not granted to execute <a href=\"https://docs.python.org/3/library/os.html#os.stat\" rel=\"nofollow noreferrer\">os.stat()</a> on the requested file, even if the <em>path</em> physically exists.</p>\n</blockquote>\n<p>All good, but if following the import tree:</p>\n<ul>\n<li><code>os.path</code> - <em>posixpath.py</em> (<em>ntpath.py</em>)\n<ul>\n<li><p><em>genericpath.py</em>, line <em>~#20+</em></p>\n<pre class=\"lang-py prettyprint-override\"><code> def exists(path):\n &quot;&quot;&quot;Test whether a path exists. Returns False for broken symbolic links&quot;&quot;&quot;\n try:\n st = os.stat(path)\n except os.error:\n return False\n return True\n</code></pre>\n</li>\n</ul>\n</li>\n</ul>\n<p>it's just a <em><strong>try</strong></em> / <em><strong>except</strong></em> block around <a href=\"https://docs.python.org/3/library/os.html#os.stat\" rel=\"nofollow noreferrer\">[Python 3]: os.<strong>stat</strong>(<em>path, *, dir_fd=None, follow_symlinks=True</em>)</a>. So, your code is <em><strong>try</strong></em> / <em><strong>except</strong></em> free, but lower in the framestack there's (at least) <strong>one</strong> such block. This also applies to other functions (<strong>including</strong> <code>os.path.isfile</code>).</p>\n<p>1.1. <a href=\"https://docs.python.org/3/library/pathlib.html#pathlib.Path.is_file\" rel=\"nofollow noreferrer\">[Python 3]: Path.<strong>is_file</strong>()</a></p>\n<ul>\n<li><p>It's a fancier (and more <a href=\"https://en.wiktionary.org/wiki/Pythonic#Adjective\" rel=\"nofollow noreferrer\">Pythonic</a>) way of handling paths, <strong>but</strong></p>\n</li>\n<li><p>Under the hood, it does <strong>exactly</strong> the same thing (<em>pathlib.py</em>, line <em>~#1330</em>):</p>\n<pre class=\"lang-py prettyprint-override\"><code> def is_file(self):\n &quot;&quot;&quot;\n Whether this path is a regular file (also True for symlinks pointing\n to regular files).\n &quot;&quot;&quot;\n try:\n return S_ISREG(self.stat().st_mode)\n except OSError as e:\n if e.errno not in (ENOENT, ENOTDIR):\n raise\n # Path doesn't exist or is a broken symlink\n # (see https://bitbucket.org/pitrou/pathlib/issue/12/)\n return False\n</code></pre>\n</li>\n</ul>\n</li>\n<li><p><a href=\"https://docs.python.org/3/reference/datamodel.html#context-managers\" rel=\"nofollow noreferrer\">[Python 3]: With Statement Context Managers</a>. Either:</p>\n<ul>\n<li><p>Create one:</p>\n<pre class=\"lang-py prettyprint-override\"><code> class Swallow: # Dummy example\n swallowed_exceptions = (FileNotFoundError,)\n\n def __enter__(self):\n print(&quot;Entering...&quot;)\n\n def __exit__(self, exc_type, exc_value, exc_traceback):\n print(&quot;Exiting:&quot;, exc_type, exc_value, exc_traceback)\n return exc_type in Swallow.swallowed_exceptions # only swallow FileNotFoundError (not e.g. TypeError - if the user passes a wrong argument like None or float or ...)\n</code></pre>\n<ul>\n<li><p>And its usage - I'll replicate the <code>os.path.isfile</code> behavior (note that this is just for demonstrating purposes, do <strong>not</strong> attempt to write such code for <em>production</em>):</p>\n<pre class=\"lang-py prettyprint-override\"><code> import os\n import stat\n\n\n def isfile_seaman(path): # Dummy func\n result = False\n with Swallow():\n result = stat.S_ISREG(os.stat(path).st_mode)\n return result\n</code></pre>\n</li>\n</ul>\n</li>\n<li><p>Use <a href=\"https://docs.python.org/3/library/contextlib.html#contextlib.suppress\" rel=\"nofollow noreferrer\">[Python 3]: contextlib.<strong>suppress</strong>(<em>*exceptions</em>)</a> - which was <strong>specifically</strong> designed for selectively suppressing exceptions</p>\n</li>\n</ul>\n<p><br>But, they seem to be wrappers over <em><strong>try</strong></em> / <em><strong>except</strong></em> / <em><strong>else</strong></em> / <em><strong>finally</strong></em> blocks, as <a href=\"https://docs.python.org/3/reference/compound_stmts.html#with\" rel=\"nofollow noreferrer\">[Python 3]: The <em>with</em> statement</a> states:</p>\n<blockquote>\n<p>This allows common <a href=\"https://docs.python.org/3/reference/compound_stmts.html#try\" rel=\"nofollow noreferrer\">try</a>...<a href=\"https://docs.python.org/3/reference/compound_stmts.html#except\" rel=\"nofollow noreferrer\">except</a>...<a href=\"https://docs.python.org/3/reference/compound_stmts.html#finally\" rel=\"nofollow noreferrer\">finally</a> usage patterns to be encapsulated for convenient reuse.</p>\n</blockquote>\n</li>\n<li><p>Filesystem traversal functions (and search the results for matching item(s))</p>\n<ul>\n<li><p><a href=\"https://docs.python.org/3/library/os.html#os.listdir\" rel=\"nofollow noreferrer\">[Python 3]: os.<strong>listdir</strong>(<em>path='.'</em>)</a> (or <a href=\"https://docs.python.org/3/library/os.html#os.scandir\" rel=\"nofollow noreferrer\">[Python 3]: os.<strong>scandir</strong>(<em>path='.'</em>)</a> on <em>Python v<strong>3.5</strong></em>+, backport: <a href=\"https://pypi.org/project/scandir\" rel=\"nofollow noreferrer\">[PyPI]: scandir</a>)</p>\n<ul>\n<li><p>Under the hood, both use:</p>\n<ul>\n<li><em>Unix-like</em>: <a href=\"http://man7.org/linux/man-pages/man3/opendir.3.html\" rel=\"nofollow noreferrer\">[man7]: OPENDIR(3)</a> / <a href=\"http://man7.org/linux/man-pages/man3/readdir.3.html\" rel=\"nofollow noreferrer\">[man7]: READDIR(3)</a> / <a href=\"http://man7.org/linux/man-pages/man3/closedir.3.html\" rel=\"nofollow noreferrer\">[man7]: CLOSEDIR(3)</a></li>\n<li><em>Windows</em>: <a href=\"https://learn.microsoft.com/en-gb/windows/desktop/api/fileapi/nf-fileapi-findfirstfilew\" rel=\"nofollow noreferrer\">[MS.Docs]: FindFirstFileW function</a> / <a href=\"https://learn.microsoft.com/en-gb/windows/desktop/api/fileapi/nf-fileapi-findnextfilew\" rel=\"nofollow noreferrer\">[MS.Docs]: FindNextFileW function</a> / <a href=\"https://learn.microsoft.com/en-gb/windows/desktop/api/fileapi/nf-fileapi-findclose\" rel=\"nofollow noreferrer\">[MS.Docs]: FindClose function</a></li>\n</ul>\n<p>via <a href=\"https://github.com/python/cpython/blob/master/Modules/posixmodule.c\" rel=\"nofollow noreferrer\">[GitHub]: Python/CPython - (master) cpython/Modules/posixmodule.c</a></p>\n</li>\n</ul>\n<blockquote>\n<p>Using <a href=\"https://docs.python.org/3/library/os.html#os.scandir\" rel=\"nofollow noreferrer\">scandir()</a> instead of <a href=\"https://docs.python.org/3/library/os.html#os.listdir\" rel=\"nofollow noreferrer\">listdir()</a> can significantly increase the performance of code that also needs file type or file attribute information, because <a href=\"https://docs.python.org/3/library/os.html#os.DirEntry\" rel=\"nofollow noreferrer\">os.DirEntry</a> objects expose this information if the operating system provides it when scanning a directory. All <a href=\"https://docs.python.org/3/library/os.html#os.DirEntry\" rel=\"nofollow noreferrer\">os.DirEntry</a> methods may perform a system call, but <a href=\"https://docs.python.org/3/library/os.html#os.DirEntry.is_dir\" rel=\"nofollow noreferrer\">is_dir()</a> and <a href=\"https://docs.python.org/3/library/os.html#os.DirEntry.is_file\" rel=\"nofollow noreferrer\">is_file()</a> usually only require a system call for symbolic links; <a href=\"https://docs.python.org/3/library/os.html#os.DirEntry.stat\" rel=\"nofollow noreferrer\">os.DirEntry.stat()</a> always requires a system call on Unix, but only requires one for symbolic links on Windows.</p>\n</blockquote>\n</li>\n<li><p><a href=\"https://docs.python.org/3/library/os.html#os.walk\" rel=\"nofollow noreferrer\">[Python 3]: os.<strong>walk</strong>(<em>top, topdown=True, onerror=None, followlinks=False</em>)</a></p>\n<ul>\n<li>It uses <code>os.listdir</code> (<code>os.scandir</code> when available)</li>\n</ul>\n</li>\n<li><p><a href=\"https://docs.python.org/3/library/glob.html#glob.iglob\" rel=\"nofollow noreferrer\">[Python 3]: glob.<strong>iglob</strong>(<em>pathname, *, recursive=False</em>)</a> (or its predecessor: <code>glob.glob</code>)</p>\n<ul>\n<li>Doesn't seem a traversing function <em>per se</em> (at least in some cases), but it still uses <code>os.listdir</code></li>\n</ul>\n</li>\n</ul>\n<p><br>Since these iterate over folders, (in most of the cases) they are inefficient for our problem (there are exceptions, like non wildcarded <em>glob</em>bing - as @ShadowRanger pointed out), so I'm not going to insist on them. Not to mention that in some cases, filename processing might be required.</p>\n</li>\n<li><p><a href=\"https://docs.python.org/3/library/os.html#os.access\" rel=\"nofollow noreferrer\">[Python 3]: os.<strong>access</strong>(<em>path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True</em>)</a> whose behavior is close to <code>os.path.exists</code> (actually it's wider, mainly because of the 2<sup>nd</sup> argument)</p>\n<ul>\n<li><strong>user permissions</strong> might restrict the file &quot;visibility&quot; as the doc states:\n<blockquote>\n<p>...test if the invoking user has the specified access to <em>path</em>. <em>mode</em> should be <a href=\"https://docs.python.org/3/library/os.html#os.F_OK\" rel=\"nofollow noreferrer\">F_OK</a> to test the existence of path...</p>\n</blockquote>\n</li>\n</ul>\n<p><code>os.access(&quot;/tmp&quot;, os.F_OK)</code></p>\n<p>Since I also work in <em>C</em>, I use this method as well because under the hood, it calls <strong>native <em>API</em>s</strong> (again, via <em>&quot;${PYTHON_SRC_DIR}/Modules/posixmodule.c&quot;</em>), but it also opens a gate for possible <strong>user errors</strong>, and it's not as Pythonic as other variants. So, as @AaronHall rightly pointed out, don't use it unless you know what you're doing:</p>\n<ul>\n<li><em>Unix-like</em>: <a href=\"http://man7.org/linux/man-pages/man2/access.2.html\" rel=\"nofollow noreferrer\">[man7]: ACCESS(2)</a> (!!! pay attention to the note about the <strong>security hole</strong> its usage might introduce !!!)</li>\n<li><em>Windows</em>: <a href=\"https://learn.microsoft.com/en-gb/windows/desktop/api/fileapi/nf-fileapi-getfileattributesw\" rel=\"nofollow noreferrer\">[MS.Docs]: GetFileAttributesW function</a></li>\n</ul>\n<p><strong>Note</strong>: calling native <em>API</em>s is also possible via <a href=\"https://docs.python.org/3/library/ctypes.html#module-ctypes\" rel=\"nofollow noreferrer\">[Python 3]: <em>ctypes</em> - A foreign function library for Python</a>, but in most cases it's more complicated.</p>\n<p>(<em><strong>Windows</strong></em>-specific): Since <em>vcruntime*</em> (<em>msvcr*</em>) <em>.dll</em> exports a <a href=\"https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/access-waccess?view=vs-2015\" rel=\"nofollow noreferrer\">[MS.Docs]: _access, _waccess</a> function family as well, here's an example:</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)] on win32\n</code></pre>\n</blockquote>\n<pre class=\"lang-py prettyprint-override\"><code> Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.\n</code></pre>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; import os, ctypes\n&gt;&gt;&gt; ctypes.CDLL(&quot;msvcrt&quot;)._waccess(u&quot;C:\\\\Windows\\\\System32\\\\cmd.exe&quot;, os.F_OK)\n</code></pre>\n</blockquote>\n<pre class=\"lang-py prettyprint-override\"><code> 0\n</code></pre>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; ctypes.CDLL(&quot;msvcrt&quot;)._waccess(u&quot;C:\\\\Windows\\\\System32\\\\cmd.exe.notexist&quot;, os.F_OK)\n</code></pre>\n</blockquote>\n<pre class=\"lang-py prettyprint-override\"><code> -1\n</code></pre>\n<p><strong>Notes</strong>:</p>\n<ul>\n<li>Although it's not a good practice, I'm using <code>os.F_OK</code> in the call, but that's just for clarity (its value is <strong>0</strong>)</li>\n<li>I'm using <em>_waccess</em> so that the same code works on <em>Python3</em> and <em>Python2</em> (in spite of <em><a href=\"https://en.wikipedia.org/wiki/Unicode\" rel=\"nofollow noreferrer\">Unicode</a></em>-related differences between them)</li>\n<li>Although this targets a very specific area, <strong>it was not mentioned in any of the previous answers</strong></li>\n</ul>\n<p><br>The <em>Linux</em> (<em>Ubuntu (<a href=\"https://en.wikipedia.org/wiki/Ubuntu_version_history#Ubuntu_16.04_LTS_.28Xenial_Xerus.29\" rel=\"nofollow noreferrer\">16</a> x64)</em>) counterpart as well:</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>Python 3.5.2 (default, Nov 17 2016, 17:05:23)\n</code></pre>\n</blockquote>\n<pre class=\"lang-py prettyprint-override\"><code> [GCC 5.4.0 20160609] on linux\n Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.\n</code></pre>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; import os, ctypes\n&gt;&gt;&gt; ctypes.CDLL(&quot;/lib/x86_64-linux-gnu/libc.so.6&quot;).access(b&quot;/tmp&quot;, os.F_OK)\n</code></pre>\n</blockquote>\n<pre class=\"lang-py prettyprint-override\"><code> 0\n</code></pre>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; ctypes.CDLL(&quot;/lib/x86_64-linux-gnu/libc.so.6&quot;).access(b&quot;/tmp.notexist&quot;, os.F_OK)\n</code></pre>\n</blockquote>\n<pre class=\"lang-py prettyprint-override\"><code> -1\n</code></pre>\n<p><strong>Notes</strong>:</p>\n<ul>\n<li><p>Instead hardcoding <em>libc</em>'s path (<em>&quot;/lib/x86_64-linux-gnu/libc.so.6&quot;</em>) which may (and most likely, will) vary across systems, <em>None</em> (or the empty string) can be passed to <em>CDLL</em> constructor (<strong><code>ctypes.CDLL(None).access(b&quot;/tmp&quot;, os.F_OK)</code></strong>). According to <a href=\"http://man7.org/linux/man-pages/man3/dlopen.3.html\" rel=\"nofollow noreferrer\">[man7]: DLOPEN(3)</a>:</p>\n<blockquote>\n<p>If <em>filename</em> is NULL, then the returned handle is for the main\nprogram. When given to <strong>dlsym</strong>(), this handle causes a search for a\nsymbol in the main program, followed by all shared objects loaded at\nprogram startup, and then all shared objects loaded by <strong>dlopen</strong>() with\nthe flag <strong>RTLD_GLOBAL</strong>.</p>\n</blockquote>\n</li>\n<li><p>Main (current) program (<em>python</em>) is linked against <em>libc</em>, so its symbols (including <em>access</em>) will be loaded</p>\n</li>\n<li><p>This has to be handled with care, since functions like <em>main</em>, <em>Py_Main</em> and (all the) others are available; calling them could have disastrous effects (on the current program)</p>\n</li>\n<li><p>This doesn't also apply to <em>Windows</em> (but that's not such a big deal, since <em>msvcrt.dll</em> is located in <em>&quot;%SystemRoot%\\System32&quot;</em> which is in <em>%PATH%</em> by default). I wanted to take things further and replicate this behavior on <em>Windows</em> (and submit a patch), but as it turns out, <a href=\"https://learn.microsoft.com/en-gb/windows/desktop/api/libloaderapi/nf-libloaderapi-getprocaddress\" rel=\"nofollow noreferrer\">[MS.Docs]: GetProcAddress function</a> only &quot;sees&quot; <strong>exported</strong> symbols, so unless someone declares the functions in the main executable as <code>__declspec(dllexport)</code> (why on Earth the <em>regular</em> person would do that?), the main program is loadable, but it is pretty much unusable</p>\n</li>\n</ul>\n</li>\n<li><p>Install some third-party module with filesystem capabilities</p>\n<p>Most likely, will rely on one of the ways above (maybe with slight customizations). <br>One example would be (again, <em>Windows</em>-specific) <a href=\"https://github.com/mhammond/pywin32\" rel=\"nofollow noreferrer\">[GitHub]: mhammond/pywin32 - Python for Windows (pywin32) Extensions</a>, which is a <em>Python</em> wrapper over <em>WINAPI</em>s.</p>\n<p>But, since this is more like a workaround, I'm stopping here.</p>\n</li>\n<li><p>Another (lame) workaround (<em>gainarie</em>) is (as I like to call it,) the <em>system administrator</em> approach: use <em>Python</em> as a wrapper to execute shell commands</p>\n<ul>\n<li><p><em>Windows</em>:</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>(py35x64_test) e:\\Work\\Dev\\StackOverflow\\q000082831&gt;&quot;e:\\Work\\Dev\\VEnvs\\py35x64_test\\Scripts\\python.exe&quot; -c &quot;import os; print(os.system('dir /b \\&quot;C:\\\\Windows\\\\System32\\\\cmd.exe\\&quot; &gt; nul 2&gt;&amp;1'))&quot;\n</code></pre>\n</blockquote>\n<pre class=\"lang-py prettyprint-override\"><code> 0\n</code></pre>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>(py35x64_test) e:\\Work\\Dev\\StackOverflow\\q000082831&gt;&quot;e:\\Work\\Dev\\VEnvs\\py35x64_test\\Scripts\\python.exe&quot; -c &quot;import os; print(os.system('dir /b \\&quot;C:\\\\Windows\\\\System32\\\\cmd.exe.notexist\\&quot; &gt; nul 2&gt;&amp;1'))&quot;\n</code></pre>\n</blockquote>\n<pre class=\"lang-py prettyprint-override\"><code> 1\n</code></pre>\n</li>\n<li><p><a href=\"https://en.wikipedia.org/wiki/Unix-like\" rel=\"nofollow noreferrer\">Unix-like</a> (<em>Linux</em> (<em>Ubuntu</em>)):</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>[cfati@cfati-ubtu16x64-0:~]&gt; python3 -c &quot;import os; print(os.system('ls \\&quot;/tmp\\&quot; &gt; /dev/null 2&gt;&amp;1'))&quot;\n</code></pre>\n</blockquote>\n<pre class=\"lang-py prettyprint-override\"><code> 0\n [cfati@cfati-ubtu16x64-0:~]&gt; python3 -c &quot;import os; print(os.system('ls \\&quot;/tmp.notexist\\&quot; &gt; /dev/null 2&gt;&amp;1'))&quot;\n 512\n</code></pre>\n</li>\n</ul>\n</li>\n</ol>\n<p><strong>Bottom line</strong>:</p>\n<ul>\n<li><strong>Do</strong> use <em><strong>try</strong></em> / <em><strong>except</strong></em> / <em><strong>else</strong></em> / <em><strong>finally</strong></em> blocks, because they can prevent you running into a series of nasty problems. A counterexample that I can think of, is performance: such blocks are costly, so try not to place them in code that it's supposed to run hundreds of thousands times per second (but since (in most cases) it involves disk access, it won't be the case).</li>\n</ul>\n" }, { "answer_id": 45605450, "author": "durjoy", "author_id": 6291574, "author_profile": "https://Stackoverflow.com/users/6291574", "pm_score": 5, "selected": false, "text": "<p>If you imported NumPy already for other purposes then there is no need to import other libraries like <code>pathlib</code>, <code>os</code>, <code>paths</code>, etc.</p>\n\n<pre><code>import numpy as np\nnp.DataSource().exists(\"path/to/your/file\")\n</code></pre>\n\n<p>This will return true or false based on its existence.</p>\n" }, { "answer_id": 47629576, "author": "AbstProcDo", "author_id": 7301792, "author_profile": "https://Stackoverflow.com/users/7301792", "pm_score": 6, "selected": false, "text": "<p>Date: 2017-12-04</p>\n<p>Every possible solution has been listed in other answers.</p>\n<p>An intuitive and arguable way to check if a file exists is the following:</p>\n<pre><code>import os\n\nos.path.isfile('~/file.md') # Returns True if exists, else False\n\n# Additionally, check a directory\nos.path.isdir('~/folder') # Returns True if the folder exists, else False\n\n# Check either a directory or a file\nos.path.exists('~/file')\n</code></pre>\n<p>I made an exhaustive cheat sheet for your reference:</p>\n<pre><code># os.path methods in exhaustive cheat sheet\n{'definition': ['dirname',\n 'basename',\n 'abspath',\n 'relpath',\n 'commonpath',\n 'normpath',\n 'realpath'],\n'operation': ['split', 'splitdrive', 'splitext',\n 'join', 'normcase'],\n'compare': ['samefile', 'sameopenfile', 'samestat'],\n'condition': ['isdir',\n 'isfile',\n 'exists',\n 'lexists'\n 'islink',\n 'isabs',\n 'ismount',],\n 'expand': ['expanduser',\n 'expandvars'],\n 'stat': ['getatime', 'getctime', 'getmtime',\n 'getsize']}\n</code></pre>\n" }, { "answer_id": 49092615, "author": "Ali Hallaji", "author_id": 3043331, "author_profile": "https://Stackoverflow.com/users/3043331", "pm_score": 4, "selected": false, "text": "<h2>Check file or directory exists</h2>\n<p>You can follow these three ways:</p>\n<h3>1. Using isfile()</h3>\n<p>Note 1: The <code>os.path.isfile</code> used only for files</p>\n<pre><code>import os.path\nos.path.isfile(filename) # True if file exists\nos.path.isfile(dirname) # False if directory exists\n</code></pre>\n<h3>2. Using <em>exists</em></h3>\n<p>Note 2: The <code>os.path.exists</code> is used for both files and directories</p>\n<pre><code>import os.path\nos.path.exists(filename) # True if file exists\nos.path.exists(dirname) # True if directory exists\n</code></pre>\n<h3>3. The <code>pathlib.Path</code> method (included in Python 3+, installable with pip for Python 2)</h3>\n<pre><code>from pathlib import Path\nPath(filename).exists()\n</code></pre>\n" }, { "answer_id": 53084404, "author": "Vimal Maheedharan", "author_id": 3682968, "author_profile": "https://Stackoverflow.com/users/3682968", "pm_score": 3, "selected": false, "text": "<p>Use:</p>\n<pre><code>import os\n\n# For testing purposes the arguments defaulted to the current folder and file.\n# returns True if file found\ndef file_exists(FOLDER_PATH='../', FILE_NAME=__file__):\n return os.path.isdir(FOLDER_PATH) \\\n and os.path.isfile(os.path.join(FOLDER_PATH, FILE_NAME))\n</code></pre>\n<p>It is basically a folder check, and then a file check with the proper directory separator using <em><a href=\"https://docs.python.org/3.8/library/os.path.html#os.path.join\" rel=\"nofollow noreferrer\">os.path.join</a></em>.</p>\n" }, { "answer_id": 59923701, "author": "Gopinath", "author_id": 6571165, "author_profile": "https://Stackoverflow.com/users/6571165", "pm_score": 3, "selected": false, "text": "<p><strong>exists()</strong> and <strong>is_file()</strong> methods of '<strong>Path</strong>' object can be used for checking if a given path exists and is a file.</p>\n\n<p><strong>Python 3 program to check if a file exists:</strong></p>\n\n<pre><code># File name: check-if-file-exists.py\n\nfrom pathlib import Path\n\nfilePath = Path(input(\"Enter path of the file to be found: \"))\n\nif filePath.exists() and filePath.is_file():\n print(\"Success: File exists\")\nelse:\n print(\"Error: File does not exist\")\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<blockquote>\n <p><strong>$ python3 check-if-file-exists.py</strong> </p>\n \n <p>Enter path of the file to be found: <strong><em>/Users/macuser1/stack-overflow/index.html</em></strong> </p>\n \n <p>Success: <strong><em>File exists</em></strong></p>\n \n <p><strong>$ python3 check-if-file-exists.py</strong> </p>\n \n <p>Enter path of the file to be found: <strong><em>hghjg jghj</em></strong></p>\n \n <p>Error: <strong><em>File does not exist</em></strong></p>\n</blockquote>\n" }, { "answer_id": 61754517, "author": "Devbrat Shukla", "author_id": 6487422, "author_profile": "https://Stackoverflow.com/users/6487422", "pm_score": 3, "selected": false, "text": "<p>Use <a href=\"https://www.geeksforgeeks.org/python-os-path-exists-method/\" rel=\"noreferrer\">os.path.exists()</a> to check whether file exists or not:</p>\n<pre><code>def fileAtLocation(filename,path):\n return os.path.exists(path + filename)\n \n\nfilename=&quot;dummy.txt&quot;\npath = &quot;/home/ie/SachinSaga/scripts/subscription_unit_reader_file/&quot;\n\n\nif fileAtLocation(filename,path):\n print('file found at location..')\nelse:\n print('file not found at location..')\n</code></pre>\n" }, { "answer_id": 65857751, "author": "Memin", "author_id": 2234161, "author_profile": "https://Stackoverflow.com/users/2234161", "pm_score": 7, "selected": false, "text": "<p><strong>TL;DR</strong> <br>\nThe answer is: use the <strong><code>pathlib</code></strong> module</p>\n<hr />\n<p><strong>Pathlib</strong> is probably the most modern and convenient way for almost all of the file operations. For the existence of a <strong>file</strong> or a <strong>folder</strong> a single line of code is enough. If file is not exists, it will <em><strong>not</strong></em> throw any exception.</p>\n<pre><code>from pathlib import Path\n\nif Path(&quot;myfile.txt&quot;).exists(): # works for both file and folders\n # do your cool stuff...\n</code></pre>\n<p>The <code>pathlib</code> module was introduced in Python 3.4, so you need to have Python 3.4+. This library makes your life much easier while working with files and folders, and it is pretty to use. Here is more documentation about it: <em><a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\">pathlib — Object-oriented filesystem paths</a></em>.</p>\n<p>BTW, if you are going to reuse the path, then it is better to assign it to a variable.</p>\n<p>So it will become:</p>\n<pre><code>from pathlib import Path\n\np = Path(&quot;loc/of/myfile.txt&quot;)\nif p.exists(): # works for both file and folders\n # do stuffs...\n#reuse 'p' if needed.\n</code></pre>\n" }, { "answer_id": 66993660, "author": "IsraelW", "author_id": 13950438, "author_profile": "https://Stackoverflow.com/users/13950438", "pm_score": 2, "selected": false, "text": "<p>Another possible option is to check whether the filename is in the directory using os.listdir():</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\nif 'foo.txt' in os.listdir():\n # Do things\n</code></pre>\n<p>This will return true if it is and false if not.</p>\n" }, { "answer_id": 73083229, "author": "Ban_Midou", "author_id": 3035075, "author_profile": "https://Stackoverflow.com/users/3035075", "pm_score": 0, "selected": false, "text": "<p>This is how I found a list of files (in these images) in one folder and searched it in a folder (with subfolders):</p>\n<pre><code># This script concatenates JavaScript files into a unified JavaScript file to reduce server round-trips\n\nimport os\nimport string\nimport math\nimport ntpath\nimport sys\n\n#import pyodbc\n\nimport gzip\nimport shutil\n\nimport hashlib\n\n# BUF_SIZE is totally arbitrary, change for your app!\nBUF_SIZE = 65536 # Let’s read stuff in 64 kilobyte chunks\n\n# Iterate over all JavaScript files in the folder and combine them\nfilenames = []\nshortfilenames = []\n\nimgfilenames = []\nimgshortfilenames = []\n\n# Get a unified path so we can stop dancing with user paths.\n# Determine where files are on this machine (%TEMP% directory and application installation directory)\nif '.exe' in sys.argv[0]: # if getattr(sys, 'frozen', False):\n RootPath = os.path.abspath(os.path.join(__file__, &quot;..\\\\&quot;))\n\nelif __file__:\n RootPath = os.path.abspath(os.path.join(__file__, &quot;..\\\\&quot;))\n\nprint (&quot;\\n storage of image files RootPath: %s\\n&quot; %RootPath)\n\nFolderPath = &quot;D:\\\\TFS-FARM1\\\\StoneSoup_STS\\\\SDLC\\\\Build\\\\Code\\\\StoneSoup_Refactor\\\\StoneSoupUI\\\\Images&quot;\nprint (&quot;\\n storage of image files in folder to search: %s\\n&quot; %FolderPath)\n\nfor root, directories, filenames2 in os.walk(FolderPath):\n for filename in filenames2:\n fullname = os.path.join(root, filename)\n filenames.append(fullname)\n shortfilenames.append(filename)\n\nfor i, fname in enumerate(shortfilenames):\n print(&quot;%s - %s&quot; % (i+1, fname))\n\nfor root, directories, filenames2 in os.walk(RootPath):\n for filename in filenames2:\n fullname = os.path.join(root, filename)\n imgfilenames.append(fullname)\n imgshortfilenames.append(filename)\n\nfor i, fname in enumerate(imgshortfilenames):\n print(&quot;%s - %s&quot; % (i+1, fname))\n\nfor i, fname in enumerate(imgshortfilenames):\n if fname in shortfilenames:\n print(&quot;%s - %s exists&quot; % (i+1, fname))\n else:\n print(&quot;%s - %s ABSENT&quot; % (i+1, fname))\n</code></pre>\n" } ]
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 about.</p>\n\n<p>Also I don't like the \"magic\" that puts the args in the method parameter for the first way.</p>\n" }, { "answer_id": 82883, "author": "user12861", "author_id": 12861, "author_profile": "https://Stackoverflow.com/users/12861", "pm_score": 2, "selected": false, "text": "<p>The first way is better because it's simpler.</p>\n" }, { "answer_id": 82922, "author": "Thomas", "author_id": 4980, "author_profile": "https://Stackoverflow.com/users/4980", "pm_score": 2, "selected": false, "text": "<p>Do you know getopt? There is a port for C# on codeplex: <a href=\"http://www.codeplex.com/getopt\" rel=\"nofollow noreferrer\">http://www.codeplex.com/getopt</a></p>\n" }, { "answer_id": 368484, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>To me the first way seems more intuitive because that is how I have been doing it since my C/C++ days.</p>\n\n<p>If your commandline has one too many switches please do take a look at getopt that Thomas recommends. It's quite useful. I haven't had a look at C# port of the same though.</p>\n\n<p>Regards,</p>\n\n<p>kgr</p>\n" } ]
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 operation's DispatcherPriority sufficiently low enough, the layout operations will occur, and you will be good to go.</p>\n\n<pre><code>StatusBarMessageText.Text = \"Loading Configuration Settings...\";\nthis.Dispatcher.BeginInvoke(new Action(LoadSettingsGridData), DispatcherPriority.Render);\nthis.Dispatcher.BeginInvoke(new Action(() =&gt; StatusBarMessageText.Text = \"Done\"), DispatcherPriority.Render);\n</code></pre>\n" }, { "answer_id": 89053, "author": "mrbradleyt", "author_id": 2744, "author_profile": "https://Stackoverflow.com/users/2744", "pm_score": 0, "selected": false, "text": "<p>In reading the article by Shawn Wildermuth <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163328.aspx\" rel=\"nofollow noreferrer\">WPF Threads: Build More Responsive Apps With The Dispatcher</a>.</p>\n\n<p>I came accross the following, which states you can use the Background Worker just like you could in WindowsForms. Fancy that:</p>\n\n<blockquote>\n <p>BackgroundWorker\n Now that you have a sense of how the Dispatcher works, you might be surprised to know that you will not find use for it in most cases. In Windows Forms 2.0, Microsoft introduced a class for non-UI thread handling to simplify the development model for user interface developers. This class is called the BackgroundWorker. Figure 7 shows typical usage of the BackgroundWorker class.</p>\n \n <h3>Figure 7 Using a BackgroundWorker in WPF</h3>\n\n<pre><code>BackgroundWorker _backgroundWorker = new BackgroundWorker();\n\n...\n\n// Set up the Background Worker Events\n_backgroundWorker.DoWork += _backgroundWorker_DoWork;\nbackgroundWorker.RunWorkerCompleted += \n _backgroundWorker_RunWorkerCompleted;\n\n// Run the Background Worker\n_backgroundWorker.RunWorkerAsync(5000);\n\n...\n\n// Worker Method\nvoid _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)\n{\n // Do something\n}\n\n// Completed Method\nvoid _backgroundWorker_RunWorkerCompleted(\n object sender, \n RunWorkerCompletedEventArgs e)\n{\n if (e.Cancelled)\n {\n statusText.Text = \"Cancelled\";\n }\n else if (e.Error != null) \n {\n statusText.Text = \"Exception Thrown\";\n }\n else \n {\n statusText.Text = \"Completed\";\n }\n}\n</code></pre>\n \n <p>The BackgroundWorker component works well with WPF because underneath the covers it uses the AsyncOperationManager class, which in turn uses the SynchronizationContext class to deal with synchronization. In Windows Forms, the AsyncOperationManager hands off a WindowsFormsSynchronizationContext class that derives from the SynchronizationContext class. Likewise, in ASP.NET it works with a different derivation of SynchronizationContext called AspNetSynchronizationContext. These SynchronizationContext-derived classes know how to handle the cross-thread synchronization of method invocation.</p>\n \n <p>In WPF, this model is extended with a DispatcherSynchronizationContext class. By using BackgroundWorker, the Dispatcher is being employed automatically to invoke cross-thread method calls. The good news is that since you are probably already familiar with this common pattern, you can continue using BackgroundWorker in your new WPF projects.</p>\n</blockquote>\n" }, { "answer_id": 3383010, "author": "Ernest", "author_id": 408037, "author_profile": "https://Stackoverflow.com/users/408037", "pm_score": 5, "selected": false, "text": "<p>Best and simplest:</p>\n\n<pre><code>using(var d = Dispatcher.DisableProcessing())\n{\n /* your work... Use dispacher.begininvoke... */\n}\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>IDisposable d;\n\ntry\n{\n d = Dispatcher.DisableProcessing();\n /* your work... Use dispacher.begininvoke... */\n} finally {\n d.Dispose();\n}\n</code></pre>\n" } ]
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 dynamically creating extenders as they weren't being added to the updatePanel content.</p>\n\n<p>I also think you have to do somethin with the ScriptManager (registering the extender) but I could be mistaken (I don't have access to the code I did dynamic extenders at the moment).</p>\n" }, { "answer_id": 83139, "author": "Jesse Millikan", "author_id": 7526, "author_profile": "https://Stackoverflow.com/users/7526", "pm_score": 2, "selected": true, "text": "<p>See <a href=\"http://msdn.microsoft.com/en-us/library/ms178472.aspx\" rel=\"nofollow noreferrer\">ASP.NET Page Life Cycle Overview</a> 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.</p>\n\n<p>If you are doing this in a web user control or custom control, though, override CreateChildControls and do this in there. </p>\n\n<p>Post a more complete code example if that doesn't help.</p>\n" }, { "answer_id": 33173467, "author": "Raghu", "author_id": 5454305, "author_profile": "https://Stackoverflow.com/users/5454305", "pm_score": 0, "selected": false, "text": "<p>Provide the proper TargetControlID value to MaskedEditExtender</p>\n" } ]
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 structure and export the XML. Then I'd cache it to disk with file_put_contents().</p>\n" }, { "answer_id": 82902, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 1, "selected": false, "text": "<p>I've used <a href=\"http://www.bitfolge.de/rsscreator-en.html\" rel=\"nofollow noreferrer\">this LGPL-licensed feedcreator class</a> in the past and it worked quite well for the very simple use I had for it.</p>\n" }, { "answer_id": 82904, "author": "Andrew Taylor", "author_id": 1776, "author_profile": "https://Stackoverflow.com/users/1776", "pm_score": 0, "selected": false, "text": "<p>PHP5 now comes with the <code>SimpleXML</code> extension, it's a pretty quick way to build valid XML if your needs aren't complicated.</p>\n\n<p>However, the problem you're suggesting doesn't seem to an issue of implementation more a problem of syntax. Perhaps you could update your question with a code example, or, a copy of the XML that is produced.</p>\n" }, { "answer_id": 82936, "author": "Paweł Hajdan", "author_id": 9403, "author_profile": "https://Stackoverflow.com/users/9403", "pm_score": 0, "selected": false, "text": "<p>Not a full answer, but you <strong>don't have to parse</strong> your own XML. It will hurt performance and reliability.</p>\n\n<p>But definitely make sure it is <strong>well-formed</strong>. It shouldn't be very hard if you generate it by hand or using general-purpose tools. Or maybe your included HTML ruins it?</p>\n" }, { "answer_id": 84216, "author": "Jarett Millard", "author_id": 15882, "author_profile": "https://Stackoverflow.com/users/15882", "pm_score": 0, "selected": false, "text": "<p>There are lots of things that can make XML malformed. It might be a problem with character entities (a '&lt;', '>', or '&amp;' in the data between the XML tags). Try running anything output from a database through htmlentities() when you concatenate the string. Do you have an example of the generated XML for us to look at so we can see where the problem is?</p>\n" }, { "answer_id": 84601, "author": "Veynom", "author_id": 11670, "author_profile": "https://Stackoverflow.com/users/11670", "pm_score": 3, "selected": true, "text": "<p>At swcombine.com we use <a href=\"http://feedcreator.org/\" rel=\"nofollow noreferrer\">Feedcreator</a>. Use that one and your problem will be gone. :)</p>\n\n<p>Here is the PHP code to use it once installed:</p>\n\n<pre><code>function feed_simnews() {\n $objRSS = new UniversalFeedCreator();\n $objRSS-&gt;title = 'My News';\n $objRSS-&gt;link = 'http://link.to/news.php';\n $objRSS-&gt;description = 'daily news from me';\n $objRSS-&gt;xsl = 'http://link.to/feeds/feedxsl.xsl';\n $objRSS-&gt;language = 'en';\n $objRSS-&gt;copyright = 'Copyright: Mine!';\n $objRSS-&gt;webmaster = '[email protected]';\n $objRSS-&gt;syndicationURL = 'http://link.to/news/simnews.php';\n $objRSS-&gt;ttl = 180;\n\n $objImage = new FeedImage();\n $objImage-&gt;title = 'my logo';\n $objImage-&gt;url = 'http://link.to/feeds/logo.jpg';\n $objImage-&gt;link = 'http://link.to';\n $objImage-&gt;description = 'Feed provided by link.to. Click to visit.';\n $objImage-&gt;width = 120;\n $objImage-&gt;height = 60;\n $objRSS-&gt;image = $objImage;\n\n //Function retrieving an array of your news from date start to last week\n $colNews = getYourNews(array('start_date' =&gt; 'Last week'));\n\n foreach($colNews as $p) {\n $objItem = new FeedItem();\n $objItem-&gt;title = $p-&gt;title;\n $objItem-&gt;description = $p-&gt;body;\n $objItem-&gt;link = $p-&gt;link;\n $objItem-&gt;date = $p-&gt;date;\n $objItem-&gt;author = $p-&gt;author;\n $objItem-&gt;guid = $p-&gt;guid;\n\n $objRSS-&gt;addItem($objItem);\n }\n\n $objRSS-&gt;saveFeed('RSS2.0', 'http://link.to/feeds/news.xml', false);\n};\n</code></pre>\n\n<p>Quite KISS. :)</p>\n" } ]
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 = '[email protected]'; $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 * FROM dbname.sqlite_master WHERE type='table';\n</code></pre>\n\n<p>And then manually go through each table with a <code>SELECT</code> or similar to look at the rows.</p>\n\n<p>The <code>.DUMP</code> and <code>.SCHEMA</code> commands doesn't appear to see the database at all.</p>\n" }, { "answer_id": 82899, "author": "Mark Janssen", "author_id": 15828, "author_profile": "https://Stackoverflow.com/users/15828", "pm_score": 10, "selected": false, "text": "<p>There are a few steps to see the tables in an SQLite database:</p>\n\n<ol>\n<li><p>List the tables in your database:</p>\n\n<pre><code>.tables\n</code></pre></li>\n<li><p>List how the table looks:</p>\n\n<pre><code>.schema tablename\n</code></pre></li>\n<li><p>Print the entire table:</p>\n\n<pre><code>SELECT * FROM tablename;\n</code></pre></li>\n<li><p>List all of the available SQLite prompt commands:</p>\n\n<pre><code>.help\n</code></pre></li>\n</ol>\n" }, { "answer_id": 82917, "author": "Rafał Dowgird", "author_id": 12166, "author_profile": "https://Stackoverflow.com/users/12166", "pm_score": 5, "selected": false, "text": "<p>To list the tables you can also do:</p>\n\n<pre><code>SELECT name FROM sqlite_master\nWHERE type='table';\n</code></pre>\n" }, { "answer_id": 82920, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>The \".schema\" commando will list available tables and their rows, by showing you the statement used to create said tables:</p>\n\n<pre>\nsqlite> create table_a (id int, a int, b int);\nsqlite> .schema table_a\nCREATE TABLE table_a (id int, a int, b int);\n</pre>\n" }, { "answer_id": 82930, "author": "Christian Davén", "author_id": 12534, "author_profile": "https://Stackoverflow.com/users/12534", "pm_score": 8, "selected": false, "text": "<p>To show all tables, use</p>\n\n<pre><code>SELECT name FROM sqlite_master WHERE type = \"table\"\n</code></pre>\n\n<p>To show all rows, I guess you can iterate through all tables and just do a SELECT * on each one. But maybe a DUMP is what you're after?</p>\n" }, { "answer_id": 82935, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>There is a command available for this on the SQLite command line:</p>\n\n<pre><code>.tables ?PATTERN? List names of tables matching a LIKE pattern\n</code></pre>\n\n<p>Which converts to the following SQL:</p>\n\n<pre><code>SELECT name FROM sqlite_master\nWHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%'\nUNION ALL\nSELECT name FROM sqlite_temp_master\nWHERE type IN ('table','view')\nORDER BY 1\n</code></pre>\n" }, { "answer_id": 83195, "author": "Anthony Williams", "author_id": 5597, "author_profile": "https://Stackoverflow.com/users/5597", "pm_score": 10, "selected": true, "text": "<p>The <code>.tables</code>, and <code>.schema</code> \"helper\" functions don't look into ATTACHed databases: they just query the <code>SQLITE_MASTER</code> table for the \"main\" database. Consequently, if you used</p>\n\n<pre><code>ATTACH some_file.db AS my_db;\n</code></pre>\n\n<p>then you need to do</p>\n\n<pre><code>SELECT name FROM my_db.sqlite_master WHERE type='table';\n</code></pre>\n\n<p>Note that temporary tables don't show up with <code>.tables</code> either: you have to list <code>sqlite_temp_master</code> for that:</p>\n\n<pre><code>SELECT name FROM sqlite_temp_master WHERE type='table';\n</code></pre>\n" }, { "answer_id": 494643, "author": "Noah", "author_id": 12113, "author_profile": "https://Stackoverflow.com/users/12113", "pm_score": 4, "selected": false, "text": "<p>The easiest way to do this is to open the database directly and use the <code>.dump</code> command, rather than attaching it after invoking the SQLite&nbsp;3 shell tool.</p>\n\n<p>So... (assume your OS command line prompt is $) instead of <code>$sqlite3</code>:</p>\n\n<pre><code>sqlite3&gt; ATTACH database.sqlite as \"attached\"\n</code></pre>\n\n<p>From your OS command line, open the database directly:</p>\n\n<pre><code>$sqlite3 database.sqlite\nsqlite3&gt; .dump\n</code></pre>\n" }, { "answer_id": 2986841, "author": "Luiz Geron", "author_id": 142548, "author_profile": "https://Stackoverflow.com/users/142548", "pm_score": 5, "selected": false, "text": "<p>Try <code>PRAGMA table_info(table-name);</code><br>\n<a href=\"http://www.sqlite.org/pragma.html#schema\" rel=\"noreferrer\">http://www.sqlite.org/pragma.html#schema</a></p>\n" }, { "answer_id": 7252488, "author": "Antony.H", "author_id": 822864, "author_profile": "https://Stackoverflow.com/users/822864", "pm_score": 6, "selected": false, "text": "<p>Use <code>.help</code> to check for available commands.</p>\n\n<pre><code>.table\n</code></pre>\n\n<p>This command would show all tables under your current database.</p>\n" }, { "answer_id": 14623907, "author": "Alix Axel", "author_id": 89771, "author_profile": "https://Stackoverflow.com/users/89771", "pm_score": 4, "selected": false, "text": "<p>According to <a href=\"http://www.sqlite.org/sqlite.html\" rel=\"nofollow noreferrer\">the documentation</a>, the equivalent of MySQL's <code>SHOW TABLES;</code> is:</p>\n<blockquote>\n<p>The &quot;.tables&quot; command is similar to setting list mode then executing\nthe following query:</p>\n</blockquote>\n<pre><code>SELECT name FROM sqlite_master\n WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%'\nUNION ALL\nSELECT name FROM sqlite_temp_master\n WHERE type IN ('table','view')\nORDER BY 1;\n</code></pre>\n<p>However, if you are checking if a single table exists (or to get its details), see <a href=\"https://stackoverflow.com/a/2986841/89771\">LuizGeron's answer</a>.</p>\n" }, { "answer_id": 25734826, "author": "pepper", "author_id": 2146169, "author_profile": "https://Stackoverflow.com/users/2146169", "pm_score": 4, "selected": false, "text": "<p>As of the latest versions of SQLite&nbsp;3 you can issue:</p>\n\n<pre><code>.fullschema\n</code></pre>\n\n<p>to see all of your create statements.</p>\n" }, { "answer_id": 29422734, "author": "oiyio", "author_id": 1308990, "author_profile": "https://Stackoverflow.com/users/1308990", "pm_score": 3, "selected": false, "text": "<p>Since nobody has mentioned about the official reference of SQLite, I think it may be useful to refer to it under this heading:</p>\n\n<p><a href=\"https://www.sqlite.org/cli.html\" rel=\"noreferrer\">https://www.sqlite.org/cli.html</a></p>\n\n<p>You can manipulate your database using the commands described in this link. Besides, <strong>if you are using Windows OS</strong> and do not know where the command shell is, that is in the SQLite's site: </p>\n\n<p><a href=\"https://www.sqlite.org/download.html\" rel=\"noreferrer\">https://www.sqlite.org/download.html</a></p>\n\n<p>After downloading it, <strong>click sqlite3.exe file to initialize the SQLite command shell</strong>. When it is initialized, by default this SQLite session is using an in-memory database, not a file on disk, and so all changes will be lost when the session exits. To use a persistent disk file as the database, enter the \".open ex1.db\" command immediately after the terminal window starts up.</p>\n\n<p>The example above causes the database file named \"ex1.db\" to be opened and used, and created if it does not previously exist. You might want to use a full pathname to ensure that the file is in the directory that you think it is in. Use forward-slashes as the directory separator character. In other words use \"c:/work/ex1.db\", not \"c:\\work\\ex1.db\".</p>\n\n<p>To see all tables in the database you have previously chosen, type the command <strong>.tables</strong> as it is said in the above link.</p>\n\n<p>If you work in Windows, I think it might be useful to move this sqlite.exe file to same folder with the other Python files. In this way, the Python file writes to and the SQLite shell reads from .db files are in the same path.</p>\n" }, { "answer_id": 31763337, "author": "GameLoading", "author_id": 563848, "author_profile": "https://Stackoverflow.com/users/563848", "pm_score": 5, "selected": false, "text": "<p>I use this query to get it:</p>\n\n<pre><code>SELECT name FROM sqlite_master WHERE type='table'\n</code></pre>\n\n<p>And to use in iOS:</p>\n\n<pre><code>NSString *aStrQuery=[NSString stringWithFormat:@\"SELECT name FROM sqlite_master WHERE type='table'\"];\n</code></pre>\n" }, { "answer_id": 33097341, "author": "Mrityunjay Singh", "author_id": 1590898, "author_profile": "https://Stackoverflow.com/users/1590898", "pm_score": 3, "selected": false, "text": "<p>Use:</p>\n\n<pre><code>import sqlite3\n\nTABLE_LIST_QUERY = \"SELECT * FROM sqlite_master where type='table'\"\n</code></pre>\n" }, { "answer_id": 40031557, "author": "openwonk", "author_id": 4259761, "author_profile": "https://Stackoverflow.com/users/4259761", "pm_score": 4, "selected": false, "text": "<p>Via a <code>union all</code>, combine all tables into one list.</p>\n\n<pre><code>select name\nfrom sqlite_master \nwhere type='table'\n\nunion all \n\nselect name \nfrom sqlite_temp_master \nwhere type='table'\n</code></pre>\n" }, { "answer_id": 47247535, "author": "Klaas-Z4us-V", "author_id": 1869683, "author_profile": "https://Stackoverflow.com/users/1869683", "pm_score": 3, "selected": false, "text": "<p>Use <em>.da</em> to see all databases - one is called '<strong>main</strong>'.</p>\n<p>Tables of this database can be seen by:</p>\n<pre><code>SELECT distinct tbl_name from sqlite_master order by 1;\n</code></pre>\n<p>The attached databases need prefixes you chose with AS in the statement ATTACH, e.g., <strong>aa</strong> (, bb, cc...) so:</p>\n<pre><code>SELECT distinct tbl_name from **aa.sqlite_master** order by 1;\n</code></pre>\n<p>Note that here you get the views as well. To exclude these add:</p>\n<pre><code>where type = 'table'\n</code></pre>\n<p>before ' order'</p>\n" } ]
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" }, { "answer_id": 82925, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>That would be a <code>Dictionary&lt;int, SomeObject&gt; myDictionary</code>, and you would do it by:</p>\n\n<pre><code>foreach(SomeObject _object in myDictionary.Values.Reverse())\n{\n}\n</code></pre>\n" }, { "answer_id": 82926, "author": "Timothy Carter", "author_id": 4660, "author_profile": "https://Stackoverflow.com/users/4660", "pm_score": 0, "selected": false, "text": "<p>If the ordering is most important, you could you a Stack and create a simple struct to store your int, Object pair.</p>\n" }, { "answer_id": 82927, "author": "Chris Wenham", "author_id": 5548, "author_profile": "https://Stackoverflow.com/users/5548", "pm_score": 4, "selected": false, "text": "<p>If you have <strong>.NET 3.5</strong> you can use the .Reverse() extension method on IEnumerables. For example:</p>\n<pre><code>foreach (object o in myDictionary.Values.Reverse())\n{\n // Do stuff to object\n}\n</code></pre>\n" }, { "answer_id": 82931, "author": "Stormenet", "author_id": 2090, "author_profile": "https://Stackoverflow.com/users/2090", "pm_score": 1, "selected": false, "text": "<p>The only way I can come up with in <strong>.NET 2.0</strong> is to first copy all the values to a List, reverse the list and then run the foreach on that list:</p>\n\n<pre><code>Dictionary&lt;int, object&gt; d;\nList&lt;object&gt; tmplist;\nforeach (object o in d.Values) tmplist.Add(s);\ntmplist.Reverse();\nforeach (object o in tmplist) {\n //Do stuff\n}\n</code></pre>\n" }, { "answer_id": 82968, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 2, "selected": false, "text": "<p>I agree with @leppie, but think you deserve an answer to the question in general. It could be that you meant for the question to be in general, but accidentally picked a bad data structure. The order of the values in a dictionary should be considered implementation-specific; according to the documentation it is always the same order as the keys, but this order is unspecified as well.</p>\n\n<p>Anyway, there's not a straightforward way to make <code>foreach</code> work in reverse. It's syntactic sugar to using the class's enumerator, and enumerators can only travel in one direction. Technically the answer could be \"reverse the collection, then enumerate\", but I think this is a case where you'll just have to use a \"backwards\" for loop:</p>\n\n<pre><code>for (int i = myCollection.Length - 1; i >= 0; i--)\n{\n // do something\n}</code></pre>\n" }, { "answer_id": 83006, "author": "Gord", "author_id": 12560, "author_profile": "https://Stackoverflow.com/users/12560", "pm_score": 0, "selected": false, "text": "<p>If you want a dictionary type collection but you need to maintain the insertion order you can look into the KeyedCollection\n<a href=\"http://msdn.microsoft.com/en-us/library/ms132438.aspx\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>It is a merger between a dictionary and a list. That way you can access elements in the collection via the key or the insertion index.</p>\n\n<p>The only gotcha is if your element being stored in the collection has to have an int key. If you could change that to a string or another type (Guid Mabye). Since collection<a href=\"http://msdn.microsoft.com/en-us/library/ms132438.aspx\" rel=\"nofollow noreferrer\">1</a> will be searching for the key of 1 rather than the index of 1.</p>\n" }, { "answer_id": 83041, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 0, "selected": false, "text": "<p>A standard <code>for</code> loop would be best. You don't have to worry about the processing overhead of reversing the collection.</p>\n" }, { "answer_id": 83055, "author": "Jonathan", "author_id": 6910, "author_profile": "https://Stackoverflow.com/users/6910", "pm_score": 5, "selected": true, "text": "<p>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.</p>\n\n<pre><code>SortedList sCol = new SortedList();\n\nsCol.Add(\"bee\", \"Some extended string matching bee\");\nsCol.Add(\"ay\", \"value matching ay\");\nsCol.Add(\"cee\", \"Just a standard cee\");\n\n// Go through it backwards.\nfor (int i = sCol.Count - 1; i &gt;=0 ; i--)\n Console.WriteLine(\"sCol[\" + i.ToString() + \"] = \" + sCol.GetByIndex(i));\n\n// Reference By Key\nforeach (string i in sCol.Keys)\n Console.WriteLine(\"sCol[\" + i + \"] = \" + sCol[i]);\n\n// Enumerate all values\nforeach (string i in sCol.Values)\n Console.WriteLine(i);\n</code></pre>\n\n<p>It's worth noting that a sorted list stores key/value pairs sorted by key only.</p>\n" }, { "answer_id": 83125, "author": "Dave Van den Eynde", "author_id": 455874, "author_profile": "https://Stackoverflow.com/users/455874", "pm_score": 2, "selected": false, "text": "<p>Actually, in C# 2.0 you can create your own iterator that traverses a container in reverse. Then, you can use that iterator in your foreach statement. But your iterator would have to have a way of navigating the container in the first place. If it's a simple array, it could go backwards like this:</p>\n\n<pre><code>static IEnumerable&lt;T&gt; CreateReverseIterator&lt;T&gt;(IList&lt;T&gt; list)\n{\n int count = list.Count;\n for (int i = count - 1; i &gt;= 0; --i)\n {\n yield return list[i];\n }\n}\n</code></pre>\n\n<p>But of course you can't do that with a Dictionary as it doesn't implement IList or provides an indexer. Saying that a Dictionary does not have order is not true: of course it has order. That order can even be useful if you know what it is.</p>\n\n<p>For a solution to your problem: I'd say copy the elements to an array, and use the above method to traverse it in reverse. Like this:</p>\n\n<pre><code>static void Main(string[] args)\n{\n Dictionary&lt;int, string&gt; dict = new Dictionary&lt;int, string&gt;();\n\n dict[1] = \"value1\";\n dict[2] = \"value2\";\n dict[3] = \"value3\";\n\n foreach (KeyValuePair&lt;int, string&gt; item in dict)\n {\n Console.WriteLine(\"Key : {0}, Value: {1}\", new object[] { item.Key, item.Value });\n }\n\n string[] values = new string[dict.Values.Count];\n dict.Values.CopyTo(values, 0);\n\n foreach (string value in CreateReverseIterator(values))\n {\n Console.WriteLine(\"Value: {0}\", value);\n }\n\n}\n</code></pre>\n\n<p>Copying your values to an array may seem like a bad idea, but depending on the type of value it's not really that bad. You might just be copying references!</p>\n" }, { "answer_id": 83350, "author": "Nathan Baulch", "author_id": 8799, "author_profile": "https://Stackoverflow.com/users/8799", "pm_score": 0, "selected": false, "text": "<p>You can use the <a href=\"http://en.wikipedia.org/wiki/Language_Integrated_Query#LINQ_to_Objects\" rel=\"nofollow noreferrer\">LINQ&nbsp;to&nbsp;Objects</a> Enumerable.Reverse() function in .NET 2.0 using <a href=\"http://www.albahari.com/nutshell/linqbridge.html\" rel=\"nofollow noreferrer\">LinqBridge</a>.</p>\n" }, { "answer_id": 83467, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "<p>Literal answer:</p>\n\n<pre><code>Dictionary&lt;int, SomeObject&gt; myDictionary = new Dictionary&lt;int, SomeObject&gt;();\n\nforeach (var pair in myDictionary.OrderByDescending(i =&gt; i.Key))\n{\n //Observe pair.Key\n //Do stuff to pair.Value\n}\n</code></pre>\n" }, { "answer_id": 83683, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 2, "selected": false, "text": "<p>If you don't have .NET 3.5 and therefore the Reverse extension method you can implement your own. I'd guess it probably generates an intermediate list (when necessary) and iterates it in reverse, something like the following:</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; Reverse&lt;T&gt;(IEnumerable&lt;T&gt; items)\n{\n IList&lt;T&gt; list = items as IList&lt;T&gt;;\n if (list == null) list = new List&lt;T&gt;(items);\n for (int i = list.Count - 1; i &gt;= 0; i-- )\n {\n yield return list[i];\n }\n}\n</code></pre>\n" }, { "answer_id": 12224766, "author": "Marvin", "author_id": 1640001, "author_profile": "https://Stackoverflow.com/users/1640001", "pm_score": -1, "selected": false, "text": "<pre><code>foreach (Sample in Samples)\n\ntry the following:\n\nInt32 nEndingSample = Samples.Count - 1;\n\nfor (i = nEndingSample; i &gt;= 0; i--)\n{\n x = Samples[i].x;\n y = Samples[i].y;\n}\n</code></pre>\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 the JS to do the client validation are you?</p>\n" }, { "answer_id": 82986, "author": "dbugger", "author_id": 15754, "author_profile": "https://Stackoverflow.com/users/15754", "pm_score": 2, "selected": true, "text": "<p>Validation Groups were not added to ASP.NET until version 2.0. This is a 1.1 question. </p>\n\n<p>Double check your setting and make sure you are not overwriting it in the code behind. </p>\n" } ]
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 value of the R,G,B components in the pixel respectively as long as they're under 255, this would gradually shift the color of the sprite towards white. Hey that rhymes.</p>\n" }, { "answer_id": 83306, "author": "Joel Martinez", "author_id": 5416, "author_profile": "https://Stackoverflow.com/users/5416", "pm_score": 2, "selected": false, "text": "<p>I think this is what you're looking for </p>\n\n<pre><code>sampler2D baseMap;\n\nstruct PS_INPUT \n{\n float2 Texcoord : TEXCOORD0;\n\n};\n\nfloat4 ps_main( PS_INPUT Input ) : COLOR0\n{\n float4 color = tex2D( baseMap, Input.Texcoord );\n return float4(1.0f, 1.0f, 1.0f, color.w);\n}\n</code></pre>\n\n<p>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.</p>\n" }, { "answer_id": 86131, "author": "Adi", "author_id": 9090, "author_profile": "https://Stackoverflow.com/users/9090", "pm_score": 1, "selected": false, "text": "<p>I attach the documentation page from MS, and if you follow all the steps you should get it up and running in no time.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb203872(MSDN.9).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb203872(MSDN.9).aspx</a></p>\n\n<p>To sum it up - you need to create and effect file (combined of the code above which is indeed correct for your purposes), , add it to your project, and then in the source file load it and use it during the render as explained in the link.</p>\n\n<p>BTW: I don't quite remember the SpriteBatch (since I chose to write my own, it's too restrictive), but as I recall you might need to set the effect in the material you send to the render.\nAnyways - maybe you'll find it here:</p>\n\n<p><a href=\"http://creators.xna.com/en-us/utilities/spritebatchshader\" rel=\"nofollow noreferrer\">http://creators.xna.com/en-us/utilities/spritebatchshader</a></p>\n\n<p>And an advanced code if you want to get there:</p>\n\n<p><a href=\"http://creators.xna.com/en-us/sample/particle3d\" rel=\"nofollow noreferrer\">http://creators.xna.com/en-us/sample/particle3d</a></p>\n\n<p>Have fun</p>\n" }, { "answer_id": 86966, "author": "Joel Martinez", "author_id": 5416, "author_profile": "https://Stackoverflow.com/users/5416", "pm_score": 1, "selected": false, "text": "<p>If you want to use custom shaders with SpriteBatch, check out this sample:</p>\n\n<p><a href=\"http://creators.xna.com/en-us/sample/spriteeffects\" rel=\"nofollow noreferrer\">http://creators.xna.com/en-us/sample/spriteeffects</a></p>\n" }, { "answer_id": 122769, "author": "finalman", "author_id": 20522, "author_profile": "https://Stackoverflow.com/users/20522", "pm_score": 1, "selected": false, "text": "<p>Joel Martinez is indeed right, and you use it like this with a SpriteBatch, having loaded the effect into tintWhiteEffect:</p>\n\n<pre><code>spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.None);\n\ntintWhiteEffect.Begin();\ntintWhiteEffect.CurrentTechnique.Passes[0].Begin();\n\n // DRAW SPRITES HERE USING SPRITEBATCH\n\ntintWhiteEffect.CurrentTechnique.Passes[0].End();\ntintWhiteEffect.End();\n\nspriteBatch.End();\n</code></pre>\n\n<p>SpriteSortMode.Immediate is the trick here, it allows you to swap out SpriteBatch's default shader for your own. Using it will make sprite drawing a bit slower though, since sprites aren't batched up in a single draw call, but I don't think you will notice the difference.</p>\n" } ]
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.