question_id int64 4 6.31M | answer_id int64 7 6.31M | title stringlengths 9 150 | question_body stringlengths 0 28.8k | answer_body stringlengths 60 27.2k | question_text stringlengths 40 28.9k | combined_text stringlengths 124 39.6k | tags listlengths 1 6 | question_score int64 0 26.3k | answer_score int64 0 28.8k | view_count int64 15 14M | answer_count int64 0 182 | favorite_count int64 0 32 | question_creation_date stringdate 2008-07-31 21:42:52 2011-06-10 18:12:18 | answer_creation_date stringdate 2008-07-31 22:17:57 2011-06-10 18:14:17 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,005 | 37,042 | How do you get sudo access for a file inside the vi text editor? | Often while editing config files, I'll open one with vi and then when I go to save it realize that I didn't type sudo vi filename Is there any way to give vi sudo privileges to save the file? I seem to recall seeing something about this while looking up some stuff about vi a while ago, but now I can't find it. | % is replaced with the current file name, thus you can use::w!sudo tee % ( vim will detect that the file has been changed and ask whether you want to it to be reloaded. Say yes by choosing [L] rather than OK.) As a shortcut, you can define your own command. Put the following in your.vimrc: command W w!sudo tee % >/dev/null With the above you can type:W to save the file. Since I wrote this, I have found a nicer way (in my opinion) to do this: cmap w!! w!sudo tee >/dev/null % This way you can type:w!! and it will be expanded to the full command line, leaving the cursor at the end, so you can replace the % with a file name of your own, if you like. | How do you get sudo access for a file inside the vi text editor? Often while editing config files, I'll open one with vi and then when I go to save it realize that I didn't type sudo vi filename Is there any way to give vi sudo privileges to save the file? I seem to recall seeing something about this while looking up some stuff about vi a while ago, but now I can't find it. | TITLE:
How do you get sudo access for a file inside the vi text editor?
QUESTION:
Often while editing config files, I'll open one with vi and then when I go to save it realize that I didn't type sudo vi filename Is there any way to give vi sudo privileges to save the file? I seem to recall seeing something about this while looking up some stuff about vi a while ago, but now I can't find it.
ANSWER:
% is replaced with the current file name, thus you can use::w!sudo tee % ( vim will detect that the file has been changed and ask whether you want to it to be reloaded. Say yes by choosing [L] rather than OK.) As a shortcut, you can define your own command. Put the following in your.vimrc: command W w!sudo tee % >/dev/null With the above you can type:W to save the file. Since I wrote this, I have found a nicer way (in my opinion) to do this: cmap w!! w!sudo tee >/dev/null % This way you can type:w!! and it will be expanded to the full command line, leaving the cursor at the end, so you can replace the % with a file name of your own, if you like. | [
"linux",
"unix",
"vi"
] | 254 | 310 | 82,876 | 10 | 0 | 2008-08-04T03:34:02.860000 | 2008-08-31T19:23:48.347000 |
1,010 | 1,074 | How to get the value of built, encoded ViewState? | I need to grab the base64-encoded representation of the ViewState. Obviously, this would not be available until fairly late in the request lifecycle, which is OK. For example, if the output of the page includes: I need a way on the server-side to get the value "/wEPDwUJODU0Njc5MD...==" To clarify, I need this value when the page is being rendered, not on PostBack. e.g. I need to know the ViewState value that is being sent to the client, not the ViewState I'm getting back from them. | Rex, I suspect a good place to start looking is solutions that compress the ViewState -- they're grabbing ViewState on the server before it's sent down to the client and gzipping it. That's exactly where you want to be. Scott Hanselman on ViewState Compression (2005) ViewState Compression with System.IO.Compression (2007) | How to get the value of built, encoded ViewState? I need to grab the base64-encoded representation of the ViewState. Obviously, this would not be available until fairly late in the request lifecycle, which is OK. For example, if the output of the page includes: I need a way on the server-side to get the value "/wEPDwUJODU0Njc5MD...==" To clarify, I need this value when the page is being rendered, not on PostBack. e.g. I need to know the ViewState value that is being sent to the client, not the ViewState I'm getting back from them. | TITLE:
How to get the value of built, encoded ViewState?
QUESTION:
I need to grab the base64-encoded representation of the ViewState. Obviously, this would not be available until fairly late in the request lifecycle, which is OK. For example, if the output of the page includes: I need a way on the server-side to get the value "/wEPDwUJODU0Njc5MD...==" To clarify, I need this value when the page is being rendered, not on PostBack. e.g. I need to know the ViewState value that is being sent to the client, not the ViewState I'm getting back from them.
ANSWER:
Rex, I suspect a good place to start looking is solutions that compress the ViewState -- they're grabbing ViewState on the server before it's sent down to the client and gzipping it. That's exactly where you want to be. Scott Hanselman on ViewState Compression (2005) ViewState Compression with System.IO.Compression (2007) | [
"c#",
"asp.net",
"viewstate"
] | 31 | 13 | 2,611 | 3 | 0 | 2008-08-04T03:59:42.557000 | 2008-08-04T08:04:41.737000 |
1,024 | 171,170 | How do I fix 'Unprocessed view path found' error with ExceptionNotifier plugin in rails 2.1? | After upgrading a rails 1.2 website to 2.1, the ExceptionNotifier plugin no longer works, complaining about this error: ActionView::TemplateFinder::InvalidViewPath: Unprocessed view path found: "/path/to/appname/vendor/plugins/exception_notification/lib/../views". Set your view paths with #append_view_path, #prepend_view_path, or #view_paths=. What causes it and how do I fix it? | You ought to upgrade to the newest Exception Notification plugin which is in its new home at GitHub. | How do I fix 'Unprocessed view path found' error with ExceptionNotifier plugin in rails 2.1? After upgrading a rails 1.2 website to 2.1, the ExceptionNotifier plugin no longer works, complaining about this error: ActionView::TemplateFinder::InvalidViewPath: Unprocessed view path found: "/path/to/appname/vendor/plugins/exception_notification/lib/../views". Set your view paths with #append_view_path, #prepend_view_path, or #view_paths=. What causes it and how do I fix it? | TITLE:
How do I fix 'Unprocessed view path found' error with ExceptionNotifier plugin in rails 2.1?
QUESTION:
After upgrading a rails 1.2 website to 2.1, the ExceptionNotifier plugin no longer works, complaining about this error: ActionView::TemplateFinder::InvalidViewPath: Unprocessed view path found: "/path/to/appname/vendor/plugins/exception_notification/lib/../views". Set your view paths with #append_view_path, #prepend_view_path, or #view_paths=. What causes it and how do I fix it?
ANSWER:
You ought to upgrade to the newest Exception Notification plugin which is in its new home at GitHub. | [
"ruby-on-rails",
"ruby",
"exception",
"plugins"
] | 24 | 0 | 1,290 | 2 | 0 | 2008-08-04T04:48:38.013000 | 2008-10-04T23:18:41.483000 |
1,033 | 1,056 | How to get the Country according to a certain IP? | Does anyone know any simple way to retrieve the country from a given IP Address, preferably in ISO_3166-1 format? | A lot of people (including my company) seem to use MaxMind GeoIP. They have a free version GeoLite which is not as accurate as the paid version, but if you're just after something simple, it may be good enough. | How to get the Country according to a certain IP? Does anyone know any simple way to retrieve the country from a given IP Address, preferably in ISO_3166-1 format? | TITLE:
How to get the Country according to a certain IP?
QUESTION:
Does anyone know any simple way to retrieve the country from a given IP Address, preferably in ISO_3166-1 format?
ANSWER:
A lot of people (including my company) seem to use MaxMind GeoIP. They have a free version GeoLite which is not as accurate as the paid version, but if you're just after something simple, it may be good enough. | [
"ip",
"lookup",
"country"
] | 61 | 38 | 19,980 | 15 | 0 | 2008-08-04T05:15:35.773000 | 2008-08-04T06:26:22.370000 |
1,037 | 1,039 | Displaying Flash content in a C# WinForms application | What is the best way to display Flash content in a C# WinForms application? I would like to create a user control (similar to the current PictureBox ) that will be able to display images and flash content. It would be great to be able to load the flash content from a stream of sorts rather than a file on disk. | While I haven't used a flash object inside a windows form application myself, I do know that it's possible. In Visual studio on your toolbox, choose to add a new component. Then in the new window that appears choose the "COM Components" tab to get a list in which you can find the "Shockwave Flash Object" Once added to the toolbox, simply use the control as you would use any other "standard" control from visual studio. three simple commands are available to interact with the control: AxShockwaveFlash1.Stop() AxShockwaveFlash1.Movie = FilePath & "\FileName.swf" AxShockwaveFlash1.Play() which, I think, are all self explanatory. It would be great to be able to load the flash content from a stream of sorts rather than a file on disk. I just saw you are also looking for a means to load the content from a stream, and because I'm not really sure that is possible with the shockwave flash object I will give you another option (two actually). the first is the one I would advise you to use only when necessary, as it uses the full blown "webbrowser component" (also available as an extra toolbox item), which is like trying to shoot a fly with a bazooka. of course it will work, as the control will act as a real browser window (actually the internet explorer browser), but its not really meant to be used in the way you need it. the second option is to use something I just discovered while looking for more information about playing flash content inside a windows form. F-IN-BOX is a commercial solution that will also play content from a given website URL. (The link provided will direct you to the.NET code you have to use). | Displaying Flash content in a C# WinForms application What is the best way to display Flash content in a C# WinForms application? I would like to create a user control (similar to the current PictureBox ) that will be able to display images and flash content. It would be great to be able to load the flash content from a stream of sorts rather than a file on disk. | TITLE:
Displaying Flash content in a C# WinForms application
QUESTION:
What is the best way to display Flash content in a C# WinForms application? I would like to create a user control (similar to the current PictureBox ) that will be able to display images and flash content. It would be great to be able to load the flash content from a stream of sorts rather than a file on disk.
ANSWER:
While I haven't used a flash object inside a windows form application myself, I do know that it's possible. In Visual studio on your toolbox, choose to add a new component. Then in the new window that appears choose the "COM Components" tab to get a list in which you can find the "Shockwave Flash Object" Once added to the toolbox, simply use the control as you would use any other "standard" control from visual studio. three simple commands are available to interact with the control: AxShockwaveFlash1.Stop() AxShockwaveFlash1.Movie = FilePath & "\FileName.swf" AxShockwaveFlash1.Play() which, I think, are all self explanatory. It would be great to be able to load the flash content from a stream of sorts rather than a file on disk. I just saw you are also looking for a means to load the content from a stream, and because I'm not really sure that is possible with the shockwave flash object I will give you another option (two actually). the first is the one I would advise you to use only when necessary, as it uses the full blown "webbrowser component" (also available as an extra toolbox item), which is like trying to shoot a fly with a bazooka. of course it will work, as the control will act as a real browser window (actually the internet explorer browser), but its not really meant to be used in the way you need it. the second option is to use something I just discovered while looking for more information about playing flash content inside a windows form. F-IN-BOX is a commercial solution that will also play content from a given website URL. (The link provided will direct you to the.NET code you have to use). | [
"c#",
"winforms",
"flash",
"adobe",
"macromedia"
] | 40 | 34 | 37,469 | 2 | 0 | 2008-08-04T05:35:52.240000 | 2008-08-04T05:44:45.887000 |
1,040 | 1,044 | How do I delete a file which is locked by another process in C#? | I'm looking for a way to delete a file which is locked by another process using C#. I suspect the method must be able to find which process is locking the file (perhaps by tracking the handles, although I'm not sure how to do this in C#) then close that process before being able to complete the file delete using File.Delete(). | Killing other processes is not a healthy thing to do. If your scenario involves something like uninstallation, you could use the MoveFileEx API function to mark the file for deletion upon next reboot. If it appears that you really need to delete a file in use by another process, I'd recommend re-considering the actual problem before considering any solutions. | How do I delete a file which is locked by another process in C#? I'm looking for a way to delete a file which is locked by another process using C#. I suspect the method must be able to find which process is locking the file (perhaps by tracking the handles, although I'm not sure how to do this in C#) then close that process before being able to complete the file delete using File.Delete(). | TITLE:
How do I delete a file which is locked by another process in C#?
QUESTION:
I'm looking for a way to delete a file which is locked by another process using C#. I suspect the method must be able to find which process is locking the file (perhaps by tracking the handles, although I'm not sure how to do this in C#) then close that process before being able to complete the file delete using File.Delete().
ANSWER:
Killing other processes is not a healthy thing to do. If your scenario involves something like uninstallation, you could use the MoveFileEx API function to mark the file for deletion upon next reboot. If it appears that you really need to delete a file in use by another process, I'd recommend re-considering the actual problem before considering any solutions. | [
"c#",
"file-locking"
] | 58 | 37 | 56,005 | 9 | 0 | 2008-08-04T05:45:22.080000 | 2008-08-04T06:01:52.873000 |
1,042 | 1,061 | Why doesn't SQL Full Text Indexing return results for words containing #? | For instance, my query is like the following using SQL Server 2005: SELECT * FROM Table WHERE FREETEXT(SearchField, 'c#') I have a full text index defined to use the column SearchField which returns results when using: SELECT * FROM Table WHERE SearchField LIKE '%c#%' I believe # is a special letter, so how do I allow FREETEXT to work correctly for the query above? | The # char is indexed as punctuation and therefore ignored, so it looks like we'll remove the letter C from our word indexing ignore lists. Tested it locally after doing that and rebuilding the indexes and I get results! Looking at using a different word breaker language on the indexed column, so that those special characters aren't ignored. EDIT: I also found this information: c# is indexed as c (if c is not in your noise word list, see more on noise word lists later), but C# is indexed as C# (in SQL 2005 and SQL 2000 running on Win2003 regardless if C or c is in your noise word list). It is not only C# that is stored as C#, but any capital letter followed by #. Conversely, c++ ( and any other lower-cased letter followed by a ++) is indexed as c (regardless of whether c is in your noise word list). | Why doesn't SQL Full Text Indexing return results for words containing #? For instance, my query is like the following using SQL Server 2005: SELECT * FROM Table WHERE FREETEXT(SearchField, 'c#') I have a full text index defined to use the column SearchField which returns results when using: SELECT * FROM Table WHERE SearchField LIKE '%c#%' I believe # is a special letter, so how do I allow FREETEXT to work correctly for the query above? | TITLE:
Why doesn't SQL Full Text Indexing return results for words containing #?
QUESTION:
For instance, my query is like the following using SQL Server 2005: SELECT * FROM Table WHERE FREETEXT(SearchField, 'c#') I have a full text index defined to use the column SearchField which returns results when using: SELECT * FROM Table WHERE SearchField LIKE '%c#%' I believe # is a special letter, so how do I allow FREETEXT to work correctly for the query above?
ANSWER:
The # char is indexed as punctuation and therefore ignored, so it looks like we'll remove the letter C from our word indexing ignore lists. Tested it locally after doing that and rebuilding the indexes and I get results! Looking at using a different word breaker language on the indexed column, so that those special characters aren't ignored. EDIT: I also found this information: c# is indexed as c (if c is not in your noise word list, see more on noise word lists later), but C# is indexed as C# (in SQL 2005 and SQL 2000 running on Win2003 regardless if C or c is in your noise word list). It is not only C# that is stored as C#, but any capital letter followed by #. Conversely, c++ ( and any other lower-cased letter followed by a ++) is indexed as c (regardless of whether c is in your noise word list). | [
"sql",
"sql-server",
"sql-server-2005",
"indexing",
"full-text-search"
] | 26 | 14 | 9,411 | 2 | 0 | 2008-08-04T05:51:56.683000 | 2008-08-04T06:39:40.003000 |
1,053 | 394,225 | A little diversion into floating point (im)precision, part 1 | Most mathematicians agree that: e πi + 1 = 0 However, most floating point implementations disagree. How well can we settle this dispute? I'm keen to hear about different languages and implementations, and various methods to make the result as close to zero as possible. Be creative! | It's not that most floating point implementations disagree, it's just that they cannot get the accuracy necessary to get a 100% answer. And the correct answer is that they can't. PI is an infinite series of digits that nobody has been able to denote by anything other than a symbolic representation, and e^X is the same, and thus the only way to get to 100% accuracy is to go symbolic. | A little diversion into floating point (im)precision, part 1 Most mathematicians agree that: e πi + 1 = 0 However, most floating point implementations disagree. How well can we settle this dispute? I'm keen to hear about different languages and implementations, and various methods to make the result as close to zero as possible. Be creative! | TITLE:
A little diversion into floating point (im)precision, part 1
QUESTION:
Most mathematicians agree that: e πi + 1 = 0 However, most floating point implementations disagree. How well can we settle this dispute? I'm keen to hear about different languages and implementations, and various methods to make the result as close to zero as possible. Be creative!
ANSWER:
It's not that most floating point implementations disagree, it's just that they cannot get the accuracy necessary to get a 100% answer. And the correct answer is that they can't. PI is an infinite series of digits that nobody has been able to denote by anything other than a symbolic representation, and e^X is the same, and thus the only way to get to 100% accuracy is to go symbolic. | [
"math",
"language-agnostic",
"floating-point"
] | 23 | 18 | 2,220 | 10 | 0 | 2008-08-04T06:21:38.293000 | 2008-12-26T20:22:01.910000 |
1,064 | 1,096 | Displaying 100 Floating Cubes Using DirectX OR OpenGL | I'd like to display 100 floating cubes using DirectX or OpenGL. I'm looking for either some sample source code, or a description of the technique. I have trouble getting more one cube to display correctly. I've combed the net for a good series of tutorials and although they talk about how to do 3D primitives, what I can't find is information on how to do large numbers of 3D primitives - cubes, spheres, pyramids, and so forth. | You say you have enough trouble getting one cube to display... so I am not sure if you have got one to display or not. Basically... put your code for writing a cube in one function, then just call that function 100 times. void DrawCube() { //code to draw the cube }
void DisplayCubes() { for(int i = 0; i < 10; ++i) { for(int j = 0; j < 10; ++j) { glPushMatrix(); //alter these values depending on the size of your cubes. //This call makes sure that your cubes aren't drawn overtop of each other glTranslatef(i*5.0, j*5.0, 0); DrawCube(); glPopMatrix(); } } } That is the basic outline for how you could go about doing this. If you want something more efficient take a look into Display Lists sometime once you have the basics figured out:) | Displaying 100 Floating Cubes Using DirectX OR OpenGL I'd like to display 100 floating cubes using DirectX or OpenGL. I'm looking for either some sample source code, or a description of the technique. I have trouble getting more one cube to display correctly. I've combed the net for a good series of tutorials and although they talk about how to do 3D primitives, what I can't find is information on how to do large numbers of 3D primitives - cubes, spheres, pyramids, and so forth. | TITLE:
Displaying 100 Floating Cubes Using DirectX OR OpenGL
QUESTION:
I'd like to display 100 floating cubes using DirectX or OpenGL. I'm looking for either some sample source code, or a description of the technique. I have trouble getting more one cube to display correctly. I've combed the net for a good series of tutorials and although they talk about how to do 3D primitives, what I can't find is information on how to do large numbers of 3D primitives - cubes, spheres, pyramids, and so forth.
ANSWER:
You say you have enough trouble getting one cube to display... so I am not sure if you have got one to display or not. Basically... put your code for writing a cube in one function, then just call that function 100 times. void DrawCube() { //code to draw the cube }
void DisplayCubes() { for(int i = 0; i < 10; ++i) { for(int j = 0; j < 10; ++j) { glPushMatrix(); //alter these values depending on the size of your cubes. //This call makes sure that your cubes aren't drawn overtop of each other glTranslatef(i*5.0, j*5.0, 0); DrawCube(); glPopMatrix(); } } } That is the basic outline for how you could go about doing this. If you want something more efficient take a look into Display Lists sometime once you have the basics figured out:) | [
"language-agnostic",
"opengl",
"3d",
"directx"
] | 19 | 8 | 1,964 | 3 | 0 | 2008-08-04T06:51:20.323000 | 2008-08-04T09:12:37.543000 |
1,069 | 1,073 | Heap corruption under Win32; how to locate? | I'm working on a multithreaded C++ application that is corrupting the heap. The usual tools to locate this corruption seem to be inapplicable. Old builds (18 months old) of the source code exhibit the same behavior as the most recent release, so this has been around for a long time and just wasn't noticed; on the downside, source deltas can't be used to identify when the bug was introduced - there are a lot of code changes in the repository. The prompt for crashing behavior is to generate throughput in this system - socket transfer of data which is munged into an internal representation. I have a set of test data that will periodically cause the app to exception (various places, various causes - including heap alloc failing, thus: heap corruption). The behavior seems related to CPU power or memory bandwidth; the more of each the machine has, the easier it is to crash. Disabling a hyper-threading core or a dual-core core reduces the rate of (but does not eliminate) corruption. This suggests a timing-related issue. Now here's the rub: When it's run under a lightweight debug environment (say Visual Studio 98 / AKA MSVC6 ) the heap corruption is reasonably easy to reproduce - ten or fifteen minutes pass before something fails horrendously and exceptions, like an alloc; when running under a sophisticated debug environment (Rational Purify, VS2008/MSVC9 or even Microsoft Application Verifier) the system becomes memory-speed bound and doesn't crash (Memory-bound: CPU is not getting above 50%, disk light is not on, the program's going as fast it can, box consuming 1.3G of 2G of RAM). So, I've got a choice between being able to reproduce the problem (but not identifying the cause) or being able to identify the cause of a problem I can't reproduce. My current best guesses as to where to next is: Get an insanely grunty box (to replace the current dev box: 2Gb RAM in an E6550 Core2 Duo ); this will make it possible to repro the crash causing misbehavior when running under a powerful debug environment; or Rewrite operators new and delete to use VirtualAlloc and VirtualProtect to mark memory as read-only as soon as it's done with. Run under MSVC6 and have the OS catch the bad guy who's writing to freed memory. Yes, this is a sign of desperation: who the hell rewrites new and delete?! I wonder if this is going to make it as slow as under Purify et al. And, no: Shipping with Purify instrumentation built in is not an option. A colleague just walked past and asked "Stack Overflow? Are we getting stack overflows now?!?" And now, the question: How do I locate the heap corruptor? Update: balancing new[] and delete[] seems to have gotten a long way toward solving the problem. Instead of 15mins, the app now goes about two hours before crashing. Not there yet. Any further suggestions? The heap corruption persists. Update: a release build under Visual Studio 2008 seems dramatically better; current suspicion rests on the STL implementation that ships with VS98. Reproduce the problem. Dr Watson will produce a dump that might be helpful in further analysis. I'll take note of that, but I'm concerned that Dr. Watson will only be tripped up after the fact, not when the heap is getting stomped on. Another try might be using WinDebug as a debugging tool which is a quite powerful being at the same time also lightweight. Got that going at the moment, again: not much help until something goes wrong. I want to catch the vandal in the act. Maybe these tools will allow you at least to narrow the problem to a certain component. I don't hold much hope, but desperate times call for... And are you sure that all the components of the project have correct runtime library settings ( C/C++ tab, Code Generation category in VS 6.0 project settings)? No, I'm not, and I'll spend a couple of hours tomorrow going through the workspace (58 projects in it) and checking they're all compiling and linking with the appropriate flags. Update: This took 30 seconds. Select all projects in the `Settings` dialog, and unselect until you find the project(s) that don't have the right settings (they all had the right settings). | My first choice would be a dedicated heap tool such as pageheap.exe. Rewriting new and delete might be useful, but that doesn't catch the allocs committed by lower-level code. If this is what you want, better to Detour the low-level alloc API s using Microsoft Detours. Also sanity checks such as: verify your run-time libraries match (release vs. debug, multi-threaded vs. single-threaded, dll vs. static lib), look for bad deletes (eg, delete where delete [] should have been used), make sure you're not mixing and matching your allocs. Also try selectively turning off threads and see when/if the problem goes away. What does the call stack etc look like at the time of the first exception? | Heap corruption under Win32; how to locate? I'm working on a multithreaded C++ application that is corrupting the heap. The usual tools to locate this corruption seem to be inapplicable. Old builds (18 months old) of the source code exhibit the same behavior as the most recent release, so this has been around for a long time and just wasn't noticed; on the downside, source deltas can't be used to identify when the bug was introduced - there are a lot of code changes in the repository. The prompt for crashing behavior is to generate throughput in this system - socket transfer of data which is munged into an internal representation. I have a set of test data that will periodically cause the app to exception (various places, various causes - including heap alloc failing, thus: heap corruption). The behavior seems related to CPU power or memory bandwidth; the more of each the machine has, the easier it is to crash. Disabling a hyper-threading core or a dual-core core reduces the rate of (but does not eliminate) corruption. This suggests a timing-related issue. Now here's the rub: When it's run under a lightweight debug environment (say Visual Studio 98 / AKA MSVC6 ) the heap corruption is reasonably easy to reproduce - ten or fifteen minutes pass before something fails horrendously and exceptions, like an alloc; when running under a sophisticated debug environment (Rational Purify, VS2008/MSVC9 or even Microsoft Application Verifier) the system becomes memory-speed bound and doesn't crash (Memory-bound: CPU is not getting above 50%, disk light is not on, the program's going as fast it can, box consuming 1.3G of 2G of RAM). So, I've got a choice between being able to reproduce the problem (but not identifying the cause) or being able to identify the cause of a problem I can't reproduce. My current best guesses as to where to next is: Get an insanely grunty box (to replace the current dev box: 2Gb RAM in an E6550 Core2 Duo ); this will make it possible to repro the crash causing misbehavior when running under a powerful debug environment; or Rewrite operators new and delete to use VirtualAlloc and VirtualProtect to mark memory as read-only as soon as it's done with. Run under MSVC6 and have the OS catch the bad guy who's writing to freed memory. Yes, this is a sign of desperation: who the hell rewrites new and delete?! I wonder if this is going to make it as slow as under Purify et al. And, no: Shipping with Purify instrumentation built in is not an option. A colleague just walked past and asked "Stack Overflow? Are we getting stack overflows now?!?" And now, the question: How do I locate the heap corruptor? Update: balancing new[] and delete[] seems to have gotten a long way toward solving the problem. Instead of 15mins, the app now goes about two hours before crashing. Not there yet. Any further suggestions? The heap corruption persists. Update: a release build under Visual Studio 2008 seems dramatically better; current suspicion rests on the STL implementation that ships with VS98. Reproduce the problem. Dr Watson will produce a dump that might be helpful in further analysis. I'll take note of that, but I'm concerned that Dr. Watson will only be tripped up after the fact, not when the heap is getting stomped on. Another try might be using WinDebug as a debugging tool which is a quite powerful being at the same time also lightweight. Got that going at the moment, again: not much help until something goes wrong. I want to catch the vandal in the act. Maybe these tools will allow you at least to narrow the problem to a certain component. I don't hold much hope, but desperate times call for... And are you sure that all the components of the project have correct runtime library settings ( C/C++ tab, Code Generation category in VS 6.0 project settings)? No, I'm not, and I'll spend a couple of hours tomorrow going through the workspace (58 projects in it) and checking they're all compiling and linking with the appropriate flags. Update: This took 30 seconds. Select all projects in the `Settings` dialog, and unselect until you find the project(s) that don't have the right settings (they all had the right settings). | TITLE:
Heap corruption under Win32; how to locate?
QUESTION:
I'm working on a multithreaded C++ application that is corrupting the heap. The usual tools to locate this corruption seem to be inapplicable. Old builds (18 months old) of the source code exhibit the same behavior as the most recent release, so this has been around for a long time and just wasn't noticed; on the downside, source deltas can't be used to identify when the bug was introduced - there are a lot of code changes in the repository. The prompt for crashing behavior is to generate throughput in this system - socket transfer of data which is munged into an internal representation. I have a set of test data that will periodically cause the app to exception (various places, various causes - including heap alloc failing, thus: heap corruption). The behavior seems related to CPU power or memory bandwidth; the more of each the machine has, the easier it is to crash. Disabling a hyper-threading core or a dual-core core reduces the rate of (but does not eliminate) corruption. This suggests a timing-related issue. Now here's the rub: When it's run under a lightweight debug environment (say Visual Studio 98 / AKA MSVC6 ) the heap corruption is reasonably easy to reproduce - ten or fifteen minutes pass before something fails horrendously and exceptions, like an alloc; when running under a sophisticated debug environment (Rational Purify, VS2008/MSVC9 or even Microsoft Application Verifier) the system becomes memory-speed bound and doesn't crash (Memory-bound: CPU is not getting above 50%, disk light is not on, the program's going as fast it can, box consuming 1.3G of 2G of RAM). So, I've got a choice between being able to reproduce the problem (but not identifying the cause) or being able to identify the cause of a problem I can't reproduce. My current best guesses as to where to next is: Get an insanely grunty box (to replace the current dev box: 2Gb RAM in an E6550 Core2 Duo ); this will make it possible to repro the crash causing misbehavior when running under a powerful debug environment; or Rewrite operators new and delete to use VirtualAlloc and VirtualProtect to mark memory as read-only as soon as it's done with. Run under MSVC6 and have the OS catch the bad guy who's writing to freed memory. Yes, this is a sign of desperation: who the hell rewrites new and delete?! I wonder if this is going to make it as slow as under Purify et al. And, no: Shipping with Purify instrumentation built in is not an option. A colleague just walked past and asked "Stack Overflow? Are we getting stack overflows now?!?" And now, the question: How do I locate the heap corruptor? Update: balancing new[] and delete[] seems to have gotten a long way toward solving the problem. Instead of 15mins, the app now goes about two hours before crashing. Not there yet. Any further suggestions? The heap corruption persists. Update: a release build under Visual Studio 2008 seems dramatically better; current suspicion rests on the STL implementation that ships with VS98. Reproduce the problem. Dr Watson will produce a dump that might be helpful in further analysis. I'll take note of that, but I'm concerned that Dr. Watson will only be tripped up after the fact, not when the heap is getting stomped on. Another try might be using WinDebug as a debugging tool which is a quite powerful being at the same time also lightweight. Got that going at the moment, again: not much help until something goes wrong. I want to catch the vandal in the act. Maybe these tools will allow you at least to narrow the problem to a certain component. I don't hold much hope, but desperate times call for... And are you sure that all the components of the project have correct runtime library settings ( C/C++ tab, Code Generation category in VS 6.0 project settings)? No, I'm not, and I'll spend a couple of hours tomorrow going through the workspace (58 projects in it) and checking they're all compiling and linking with the appropriate flags. Update: This took 30 seconds. Select all projects in the `Settings` dialog, and unselect until you find the project(s) that don't have the right settings (they all had the right settings).
ANSWER:
My first choice would be a dedicated heap tool such as pageheap.exe. Rewriting new and delete might be useful, but that doesn't catch the allocs committed by lower-level code. If this is what you want, better to Detour the low-level alloc API s using Microsoft Detours. Also sanity checks such as: verify your run-time libraries match (release vs. debug, multi-threaded vs. single-threaded, dll vs. static lib), look for bad deletes (eg, delete where delete [] should have been used), make sure you're not mixing and matching your allocs. Also try selectively turning off threads and see when/if the problem goes away. What does the call stack etc look like at the time of the first exception? | [
"c++",
"windows",
"multithreading",
"debugging",
"memory"
] | 65 | 29 | 39,110 | 15 | 0 | 2008-08-04T07:30:01.727000 | 2008-08-04T07:51:02.997000 |
1,070 | 1,773 | Process size on UNIX | What is the correct way to get the process size on Solaris, HP-UX and AIX? Should we use top or ps -o vsz or something else? | The exact definitions of vsize, rss, rprvt, rshrd, and other obscure-looking abbreviations vary from OS to OS. The manual pages for the top and ps commands will have some sort of description, but all such descriptions are simplified greatly (or are based on long-extinct kernel implementations). "Process size" as a concept is fiendishly difficult to pin down in the general case. Answers in specific instances depend heavily on the actual memory management implementation in the OS, and are rarely as satisfying as the tidy "process size" concept that exists in the minds of most users (and most developers). For example, none of those numbers (nor, likely, any combination of them) can be used to tell you exactly how many such processes can run at once in a given amount of free memory. But really, your best bet is to come at it from that end: why do you want this number, and what will you use it for? Given that information, I think you'll get more useful answers. | Process size on UNIX What is the correct way to get the process size on Solaris, HP-UX and AIX? Should we use top or ps -o vsz or something else? | TITLE:
Process size on UNIX
QUESTION:
What is the correct way to get the process size on Solaris, HP-UX and AIX? Should we use top or ps -o vsz or something else?
ANSWER:
The exact definitions of vsize, rss, rprvt, rshrd, and other obscure-looking abbreviations vary from OS to OS. The manual pages for the top and ps commands will have some sort of description, but all such descriptions are simplified greatly (or are based on long-extinct kernel implementations). "Process size" as a concept is fiendishly difficult to pin down in the general case. Answers in specific instances depend heavily on the actual memory management implementation in the OS, and are rarely as satisfying as the tidy "process size" concept that exists in the minds of most users (and most developers). For example, none of those numbers (nor, likely, any combination of them) can be used to tell you exactly how many such processes can run at once in a given amount of free memory. But really, your best bet is to come at it from that end: why do you want this number, and what will you use it for? Given that information, I think you'll get more useful answers. | [
"unix",
"size"
] | 28 | 16 | 21,919 | 4 | 0 | 2008-08-04T07:34:44.137000 | 2008-08-05T01:07:50.657000 |
1,083 | 42,406 | Object Oriented Bayesian Spam Filtering? | I was wondering if there is any good and clean object-oriented programming (OOP) implementation of Bayesian filtering for spam and text classification? This is just for learning purposes. | I definitely recommend Weka which is an Open Source Data Mining Software written in Java: Weka is a collection of machine learning algorithms for data mining tasks. The algorithms can either be applied directly to a dataset or called from your own Java code. Weka contains tools for data pre-processing, classification, regression, clustering, association rules, and visualization. It is also well-suited for developing new machine learning schemes. As mentioned above, it ships with a bunch of different classifiers like SVM, Winnow, C4.5, Naive Bayes (of course) and many more (see the API doc ). Note that a lot of classifiers are known to have much better perfomance than Naive Bayes in the field of spam detection or text classification. Furthermore Weka brings you a very powerful GUI … | Object Oriented Bayesian Spam Filtering? I was wondering if there is any good and clean object-oriented programming (OOP) implementation of Bayesian filtering for spam and text classification? This is just for learning purposes. | TITLE:
Object Oriented Bayesian Spam Filtering?
QUESTION:
I was wondering if there is any good and clean object-oriented programming (OOP) implementation of Bayesian filtering for spam and text classification? This is just for learning purposes.
ANSWER:
I definitely recommend Weka which is an Open Source Data Mining Software written in Java: Weka is a collection of machine learning algorithms for data mining tasks. The algorithms can either be applied directly to a dataset or called from your own Java code. Weka contains tools for data pre-processing, classification, regression, clustering, association rules, and visualization. It is also well-suited for developing new machine learning schemes. As mentioned above, it ships with a bunch of different classifiers like SVM, Winnow, C4.5, Naive Bayes (of course) and many more (see the API doc ). Note that a lot of classifiers are known to have much better perfomance than Naive Bayes in the field of spam detection or text classification. Furthermore Weka brings you a very powerful GUI … | [
"oop",
"artificial-intelligence",
"naivebayes",
"email-spam"
] | 29 | 12 | 4,036 | 6 | 0 | 2008-08-04T08:21:42.043000 | 2008-09-03T19:46:47.923000 |
1,104 | 1,109 | Ensuring that Exceptions are always caught | Exceptions in C++ don't need to be caught (no compile time errors) by the calling function. So it's up to the developer's judgment whether to catch them using try/catch (unlike in Java). Is there a way one can ensure that the exceptions thrown are always caught using try/catch by the calling function? | No. See A Pragmatic Look at Exception Specifications for reasons why not. The only way you can "help" this is to document the exceptions your function can throw, say as a comment in the header file declaring it. This is not enforced by the compiler or anything. Use code reviews for that purpose. | Ensuring that Exceptions are always caught Exceptions in C++ don't need to be caught (no compile time errors) by the calling function. So it's up to the developer's judgment whether to catch them using try/catch (unlike in Java). Is there a way one can ensure that the exceptions thrown are always caught using try/catch by the calling function? | TITLE:
Ensuring that Exceptions are always caught
QUESTION:
Exceptions in C++ don't need to be caught (no compile time errors) by the calling function. So it's up to the developer's judgment whether to catch them using try/catch (unlike in Java). Is there a way one can ensure that the exceptions thrown are always caught using try/catch by the calling function?
ANSWER:
No. See A Pragmatic Look at Exception Specifications for reasons why not. The only way you can "help" this is to document the exceptions your function can throw, say as a comment in the header file declaring it. This is not enforced by the compiler or anything. Use code reviews for that purpose. | [
"c++",
"exception",
"try-catch",
"exception-safety"
] | 31 | 27 | 3,032 | 7 | 0 | 2008-08-04T10:01:37.927000 | 2008-08-04T10:10:15.727000 |
1,108 | 1,130 | How does database indexing work? | Given that indexing is so important as your data set increases in size, can someone explain how indexing works at a database-agnostic level? For information on queries to index a field, check out How do I index a database column. | Why is it needed? When data is stored on disk-based storage devices, it is stored as blocks of data. These blocks are accessed in their entirety, making them the atomic disk access operation. Disk blocks are structured in much the same way as linked lists; both contain a section for data, a pointer to the location of the next node (or block), and both need not be stored contiguously. Due to the fact that a number of records can only be sorted on one field, we can state that searching on a field that isn’t sorted requires a Linear Search which requires (N+1)/2 block accesses (on average), where N is the number of blocks that the table spans. If that field is a non-key field (i.e. doesn’t contain unique entries) then the entire tablespace must be searched at N block accesses. Whereas with a sorted field, a Binary Search may be used, which has log2 N block accesses. Also since the data is sorted given a non-key field, the rest of the table doesn’t need to be searched for duplicate values, once a higher value is found. Thus the performance increase is substantial. What is indexing? Indexing is a way of sorting a number of records on multiple fields. Creating an index on a field in a table creates another data structure which holds the field value, and a pointer to the record it relates to. This index structure is then sorted, allowing Binary Searches to be performed on it. The downside to indexing is that these indices require additional space on the disk since the indices are stored together in a table using the MyISAM engine, this file can quickly reach the size limits of the underlying file system if many fields within the same table are indexed. How does it work? Firstly, let’s outline a sample database table schema; Field name Data type Size on disk id (Primary key) Unsigned INT 4 bytes firstName Char(50) 50 bytes lastName Char(50) 50 bytes emailAddress Char(100) 100 bytes Note: char was used in place of varchar to allow for an accurate size on disk value. This sample database contains five million rows and is unindexed. The performance of several queries will now be analyzed. These are a query using the id (a sorted key field) and one using the firstName (a non-key unsorted field). Example 1 - sorted vs unsorted fields Given our sample database of r = 5,000,000 records of a fixed size giving a record length of R = 204 bytes and they are stored in a table using the MyISAM engine which is using the default block size B = 1,024 bytes. The blocking factor of the table would be bfr = (B/R) = 1024/204 = 5 records per disk block. The total number of blocks required to hold the table is N = (r/bfr) = 5000000/5 = 1,000,000 blocks. A linear search on the id field would require an average of N/2 = 500,000 block accesses to find a value, given that the id field is a key field. But since the id field is also sorted, a binary search can be conducted requiring an average of log2 1000000 = 19.93 = 20 block accesses. Instantly we can see this is a drastic improvement. Now the firstName field is neither sorted nor a key field, so a binary search is impossible, nor are the values unique, and thus the table will require searching to the end for an exact N = 1,000,000 block accesses. It is this situation that indexing aims to correct. Given that an index record contains only the indexed field and a pointer to the original record, it stands to reason that it will be smaller than the multi-field record that it points to. So the index itself requires fewer disk blocks than the original table, which therefore requires fewer block accesses to iterate through. The schema for an index on the firstName field is outlined below; Field name Data type Size on disk firstName Char(50) 50 bytes (record pointer) Special 4 bytes Note: Pointers in MySQL are 2, 3, 4 or 5 bytes in length depending on the size of the table. Example 2 - indexing Given our sample database of r = 5,000,000 records with an index record length of R = 54 bytes and using the default block size B = 1,024 bytes. The blocking factor of the index would be bfr = (B/R) = 1024/54 = 18 records per disk block. The total number of blocks required to hold the index is N = (r/bfr) = 5000000/18 = 277,778 blocks. Now a search using the firstName field can utilize the index to increase performance. This allows for a binary search of the index with an average of log2 277778 = 18.08 = 19 block accesses. To find the address of the actual record, which requires a further block access to read, bringing the total to 19 + 1 = 20 block accesses, a far cry from the 1,000,000 block accesses required to find a firstName match in the non-indexed table. When should it be used? Given that creating an index requires additional disk space (277,778 blocks extra from the above example, a ~28% increase), and that too many indices can cause issues arising from the file systems size limits, careful thought must be used to select the correct fields to index. Since indices are only used to speed up the searching for a matching field within the records, it stands to reason that indexing fields used only for output would be simply a waste of disk space and processing time when doing an insert or delete operation, and thus should be avoided. Also given the nature of a binary search, the cardinality or uniqueness of the data is important. Indexing on a field with a cardinality of 2 would split the data in half, whereas a cardinality of 1,000 would return approximately 1,000 records. With such a low cardinality the effectiveness is reduced to a linear sort, and the query optimizer will avoid using the index if the cardinality is less than 30% of the record number, effectively making the index a waste of space. | How does database indexing work? Given that indexing is so important as your data set increases in size, can someone explain how indexing works at a database-agnostic level? For information on queries to index a field, check out How do I index a database column. | TITLE:
How does database indexing work?
QUESTION:
Given that indexing is so important as your data set increases in size, can someone explain how indexing works at a database-agnostic level? For information on queries to index a field, check out How do I index a database column.
ANSWER:
Why is it needed? When data is stored on disk-based storage devices, it is stored as blocks of data. These blocks are accessed in their entirety, making them the atomic disk access operation. Disk blocks are structured in much the same way as linked lists; both contain a section for data, a pointer to the location of the next node (or block), and both need not be stored contiguously. Due to the fact that a number of records can only be sorted on one field, we can state that searching on a field that isn’t sorted requires a Linear Search which requires (N+1)/2 block accesses (on average), where N is the number of blocks that the table spans. If that field is a non-key field (i.e. doesn’t contain unique entries) then the entire tablespace must be searched at N block accesses. Whereas with a sorted field, a Binary Search may be used, which has log2 N block accesses. Also since the data is sorted given a non-key field, the rest of the table doesn’t need to be searched for duplicate values, once a higher value is found. Thus the performance increase is substantial. What is indexing? Indexing is a way of sorting a number of records on multiple fields. Creating an index on a field in a table creates another data structure which holds the field value, and a pointer to the record it relates to. This index structure is then sorted, allowing Binary Searches to be performed on it. The downside to indexing is that these indices require additional space on the disk since the indices are stored together in a table using the MyISAM engine, this file can quickly reach the size limits of the underlying file system if many fields within the same table are indexed. How does it work? Firstly, let’s outline a sample database table schema; Field name Data type Size on disk id (Primary key) Unsigned INT 4 bytes firstName Char(50) 50 bytes lastName Char(50) 50 bytes emailAddress Char(100) 100 bytes Note: char was used in place of varchar to allow for an accurate size on disk value. This sample database contains five million rows and is unindexed. The performance of several queries will now be analyzed. These are a query using the id (a sorted key field) and one using the firstName (a non-key unsorted field). Example 1 - sorted vs unsorted fields Given our sample database of r = 5,000,000 records of a fixed size giving a record length of R = 204 bytes and they are stored in a table using the MyISAM engine which is using the default block size B = 1,024 bytes. The blocking factor of the table would be bfr = (B/R) = 1024/204 = 5 records per disk block. The total number of blocks required to hold the table is N = (r/bfr) = 5000000/5 = 1,000,000 blocks. A linear search on the id field would require an average of N/2 = 500,000 block accesses to find a value, given that the id field is a key field. But since the id field is also sorted, a binary search can be conducted requiring an average of log2 1000000 = 19.93 = 20 block accesses. Instantly we can see this is a drastic improvement. Now the firstName field is neither sorted nor a key field, so a binary search is impossible, nor are the values unique, and thus the table will require searching to the end for an exact N = 1,000,000 block accesses. It is this situation that indexing aims to correct. Given that an index record contains only the indexed field and a pointer to the original record, it stands to reason that it will be smaller than the multi-field record that it points to. So the index itself requires fewer disk blocks than the original table, which therefore requires fewer block accesses to iterate through. The schema for an index on the firstName field is outlined below; Field name Data type Size on disk firstName Char(50) 50 bytes (record pointer) Special 4 bytes Note: Pointers in MySQL are 2, 3, 4 or 5 bytes in length depending on the size of the table. Example 2 - indexing Given our sample database of r = 5,000,000 records with an index record length of R = 54 bytes and using the default block size B = 1,024 bytes. The blocking factor of the index would be bfr = (B/R) = 1024/54 = 18 records per disk block. The total number of blocks required to hold the index is N = (r/bfr) = 5000000/18 = 277,778 blocks. Now a search using the firstName field can utilize the index to increase performance. This allows for a binary search of the index with an average of log2 277778 = 18.08 = 19 block accesses. To find the address of the actual record, which requires a further block access to read, bringing the total to 19 + 1 = 20 block accesses, a far cry from the 1,000,000 block accesses required to find a firstName match in the non-indexed table. When should it be used? Given that creating an index requires additional disk space (277,778 blocks extra from the above example, a ~28% increase), and that too many indices can cause issues arising from the file systems size limits, careful thought must be used to select the correct fields to index. Since indices are only used to speed up the searching for a matching field within the records, it stands to reason that indexing fields used only for output would be simply a waste of disk space and processing time when doing an insert or delete operation, and thus should be avoided. Also given the nature of a binary search, the cardinality or uniqueness of the data is important. Indexing on a field with a cardinality of 2 would split the data in half, whereas a cardinality of 1,000 would return approximately 1,000 records. With such a low cardinality the effectiveness is reduced to a linear sort, and the query optimizer will avoid using the index if the cardinality is less than 30% of the record number, effectively making the index a waste of space. | [
"sql",
"database",
"performance",
"indexing",
"database-indexes"
] | 2,882 | 4,140 | 1,116,553 | 7 | 0 | 2008-08-04T10:07:12.673000 | 2008-08-04T10:41:04.620000 |
1,131 | 1,135 | Windows Help files - what are the options? | Back in the old days, Help was not trivial but possible: generate some funky.rtf file with special tags, run it through a compiler, and you got a WinHelp file (.hlp) that actually works really well. Then, Microsoft decided that WinHelp was not hip and cool anymore and switched to CHM, up to the point they actually axed WinHelp from Vista. Now, CHM maybe nice, but everyone that tried to open a.chm file on the Network will know the nice "Navigation to the webpage was canceled" screen that is caused by security restrictions. While there are ways to make CHM work off the network, this is hardly a good choice, because when a user presses the Help Button he wants help and not have to make some funky settings. Bottom Line: I find CHM absolutely unusable. But with WinHelp not being an option anymore either, I wonder what the alternatives are, especially when it comes to integrate with my Application (i.e. for WinHelp and CHM there are functions that allow you to directly jump to a topic)? PDF has the disadvantage of requiring the Adobe Reader (or one of the more lightweight ones that not many people use). I could live with that seeing as this is kind of standard nowadays, but can you tell it reliably to jump to a given page/anchor? HTML files seem to be the best choice, you then just have to deal with different browsers (CSS and stuff). Edit: I am looking to create my own Help Files. As I am a fan of the "No Setup, Just Extract and Run" Philosophy, i had that problem many times in the past because many of my users will run it off the network, which causes exactly this problem. So i am looking for a more robust and future-proof way to provide help to my users without having to code a different help system for each application i make. CHM is a really nice format, but that Security Stuff makes it unusable, as a Help system is supposed to provide help to the user, not to generate even more problems. | HTML would be the next best choice, ONLY IF you would serve them from a public web server. If you tried to bundle it with your app, all the files (and images (and stylesheets (and...) ) ) would make CHM look like a gift from gods. That said, when actually bundled in the installation package, (instead of being served over the network), I found the CHM files to work nicely. OTOH, another pitfall about CHM files: Even if you try to open a CHM file on a local disk, you may bump into the security block if you initially downloaded it from somewhere, because the file could be marked as "came from external source" when it was obtained. | Windows Help files - what are the options? Back in the old days, Help was not trivial but possible: generate some funky.rtf file with special tags, run it through a compiler, and you got a WinHelp file (.hlp) that actually works really well. Then, Microsoft decided that WinHelp was not hip and cool anymore and switched to CHM, up to the point they actually axed WinHelp from Vista. Now, CHM maybe nice, but everyone that tried to open a.chm file on the Network will know the nice "Navigation to the webpage was canceled" screen that is caused by security restrictions. While there are ways to make CHM work off the network, this is hardly a good choice, because when a user presses the Help Button he wants help and not have to make some funky settings. Bottom Line: I find CHM absolutely unusable. But with WinHelp not being an option anymore either, I wonder what the alternatives are, especially when it comes to integrate with my Application (i.e. for WinHelp and CHM there are functions that allow you to directly jump to a topic)? PDF has the disadvantage of requiring the Adobe Reader (or one of the more lightweight ones that not many people use). I could live with that seeing as this is kind of standard nowadays, but can you tell it reliably to jump to a given page/anchor? HTML files seem to be the best choice, you then just have to deal with different browsers (CSS and stuff). Edit: I am looking to create my own Help Files. As I am a fan of the "No Setup, Just Extract and Run" Philosophy, i had that problem many times in the past because many of my users will run it off the network, which causes exactly this problem. So i am looking for a more robust and future-proof way to provide help to my users without having to code a different help system for each application i make. CHM is a really nice format, but that Security Stuff makes it unusable, as a Help system is supposed to provide help to the user, not to generate even more problems. | TITLE:
Windows Help files - what are the options?
QUESTION:
Back in the old days, Help was not trivial but possible: generate some funky.rtf file with special tags, run it through a compiler, and you got a WinHelp file (.hlp) that actually works really well. Then, Microsoft decided that WinHelp was not hip and cool anymore and switched to CHM, up to the point they actually axed WinHelp from Vista. Now, CHM maybe nice, but everyone that tried to open a.chm file on the Network will know the nice "Navigation to the webpage was canceled" screen that is caused by security restrictions. While there are ways to make CHM work off the network, this is hardly a good choice, because when a user presses the Help Button he wants help and not have to make some funky settings. Bottom Line: I find CHM absolutely unusable. But with WinHelp not being an option anymore either, I wonder what the alternatives are, especially when it comes to integrate with my Application (i.e. for WinHelp and CHM there are functions that allow you to directly jump to a topic)? PDF has the disadvantage of requiring the Adobe Reader (or one of the more lightweight ones that not many people use). I could live with that seeing as this is kind of standard nowadays, but can you tell it reliably to jump to a given page/anchor? HTML files seem to be the best choice, you then just have to deal with different browsers (CSS and stuff). Edit: I am looking to create my own Help Files. As I am a fan of the "No Setup, Just Extract and Run" Philosophy, i had that problem many times in the past because many of my users will run it off the network, which causes exactly this problem. So i am looking for a more robust and future-proof way to provide help to my users without having to code a different help system for each application i make. CHM is a really nice format, but that Security Stuff makes it unusable, as a Help system is supposed to provide help to the user, not to generate even more problems.
ANSWER:
HTML would be the next best choice, ONLY IF you would serve them from a public web server. If you tried to bundle it with your app, all the files (and images (and stylesheets (and...) ) ) would make CHM look like a gift from gods. That said, when actually bundled in the installation package, (instead of being served over the network), I found the CHM files to work nicely. OTOH, another pitfall about CHM files: Even if you try to open a CHM file on a local disk, you may bump into the security block if you initially downloaded it from somewhere, because the file could be marked as "came from external source" when it was obtained. | [
"windows",
"language-agnostic",
"chm",
"winhelp"
] | 39 | 14 | 5,199 | 10 | 0 | 2008-08-04T10:43:05.707000 | 2008-08-04T10:51:39.560000 |
1,145 | 1,154 | Why am I getting a double free or corruption error with realloc()? | I've tried to write a string replace function in C, which works on a char *, which has been allocated using malloc(). It's a little different in that it will find and replace strings, rather than characters in the starting string. It's trivial to do if the search and replace strings are the same length (or the replace string is shorter than the search string), since I have enough space allocated. If I try to use realloc(), I get an error that tells me I am doing a double free - which I don't see how I am, since I am only using realloc(). Perhaps a little code will help: void strrep(char *input, char *search, char *replace) { int searchLen = strlen(search); int replaceLen = strlen(replace); int delta = replaceLen - searchLen; char *find = input;
while (find = strstr(find, search)) {
if (delta > 0) { realloc(input, strlen(input) + delta); find = strstr(input, search); }
memmove(find + replaceLen, find + searchLen, strlen(input) - (find - input)); memmove(find, replace, replaceLen); } } The program works, until I try to realloc() in an instance where the replaced string will be longer than the initial string. (It still kind of works, it just spits out errors as well as the result). If it helps, the calling code looks like: #include #include #include void strrep(char *input, char *search, char *replace);
int main(void) { char *input = malloc(81);
while ((fgets(input, 81, stdin))!= NULL) { strrep(input, "Noel", "Christmas"); } } | As a general rule, you should never do a free or realloc on a user provided buffer. You don't know where the user allocated the space (in your module, in another DLL) so you cannot use any of the allocation functions on a user buffer. Provided that you now cannot do any reallocation within your function, you should change its behavior a little, like doing only one replacement, so the user will be able to compute the resulting string max length and provide you with a buffer long enough for this one replacement to occur. Then you could create another function to do the multiple replacements, but you will have to allocate the whole space for the resulting string and copy the user input string. Then you must provide a way to delete the string you allocated. Resulting in: void strrep(char *input, char *search, char *replace); char* strrepm(char *input, char *search, char *replace); void strrepmfree(char *input); | Why am I getting a double free or corruption error with realloc()? I've tried to write a string replace function in C, which works on a char *, which has been allocated using malloc(). It's a little different in that it will find and replace strings, rather than characters in the starting string. It's trivial to do if the search and replace strings are the same length (or the replace string is shorter than the search string), since I have enough space allocated. If I try to use realloc(), I get an error that tells me I am doing a double free - which I don't see how I am, since I am only using realloc(). Perhaps a little code will help: void strrep(char *input, char *search, char *replace) { int searchLen = strlen(search); int replaceLen = strlen(replace); int delta = replaceLen - searchLen; char *find = input;
while (find = strstr(find, search)) {
if (delta > 0) { realloc(input, strlen(input) + delta); find = strstr(input, search); }
memmove(find + replaceLen, find + searchLen, strlen(input) - (find - input)); memmove(find, replace, replaceLen); } } The program works, until I try to realloc() in an instance where the replaced string will be longer than the initial string. (It still kind of works, it just spits out errors as well as the result). If it helps, the calling code looks like: #include #include #include void strrep(char *input, char *search, char *replace);
int main(void) { char *input = malloc(81);
while ((fgets(input, 81, stdin))!= NULL) { strrep(input, "Noel", "Christmas"); } } | TITLE:
Why am I getting a double free or corruption error with realloc()?
QUESTION:
I've tried to write a string replace function in C, which works on a char *, which has been allocated using malloc(). It's a little different in that it will find and replace strings, rather than characters in the starting string. It's trivial to do if the search and replace strings are the same length (or the replace string is shorter than the search string), since I have enough space allocated. If I try to use realloc(), I get an error that tells me I am doing a double free - which I don't see how I am, since I am only using realloc(). Perhaps a little code will help: void strrep(char *input, char *search, char *replace) { int searchLen = strlen(search); int replaceLen = strlen(replace); int delta = replaceLen - searchLen; char *find = input;
while (find = strstr(find, search)) {
if (delta > 0) { realloc(input, strlen(input) + delta); find = strstr(input, search); }
memmove(find + replaceLen, find + searchLen, strlen(input) - (find - input)); memmove(find, replace, replaceLen); } } The program works, until I try to realloc() in an instance where the replaced string will be longer than the initial string. (It still kind of works, it just spits out errors as well as the result). If it helps, the calling code looks like: #include #include #include void strrep(char *input, char *search, char *replace);
int main(void) { char *input = malloc(81);
while ((fgets(input, 81, stdin))!= NULL) { strrep(input, "Noel", "Christmas"); } }
ANSWER:
As a general rule, you should never do a free or realloc on a user provided buffer. You don't know where the user allocated the space (in your module, in another DLL) so you cannot use any of the allocation functions on a user buffer. Provided that you now cannot do any reallocation within your function, you should change its behavior a little, like doing only one replacement, so the user will be able to compute the resulting string max length and provide you with a buffer long enough for this one replacement to occur. Then you could create another function to do the multiple replacements, but you will have to allocate the whole space for the resulting string and copy the user input string. Then you must provide a way to delete the string you allocated. Resulting in: void strrep(char *input, char *search, char *replace); char* strrepm(char *input, char *search, char *replace); void strrepmfree(char *input); | [
"c",
"malloc"
] | 19 | 15 | 9,107 | 8 | 0 | 2008-08-04T11:06:00.560000 | 2008-08-04T11:19:54.447000 |
1,156 | 1,157 | How do I index a database column | Hopefully, I can get answers for each database server. For an outline of how indexing works check out: How does database indexing work? | The following is SQL92 standard so should be supported by the majority of RDMBS that use SQL: CREATE INDEX [index name] ON [table name] ( [column name] ) | How do I index a database column Hopefully, I can get answers for each database server. For an outline of how indexing works check out: How does database indexing work? | TITLE:
How do I index a database column
QUESTION:
Hopefully, I can get answers for each database server. For an outline of how indexing works check out: How does database indexing work?
ANSWER:
The following is SQL92 standard so should be supported by the majority of RDMBS that use SQL: CREATE INDEX [index name] ON [table name] ( [column name] ) | [
"sql",
"database",
"indexing"
] | 66 | 70 | 50,057 | 9 | 0 | 2008-08-04T11:21:26.567000 | 2008-08-04T11:25:14.017000 |
1,160 | 975,299 | Use SVN Revision to label build in CCNET | I am using CCNET on a sample project with SVN as my source control. CCNET is configured to create a build on every check in. CCNET uses MSBuild to build the source code. I would like to use the latest revision number to generate AssemblyInfo.cs while compiling. How can I retrieve the latest revision from subversion and use the value in CCNET? Edit: I'm not using NAnt - only MSBuild. | CruiseControl.Net 1.4.4 has now an Assembly Version Labeller, which generates version numbers compatible with.Net assembly properties. In my project I have it configured as: (Caveat: assemblyVersionLabeller won't start generating svn revision based labels until an actual commit-triggered build occurs.) and then consume this from my MSBuild projects with MSBuildCommunityTasks.AssemblyInfo: For sake of completness, it's just as easy for projects using NAnt instead of MSBuild: | Use SVN Revision to label build in CCNET I am using CCNET on a sample project with SVN as my source control. CCNET is configured to create a build on every check in. CCNET uses MSBuild to build the source code. I would like to use the latest revision number to generate AssemblyInfo.cs while compiling. How can I retrieve the latest revision from subversion and use the value in CCNET? Edit: I'm not using NAnt - only MSBuild. | TITLE:
Use SVN Revision to label build in CCNET
QUESTION:
I am using CCNET on a sample project with SVN as my source control. CCNET is configured to create a build on every check in. CCNET uses MSBuild to build the source code. I would like to use the latest revision number to generate AssemblyInfo.cs while compiling. How can I retrieve the latest revision from subversion and use the value in CCNET? Edit: I'm not using NAnt - only MSBuild.
ANSWER:
CruiseControl.Net 1.4.4 has now an Assembly Version Labeller, which generates version numbers compatible with.Net assembly properties. In my project I have it configured as: (Caveat: assemblyVersionLabeller won't start generating svn revision based labels until an actual commit-triggered build occurs.) and then consume this from my MSBuild projects with MSBuildCommunityTasks.AssemblyInfo: For sake of completness, it's just as easy for projects using NAnt instead of MSBuild: | [
"svn",
"msbuild",
"cruisecontrol.net"
] | 42 | 45 | 18,980 | 12 | 0 | 2008-08-04T11:37:24.863000 | 2009-06-10T12:37:30.197000 |
1,171 | 28,705 | What is the most efficient graph data structure in Python? | I need to be able to manipulate a large (10^7 nodes) graph in python. The data corresponding to each node/edge is minimal, say, a small number of strings. What is the most efficient, in terms of memory and speed, way of doing this? A dict of dicts is more flexible and simpler to implement, but I intuitively expect a list of lists to be faster. The list option would also require that I keep the data separate from the structure, while dicts would allow for something of the sort: graph[I][J]["Property"]="value" What would you suggest? Yes, I should have been a bit clearer on what I mean by efficiency. In this particular case I mean it in terms of random access retrieval. Loading the data in to memory isn't a huge problem. That's done once and for all. The time consuming part is visiting the nodes so I can extract the information and measure the metrics I'm interested in. I hadn't considered making each node a class (properties are the same for all nodes) but it seems like that would add an extra layer of overhead? I was hoping someone would have some direct experience with a similar case that they could share. After all, graphs are one of the most common abstractions in CS. | I would strongly advocate you look at NetworkX. It's a battle-tested war horse and the first tool most 'research' types reach for when they need to do analysis of network based data. I have manipulated graphs with 100s of thousands of edges without problem on a notebook. Its feature rich and very easy to use. You will find yourself focusing more on the problem at hand rather than the details in the underlying implementation. Example of Erdős-Rényi random graph generation and analysis """ Create an G{n,m} random graph with n nodes and m edges and report some properties.
This graph is sometimes called the Erd##[m~Qs-Rényi graph but is different from G{n,p} or binomial_graph which is also sometimes called the Erd##[m~Qs-Rényi graph. """ __author__ = """Aric Hagberg (hagberg@lanl.gov)""" __credits__ = """""" # Copyright (C) 2004-2006 by # Aric Hagberg # Dan Schult # Pieter Swart # Distributed under the terms of the GNU Lesser General Public License # http://www.gnu.org/copyleft/lesser.html
from networkx import * import sys
n=10 # 10 nodes m=20 # 20 edges
G=gnm_random_graph(n,m)
# some properties print "node degree clustering" for v in nodes(G): print v,degree(G,v),clustering(G,v)
# print the adjacency list to terminal write_adjlist(G,sys.stdout) Visualizations are also straightforward: More visualization: http://jonschull.blogspot.com/2008/08/graph-visualization.html | What is the most efficient graph data structure in Python? I need to be able to manipulate a large (10^7 nodes) graph in python. The data corresponding to each node/edge is minimal, say, a small number of strings. What is the most efficient, in terms of memory and speed, way of doing this? A dict of dicts is more flexible and simpler to implement, but I intuitively expect a list of lists to be faster. The list option would also require that I keep the data separate from the structure, while dicts would allow for something of the sort: graph[I][J]["Property"]="value" What would you suggest? Yes, I should have been a bit clearer on what I mean by efficiency. In this particular case I mean it in terms of random access retrieval. Loading the data in to memory isn't a huge problem. That's done once and for all. The time consuming part is visiting the nodes so I can extract the information and measure the metrics I'm interested in. I hadn't considered making each node a class (properties are the same for all nodes) but it seems like that would add an extra layer of overhead? I was hoping someone would have some direct experience with a similar case that they could share. After all, graphs are one of the most common abstractions in CS. | TITLE:
What is the most efficient graph data structure in Python?
QUESTION:
I need to be able to manipulate a large (10^7 nodes) graph in python. The data corresponding to each node/edge is minimal, say, a small number of strings. What is the most efficient, in terms of memory and speed, way of doing this? A dict of dicts is more flexible and simpler to implement, but I intuitively expect a list of lists to be faster. The list option would also require that I keep the data separate from the structure, while dicts would allow for something of the sort: graph[I][J]["Property"]="value" What would you suggest? Yes, I should have been a bit clearer on what I mean by efficiency. In this particular case I mean it in terms of random access retrieval. Loading the data in to memory isn't a huge problem. That's done once and for all. The time consuming part is visiting the nodes so I can extract the information and measure the metrics I'm interested in. I hadn't considered making each node a class (properties are the same for all nodes) but it seems like that would add an extra layer of overhead? I was hoping someone would have some direct experience with a similar case that they could share. After all, graphs are one of the most common abstractions in CS.
ANSWER:
I would strongly advocate you look at NetworkX. It's a battle-tested war horse and the first tool most 'research' types reach for when they need to do analysis of network based data. I have manipulated graphs with 100s of thousands of edges without problem on a notebook. Its feature rich and very easy to use. You will find yourself focusing more on the problem at hand rather than the details in the underlying implementation. Example of Erdős-Rényi random graph generation and analysis """ Create an G{n,m} random graph with n nodes and m edges and report some properties.
This graph is sometimes called the Erd##[m~Qs-Rényi graph but is different from G{n,p} or binomial_graph which is also sometimes called the Erd##[m~Qs-Rényi graph. """ __author__ = """Aric Hagberg (hagberg@lanl.gov)""" __credits__ = """""" # Copyright (C) 2004-2006 by # Aric Hagberg # Dan Schult # Pieter Swart # Distributed under the terms of the GNU Lesser General Public License # http://www.gnu.org/copyleft/lesser.html
from networkx import * import sys
n=10 # 10 nodes m=20 # 20 edges
G=gnm_random_graph(n,m)
# some properties print "node degree clustering" for v in nodes(G): print v,degree(G,v),clustering(G,v)
# print the adjacency list to terminal write_adjlist(G,sys.stdout) Visualizations are also straightforward: More visualization: http://jonschull.blogspot.com/2008/08/graph-visualization.html | [
"python",
"performance",
"data-structures",
"graph-theory"
] | 73 | 56 | 31,896 | 7 | 0 | 2008-08-04T12:00:57.297000 | 2008-08-26T17:43:06.413000 |
1,180 | 1,232 | How to make subdomain user accounts in a webapp | I am looking to allow users to control of subdomain of an app I am toying with, much like Basecamp where it is customusername.seework.com. What is required on the DNS end to allow these to be created dynamically and be available instantly. And how do you recommend dealing with this in the logic of the site? Htaccess rule to lookup the subdomain in the DB? | The way we do this is to have a 'catch all' for our domain name registered in DNS so that anything.ourdomain.com will point to our server. With Apache you can set up a similar catch-all for your vhosts. The ServerName must be a single static name but the ServerAlias directive can contain a pattern. Servername www.ourdomain.com ServerAlias *.ourdomain.com Now all of the domains will trigger the vhost for our project. The final part is to decode the domain name actually used so that you can work out the username in your code, something like (PHP): list( $username ) = explode( ".", $_SERVER[ "HTTP_HOST" ] ); or a RewriteRule as already suggested that silently maps user.ourdomain.com/foo/bar to www.ourdomain.com/foo/bar?user=user or whatever you prefer. | How to make subdomain user accounts in a webapp I am looking to allow users to control of subdomain of an app I am toying with, much like Basecamp where it is customusername.seework.com. What is required on the DNS end to allow these to be created dynamically and be available instantly. And how do you recommend dealing with this in the logic of the site? Htaccess rule to lookup the subdomain in the DB? | TITLE:
How to make subdomain user accounts in a webapp
QUESTION:
I am looking to allow users to control of subdomain of an app I am toying with, much like Basecamp where it is customusername.seework.com. What is required on the DNS end to allow these to be created dynamically and be available instantly. And how do you recommend dealing with this in the logic of the site? Htaccess rule to lookup the subdomain in the DB?
ANSWER:
The way we do this is to have a 'catch all' for our domain name registered in DNS so that anything.ourdomain.com will point to our server. With Apache you can set up a similar catch-all for your vhosts. The ServerName must be a single static name but the ServerAlias directive can contain a pattern. Servername www.ourdomain.com ServerAlias *.ourdomain.com Now all of the domains will trigger the vhost for our project. The final part is to decode the domain name actually used so that you can work out the username in your code, something like (PHP): list( $username ) = explode( ".", $_SERVER[ "HTTP_HOST" ] ); or a RewriteRule as already suggested that silently maps user.ourdomain.com/foo/bar to www.ourdomain.com/foo/bar?user=user or whatever you prefer. | [
"web-applications",
"dns",
"subdomain",
"account"
] | 25 | 15 | 6,151 | 4 | 0 | 2008-08-04T12:22:07.910000 | 2008-08-04T13:39:39.423000 |
1,189 | 1,190 | ViewState invalid only in Safari | One of the sites I maintain relies heavily on the use of ViewState (it isn't my code). However, on certain pages where the ViewState is extra-bloated, Safari throws a "Validation of viewstate MAC failed" error. This appears to only happen in Safari. Firefox, IE and Opera all load successfully in the same scenario. | I've been doing a little research into this and whilst I'm not entirely sure its the cause I believe it is because Safari is not returning the full result set (hence cropping it). I have been in dicussion with another developer and found the following post on Channel 9 as well which recommends making use of the SQL State service to store the viewstate avoiding the postback issue and also page size. http://channel9.msdn.com/forums/TechOff/250549-ASPNET-ViewState-flawed-architecture/?CommentID=270477#263702 Does this seem like the best solution? | ViewState invalid only in Safari One of the sites I maintain relies heavily on the use of ViewState (it isn't my code). However, on certain pages where the ViewState is extra-bloated, Safari throws a "Validation of viewstate MAC failed" error. This appears to only happen in Safari. Firefox, IE and Opera all load successfully in the same scenario. | TITLE:
ViewState invalid only in Safari
QUESTION:
One of the sites I maintain relies heavily on the use of ViewState (it isn't my code). However, on certain pages where the ViewState is extra-bloated, Safari throws a "Validation of viewstate MAC failed" error. This appears to only happen in Safari. Firefox, IE and Opera all load successfully in the same scenario.
ANSWER:
I've been doing a little research into this and whilst I'm not entirely sure its the cause I believe it is because Safari is not returning the full result set (hence cropping it). I have been in dicussion with another developer and found the following post on Channel 9 as well which recommends making use of the SQL State service to store the viewstate avoiding the postback issue and also page size. http://channel9.msdn.com/forums/TechOff/250549-ASPNET-ViewState-flawed-architecture/?CommentID=270477#263702 Does this seem like the best solution? | [
"c#",
".net",
"safari",
"viewstate"
] | 16 | 2 | 3,400 | 3 | 0 | 2008-08-04T12:38:21.263000 | 2008-08-04T12:40:49.137000 |
1,237 | 1,243 | Regex: To pull out a sub-string between two tags in a string | I have a file in the following format: Data Data Data [Start] Data I want [End] Data I'd like to grab the Data I want from between the [Start] and [End] tags using a Regex. Can anyone show me how this might be done? | \[start\]\s*(((?!\[start\]|\[end\]).)+)\s*\[end\] This should hopefully drop the [start] and [end] markers as well. | Regex: To pull out a sub-string between two tags in a string I have a file in the following format: Data Data Data [Start] Data I want [End] Data I'd like to grab the Data I want from between the [Start] and [End] tags using a Regex. Can anyone show me how this might be done? | TITLE:
Regex: To pull out a sub-string between two tags in a string
QUESTION:
I have a file in the following format: Data Data Data [Start] Data I want [End] Data I'd like to grab the Data I want from between the [Start] and [End] tags using a Regex. Can anyone show me how this might be done?
ANSWER:
\[start\]\s*(((?!\[start\]|\[end\]).)+)\s*\[end\] This should hopefully drop the [start] and [end] markers as well. | [
"regex",
"parsing"
] | 48 | 23 | 87,240 | 9 | 0 | 2008-08-04T13:47:10.547000 | 2008-08-04T13:55:05.647000 |
1,241 | 1,275 | Asynchronous multi-direction server-client communication over the same open socket? | I have a client-server app where the client is on a Windows Mobile 6 device, written in C++ and the server is on full Windows and written in C#. Originally, I only needed it to send messages from the client to the server, with the server only ever sending back an acknowledgment that it received the message. Now, I would like to update it so that the server can actually send a message to the client to request data. As I currently have it set up so the client is only in receive mode after it sends data to the server, this doesn't allow for the server to send a request at any time. I would have to wait for client data. My first thought would be to create another thread on the client with a separate open socket, listening for server requests...just like the server already has with respect to the client. Is there a way, within the same thread and using the same socket, for all the servers to send requests at any time? Can you use something to the effect of WaitForMultipleObjects() and pass it a receive buffer and an event that tells it there is data to be sent? | When I needed to write an application with a client-server model where the clients could leave and enter whenever they want, (I assume that's also the case for your application as you use mobile devices) I made sure that the clients send an online message to the server, indicating they were connected and ready to do whatever they needed doing. at that time the server could send messages back to the client trough the same open connection. Also, but I don't know if that is applicable for you, I had some sort of heartbeat the clients sent to the server, letting it know it was still online. That way the server knows when a client was forcibly disconnected from the network and it could mark that client back as offline. | Asynchronous multi-direction server-client communication over the same open socket? I have a client-server app where the client is on a Windows Mobile 6 device, written in C++ and the server is on full Windows and written in C#. Originally, I only needed it to send messages from the client to the server, with the server only ever sending back an acknowledgment that it received the message. Now, I would like to update it so that the server can actually send a message to the client to request data. As I currently have it set up so the client is only in receive mode after it sends data to the server, this doesn't allow for the server to send a request at any time. I would have to wait for client data. My first thought would be to create another thread on the client with a separate open socket, listening for server requests...just like the server already has with respect to the client. Is there a way, within the same thread and using the same socket, for all the servers to send requests at any time? Can you use something to the effect of WaitForMultipleObjects() and pass it a receive buffer and an event that tells it there is data to be sent? | TITLE:
Asynchronous multi-direction server-client communication over the same open socket?
QUESTION:
I have a client-server app where the client is on a Windows Mobile 6 device, written in C++ and the server is on full Windows and written in C#. Originally, I only needed it to send messages from the client to the server, with the server only ever sending back an acknowledgment that it received the message. Now, I would like to update it so that the server can actually send a message to the client to request data. As I currently have it set up so the client is only in receive mode after it sends data to the server, this doesn't allow for the server to send a request at any time. I would have to wait for client data. My first thought would be to create another thread on the client with a separate open socket, listening for server requests...just like the server already has with respect to the client. Is there a way, within the same thread and using the same socket, for all the servers to send requests at any time? Can you use something to the effect of WaitForMultipleObjects() and pass it a receive buffer and an event that tells it there is data to be sent?
ANSWER:
When I needed to write an application with a client-server model where the clients could leave and enter whenever they want, (I assume that's also the case for your application as you use mobile devices) I made sure that the clients send an online message to the server, indicating they were connected and ready to do whatever they needed doing. at that time the server could send messages back to the client trough the same open connection. Also, but I don't know if that is applicable for you, I had some sort of heartbeat the clients sent to the server, letting it know it was still online. That way the server knows when a client was forcibly disconnected from the network and it could mark that client back as offline. | [
"c#",
"c++",
"sockets"
] | 27 | 9 | 2,963 | 4 | 0 | 2008-08-04T13:52:25.090000 | 2008-08-04T14:30:12.223000 |
1,261 | 1,272 | What are the advantages of using SVN over CVS? | My company is using CVS as our de-facto standard for source control. However, I've heard a lot of people say that SVN is better. I know SVN is newer, but other than that, I'm unfamiliar with its benefits. What I'm looking for is a good, succinct comparison of the two systems, noting any advantages or disadvantages of each in a Java/Eclipse development environment. | CVS only tracks modification on a file-by-file basis, while SVN tracks a whole commit as a new revision, which means that it is easier to follow the history of your project. Add the fact that all modern source control software use the concept of revision so it is far easier to migrate from SVN than it is from CVS. There is also the atomic commit problem. While I only encountered it once, it is possible that 2 people committing together in CVS can conflict each other, losing some data and putting your client in an inconsistent state. When detected early, these problems are not major because your data is still out there somewhere, but it can be a pain in a stressful environment. And finally, not many tools are developed around CVS anymore. While the new and shiny-new tools like Git or Mercurial definitely lack tools yet, SVN has a pretty large application base on any system. EDIT 2020: Seriously, this answer is 12 years old now. Forget SVN, go use Git like everyone else! | What are the advantages of using SVN over CVS? My company is using CVS as our de-facto standard for source control. However, I've heard a lot of people say that SVN is better. I know SVN is newer, but other than that, I'm unfamiliar with its benefits. What I'm looking for is a good, succinct comparison of the two systems, noting any advantages or disadvantages of each in a Java/Eclipse development environment. | TITLE:
What are the advantages of using SVN over CVS?
QUESTION:
My company is using CVS as our de-facto standard for source control. However, I've heard a lot of people say that SVN is better. I know SVN is newer, but other than that, I'm unfamiliar with its benefits. What I'm looking for is a good, succinct comparison of the two systems, noting any advantages or disadvantages of each in a Java/Eclipse development environment.
ANSWER:
CVS only tracks modification on a file-by-file basis, while SVN tracks a whole commit as a new revision, which means that it is easier to follow the history of your project. Add the fact that all modern source control software use the concept of revision so it is far easier to migrate from SVN than it is from CVS. There is also the atomic commit problem. While I only encountered it once, it is possible that 2 people committing together in CVS can conflict each other, losing some data and putting your client in an inconsistent state. When detected early, these problems are not major because your data is still out there somewhere, but it can be a pain in a stressful environment. And finally, not many tools are developed around CVS anymore. While the new and shiny-new tools like Git or Mercurial definitely lack tools yet, SVN has a pretty large application base on any system. EDIT 2020: Seriously, this answer is 12 years old now. Forget SVN, go use Git like everyone else! | [
"svn",
"version-control",
"cvs"
] | 66 | 67 | 43,004 | 12 | 0 | 2008-08-04T14:06:48.540000 | 2008-08-04T14:17:59.080000 |
1,276 | 1,338 | How big can a MySQL database get before performance starts to degrade | At what point does a MySQL database start to lose performance? Does physical database size matter? Do number of records matter? Is any performance degradation linear or exponential? I have what I believe to be a large database, with roughly 15M records which take up almost 2GB. Based on these numbers, is there any incentive for me to clean the data out, or am I safe to allow it to continue scaling for a few more years? | The physical database size doesn't matter. The number of records don't matter. In my experience the biggest problem that you are going to run in to is not size, but the number of queries you can handle at a time. Most likely you are going to have to move to a master/slave configuration so that the read queries can run against the slaves and the write queries run against the master. However if you are not ready for this yet, you can always tweak your indexes for the queries you are running to speed up the response times. Also there is a lot of tweaking you can do to the network stack and kernel in Linux that will help. I have had mine get up to 10GB, with only a moderate number of connections and it handled the requests just fine. I would focus first on your indexes, then have a server admin look at your OS, and if all that doesn't help it might be time to implement a master/slave configuration. | How big can a MySQL database get before performance starts to degrade At what point does a MySQL database start to lose performance? Does physical database size matter? Do number of records matter? Is any performance degradation linear or exponential? I have what I believe to be a large database, with roughly 15M records which take up almost 2GB. Based on these numbers, is there any incentive for me to clean the data out, or am I safe to allow it to continue scaling for a few more years? | TITLE:
How big can a MySQL database get before performance starts to degrade
QUESTION:
At what point does a MySQL database start to lose performance? Does physical database size matter? Do number of records matter? Is any performance degradation linear or exponential? I have what I believe to be a large database, with roughly 15M records which take up almost 2GB. Based on these numbers, is there any incentive for me to clean the data out, or am I safe to allow it to continue scaling for a few more years?
ANSWER:
The physical database size doesn't matter. The number of records don't matter. In my experience the biggest problem that you are going to run in to is not size, but the number of queries you can handle at a time. Most likely you are going to have to move to a master/slave configuration so that the read queries can run against the slaves and the write queries run against the master. However if you are not ready for this yet, you can always tweak your indexes for the queries you are running to speed up the response times. Also there is a lot of tweaking you can do to the network stack and kernel in Linux that will help. I have had mine get up to 10GB, with only a moderate number of connections and it handled the requests just fine. I would focus first on your indexes, then have a server admin look at your OS, and if all that doesn't help it might be time to implement a master/slave configuration. | [
"mysql",
"database",
"database-performance"
] | 340 | 225 | 227,922 | 15 | 0 | 2008-08-04T14:31:11.410000 | 2008-08-04T15:26:55.807000 |
1,292 | 1,305 | Limit size of Queue<T> in .NET? | I have a Queue object that I have initialised to a capacity of 2, but obviously that is just the capacity and it keeps expanding as I add items. Is there already an object that automatically dequeues an item when the limit is reached, or is the best solution to create my own inherited class? | I've knocked up a basic version of what I'm looking for, it's not perfect but it'll do the job until something better comes along. public class LimitedQueue: Queue { public int Limit { get; set; }
public LimitedQueue(int limit): base(limit) { Limit = limit; }
public new void Enqueue(T item) { while (Count >= Limit) { Dequeue(); } base.Enqueue(item); } } | Limit size of Queue<T> in .NET? I have a Queue object that I have initialised to a capacity of 2, but obviously that is just the capacity and it keeps expanding as I add items. Is there already an object that automatically dequeues an item when the limit is reached, or is the best solution to create my own inherited class? | TITLE:
Limit size of Queue<T> in .NET?
QUESTION:
I have a Queue object that I have initialised to a capacity of 2, but obviously that is just the capacity and it keeps expanding as I add items. Is there already an object that automatically dequeues an item when the limit is reached, or is the best solution to create my own inherited class?
ANSWER:
I've knocked up a basic version of what I'm looking for, it's not perfect but it'll do the job until something better comes along. public class LimitedQueue: Queue { public int Limit { get; set; }
public LimitedQueue(int limit): base(limit) { Limit = limit; }
public new void Enqueue(T item) { while (Count >= Limit) { Dequeue(); } base.Enqueue(item); } } | [
".net",
"collections",
"queue"
] | 63 | 48 | 36,962 | 8 | 0 | 2008-08-04T14:47:10.970000 | 2008-08-04T14:57:28.767000 |
1,300 | 1,673 | Is nAnt still supported and suitable for .net 3.5/VS2008? | I am using MSBuild to build my stuff. I want to use CruiseControl.net as by Build Server. Now, CCNET refers nAnt a lot, but it looks as if ccnet can do most of the stuff nant could do through the project configuration and msbuild. Also, nAnt seems a bit unsupported, with a Beta release that is almost a year old now. In short: I am actually quite happy with MSBuild (especially since it's the "official" compiler front end) and a bit uncomfortable with nAnt, but I do not want to judge prematurely. What would be reasons to use nAnt over MSBuild? Especially with ccnet, which seems to overlap a bit with nant in terms of features (and adding the automated build related stuff) | If you are quite happy with MSBuild, then I would stick with MSBuild. This may be one of those cases where the tool you learn first is the one you will prefer. I started with NAnt and can't quite get used to MSBuild. I'm sure they will both be around for quite some time. There are some fundamental differences between the two, probably best highlighted by this conversation between some NAnt fans and a Microsoftie. Interestingly, Jeremy Miller asked the exact opposite question on his blog last year. | Is nAnt still supported and suitable for .net 3.5/VS2008? I am using MSBuild to build my stuff. I want to use CruiseControl.net as by Build Server. Now, CCNET refers nAnt a lot, but it looks as if ccnet can do most of the stuff nant could do through the project configuration and msbuild. Also, nAnt seems a bit unsupported, with a Beta release that is almost a year old now. In short: I am actually quite happy with MSBuild (especially since it's the "official" compiler front end) and a bit uncomfortable with nAnt, but I do not want to judge prematurely. What would be reasons to use nAnt over MSBuild? Especially with ccnet, which seems to overlap a bit with nant in terms of features (and adding the automated build related stuff) | TITLE:
Is nAnt still supported and suitable for .net 3.5/VS2008?
QUESTION:
I am using MSBuild to build my stuff. I want to use CruiseControl.net as by Build Server. Now, CCNET refers nAnt a lot, but it looks as if ccnet can do most of the stuff nant could do through the project configuration and msbuild. Also, nAnt seems a bit unsupported, with a Beta release that is almost a year old now. In short: I am actually quite happy with MSBuild (especially since it's the "official" compiler front end) and a bit uncomfortable with nAnt, but I do not want to judge prematurely. What would be reasons to use nAnt over MSBuild? Especially with ccnet, which seems to overlap a bit with nant in terms of features (and adding the automated build related stuff)
ANSWER:
If you are quite happy with MSBuild, then I would stick with MSBuild. This may be one of those cases where the tool you learn first is the one you will prefer. I started with NAnt and can't quite get used to MSBuild. I'm sure they will both be around for quite some time. There are some fundamental differences between the two, probably best highlighted by this conversation between some NAnt fans and a Microsoftie. Interestingly, Jeremy Miller asked the exact opposite question on his blog last year. | [
".net",
".net-3.5",
"msbuild",
"nant"
] | 31 | 15 | 4,052 | 7 | 0 | 2008-08-04T14:55:04.433000 | 2008-08-04T22:52:31.677000 |
1,304 | 1,309 | How to check for file lock? | Is there any way to check whether a file is locked without using a try/catch block? Right now, the only way I know of is to just open the file and catch any System.IO.IOException. | No, unfortunately, and if you think about it, that information would be worthless anyway since the file could become locked the very next second (read: short timespan). Why specifically do you need to know if the file is locked anyway? Knowing that might give us some other way of giving you good advice. If your code would look like this: if not locked then open and update file Then between the two lines, another process could easily lock the file, giving you the same problem you were trying to avoid to begin with: exceptions. | How to check for file lock? Is there any way to check whether a file is locked without using a try/catch block? Right now, the only way I know of is to just open the file and catch any System.IO.IOException. | TITLE:
How to check for file lock?
QUESTION:
Is there any way to check whether a file is locked without using a try/catch block? Right now, the only way I know of is to just open the file and catch any System.IO.IOException.
ANSWER:
No, unfortunately, and if you think about it, that information would be worthless anyway since the file could become locked the very next second (read: short timespan). Why specifically do you need to know if the file is locked anyway? Knowing that might give us some other way of giving you good advice. If your code would look like this: if not locked then open and update file Then between the two lines, another process could easily lock the file, giving you the same problem you were trying to avoid to begin with: exceptions. | [
"c#",
".net",
"io",
"filelock"
] | 270 | 133 | 240,613 | 12 | 0 | 2008-08-04T14:56:57.490000 | 2008-08-04T14:59:24.410000 |
1,306 | 1,318 | How do I use (n)curses in Ruby? | I'd like to create a progress bar to indicate the status of an a batch job in Ruby. I've read some tutorials / libraries on using (n)curses, none of which were particularly helpful in explaining how to create an "animated" progress bar in the terminal or using curses with Ruby. I'm already aware of using a separate thread to monitor the progress of a given job, I'm just not sure how to proceed with drawing a progress bar. Update ProgressBar class was incredibly straight-forward, perfectly solved my problem. | You might be able to get some implementation ideas from the Ruby/ProgressBar library, which generates text progress bars. I stumbled across it a couple of months back but haven't made any use of it. | How do I use (n)curses in Ruby? I'd like to create a progress bar to indicate the status of an a batch job in Ruby. I've read some tutorials / libraries on using (n)curses, none of which were particularly helpful in explaining how to create an "animated" progress bar in the terminal or using curses with Ruby. I'm already aware of using a separate thread to monitor the progress of a given job, I'm just not sure how to proceed with drawing a progress bar. Update ProgressBar class was incredibly straight-forward, perfectly solved my problem. | TITLE:
How do I use (n)curses in Ruby?
QUESTION:
I'd like to create a progress bar to indicate the status of an a batch job in Ruby. I've read some tutorials / libraries on using (n)curses, none of which were particularly helpful in explaining how to create an "animated" progress bar in the terminal or using curses with Ruby. I'm already aware of using a separate thread to monitor the progress of a given job, I'm just not sure how to proceed with drawing a progress bar. Update ProgressBar class was incredibly straight-forward, perfectly solved my problem.
ANSWER:
You might be able to get some implementation ideas from the Ruby/ProgressBar library, which generates text progress bars. I stumbled across it a couple of months back but haven't made any use of it. | [
"ruby",
"unix",
"curses"
] | 46 | 21 | 12,787 | 4 | 0 | 2008-08-04T14:57:59.547000 | 2008-08-04T15:11:19.770000 |
1,313 | 74,033 | Followup: Finding an accurate "distance" between colors | Original Question I am looking for a function that attempts to quantify how "distant" (or distinct) two colors are. This question is really in two parts: What color space best represents human vision? What distance metric in that space best represents human vision (euclidean?) | Convert to La*b* (aka just plain "Lab", and you'll also see reference to "CIELAB"). A good quick measaure of color difference is (L1-L2)^2 + (a1-a2)^2 + (b1-b2)^2 Color scientists have other more refined measures, which may not be worth the bother, depending on accuracy needed for what you're doing. The a and b values represent opposing colors in a way similar to how cones work, and may be negative or positive. Neutral colors - white, grays are a=0, b=0. The L is brightness defined in a particular way, from zero (pure darkness) up to whatever. Crude explanation:>> Given a color, our eyes distinguish between two broad ranges of wavelength - blue vs longer wavelengths. and then, thanks to a more recent genetic mutation, the longer wavelength cones bifurcated into two, distinguishing for us red vs. green. By the way, it'll be great for your career to rise above your color caveman collegues who know of only "RGB" or "CMYK" which are great for devices but suck for serious perception work. I've worked for imaging scientists who didn't know a thing about this stuff! For more fun reading on color difference theory, try: http://white.stanford.edu/~brian/scielab/introduction.html and info and links on color theory in general, websurf starting with http://www.efg2.com/Lab/Library/Color/ and http://www.poynton.com/Poynton-color.html More detail on Lab at http://en.kioskea.net/video/cie-lab.php3 I can't at this time find a non-ugly page that actually had the conversion formulas but I'm sure someone will edit this answer to include one. | Followup: Finding an accurate "distance" between colors Original Question I am looking for a function that attempts to quantify how "distant" (or distinct) two colors are. This question is really in two parts: What color space best represents human vision? What distance metric in that space best represents human vision (euclidean?) | TITLE:
Followup: Finding an accurate "distance" between colors
QUESTION:
Original Question I am looking for a function that attempts to quantify how "distant" (or distinct) two colors are. This question is really in two parts: What color space best represents human vision? What distance metric in that space best represents human vision (euclidean?)
ANSWER:
Convert to La*b* (aka just plain "Lab", and you'll also see reference to "CIELAB"). A good quick measaure of color difference is (L1-L2)^2 + (a1-a2)^2 + (b1-b2)^2 Color scientists have other more refined measures, which may not be worth the bother, depending on accuracy needed for what you're doing. The a and b values represent opposing colors in a way similar to how cones work, and may be negative or positive. Neutral colors - white, grays are a=0, b=0. The L is brightness defined in a particular way, from zero (pure darkness) up to whatever. Crude explanation:>> Given a color, our eyes distinguish between two broad ranges of wavelength - blue vs longer wavelengths. and then, thanks to a more recent genetic mutation, the longer wavelength cones bifurcated into two, distinguishing for us red vs. green. By the way, it'll be great for your career to rise above your color caveman collegues who know of only "RGB" or "CMYK" which are great for devices but suck for serious perception work. I've worked for imaging scientists who didn't know a thing about this stuff! For more fun reading on color difference theory, try: http://white.stanford.edu/~brian/scielab/introduction.html and info and links on color theory in general, websurf starting with http://www.efg2.com/Lab/Library/Color/ and http://www.poynton.com/Poynton-color.html More detail on Lab at http://en.kioskea.net/video/cie-lab.php3 I can't at this time find a non-ugly page that actually had the conversion formulas but I'm sure someone will edit this answer to include one. | [
"language-agnostic",
"colors"
] | 53 | 48 | 20,891 | 7 | 0 | 2008-08-04T15:08:13.143000 | 2008-09-16T16:08:42.313000 |
1,314 | 1,319 | Using MSTest with CruiseControl.NET | We have been using CruiseControl for quite a while with NUnit and NAnt. For a recent project we decided to use the testing framework that comes with Visual Studio, which so far has been adequate. I'm attempting to get the solution running in CruiseControl. I've finally got the build itself to work; however, I have been unable to get any tests to show up in the CruiseControl interface despite adding custom build tasks and components designed to do just that. Does anyone have a definitive link out there to instructions on getting this set up? | Not sure if that helps (i found the ccnet Documentation somewhat unhelpful at times): Using CruiseControl.NET with MSTest | Using MSTest with CruiseControl.NET We have been using CruiseControl for quite a while with NUnit and NAnt. For a recent project we decided to use the testing framework that comes with Visual Studio, which so far has been adequate. I'm attempting to get the solution running in CruiseControl. I've finally got the build itself to work; however, I have been unable to get any tests to show up in the CruiseControl interface despite adding custom build tasks and components designed to do just that. Does anyone have a definitive link out there to instructions on getting this set up? | TITLE:
Using MSTest with CruiseControl.NET
QUESTION:
We have been using CruiseControl for quite a while with NUnit and NAnt. For a recent project we decided to use the testing framework that comes with Visual Studio, which so far has been adequate. I'm attempting to get the solution running in CruiseControl. I've finally got the build itself to work; however, I have been unable to get any tests to show up in the CruiseControl interface despite adding custom build tasks and components designed to do just that. Does anyone have a definitive link out there to instructions on getting this set up?
ANSWER:
Not sure if that helps (i found the ccnet Documentation somewhat unhelpful at times): Using CruiseControl.NET with MSTest | [
"msbuild",
"build-process",
"cruisecontrol.net"
] | 19 | 5 | 2,076 | 2 | 0 | 2008-08-04T15:09:07.043000 | 2008-08-04T15:12:13.917000 |
1,329 | 1,339 | What is a better file copy alternative than the Windows default? | I need to copy hundreds of gigs of random files around on my computer and am pretty leery of using the vanilla file copy built into Windows. I don't want it to hang on a "Are you sure?", "Are you really sure?", "Even zip files?", "Surely not read-only files too!" loop as soon as I step away. I don't want it to work for hours and then stop unexpectedly: "Someone once opened this file and so I won't copy it!" and then cancel the whole copy or just quit with no indication of what was done and what work remains. What file management programs do you have experience with? Which do you recommend? This question is related to my other question: How can I use an old PATA hard disk drive on my newer SATA-only computer? | How about good old Command-Line Xcopy? With S: being the source and T: the target: xcopy /K /R /E /I /S /C /H /G /X /Y s:\*.* t:\ /K Copies attributes. Normal Xcopy will reset read-only attributes. /R Overwrites read-only files. /E Copies directories and subdirectories, including empty ones. /I If destination does not exist and copying more than one file, assumes that destination must be a directory. /S Copies directories and subdirectories except empty ones. /C Continues copying even if errors occur. /H Copies hidden and system files also. /Y Suppresses prompting to confirm you want to overwrite an existing destination file. /G Allows the copying of encrypted files to destination that does not support encryption. /X Copies file audit settings (implies /O). (Edit: Added /G and /X which are new since a few years) | What is a better file copy alternative than the Windows default? I need to copy hundreds of gigs of random files around on my computer and am pretty leery of using the vanilla file copy built into Windows. I don't want it to hang on a "Are you sure?", "Are you really sure?", "Even zip files?", "Surely not read-only files too!" loop as soon as I step away. I don't want it to work for hours and then stop unexpectedly: "Someone once opened this file and so I won't copy it!" and then cancel the whole copy or just quit with no indication of what was done and what work remains. What file management programs do you have experience with? Which do you recommend? This question is related to my other question: How can I use an old PATA hard disk drive on my newer SATA-only computer? | TITLE:
What is a better file copy alternative than the Windows default?
QUESTION:
I need to copy hundreds of gigs of random files around on my computer and am pretty leery of using the vanilla file copy built into Windows. I don't want it to hang on a "Are you sure?", "Are you really sure?", "Even zip files?", "Surely not read-only files too!" loop as soon as I step away. I don't want it to work for hours and then stop unexpectedly: "Someone once opened this file and so I won't copy it!" and then cancel the whole copy or just quit with no indication of what was done and what work remains. What file management programs do you have experience with? Which do you recommend? This question is related to my other question: How can I use an old PATA hard disk drive on my newer SATA-only computer?
ANSWER:
How about good old Command-Line Xcopy? With S: being the source and T: the target: xcopy /K /R /E /I /S /C /H /G /X /Y s:\*.* t:\ /K Copies attributes. Normal Xcopy will reset read-only attributes. /R Overwrites read-only files. /E Copies directories and subdirectories, including empty ones. /I If destination does not exist and copying more than one file, assumes that destination must be a directory. /S Copies directories and subdirectories except empty ones. /C Continues copying even if errors occur. /H Copies hidden and system files also. /Y Suppresses prompting to confirm you want to overwrite an existing destination file. /G Allows the copying of encrypted files to destination that does not support encryption. /X Copies file audit settings (implies /O). (Edit: Added /G and /X which are new since a few years) | [
"windows",
"file",
"filesystems",
"utilities"
] | 38 | 20 | 101,345 | 22 | 0 | 2008-08-04T15:20:42.683000 | 2008-08-04T15:28:23.527000 |
1,383 | 1,393 | What is unit testing? | I saw many questions asking 'how' to unit test in a specific language, but no question asking 'what', 'why', and 'when'. What is it? What does it do for me? Why should I use it? When should I use it (also when not)? What are some common pitfalls and misconceptions | Unit testing is, roughly speaking, testing bits of your code in isolation with test code. The immediate advantages that come to mind are: Running the tests becomes automate-able and repeatable You can test at a much more granular level than point-and-click testing via a GUI Note that if your test code writes to a file, opens a database connection or does something over the network, it's more appropriately categorized as an integration test. Integration tests are a good thing, but should not be confused with unit tests. Unit test code should be short, sweet and quick to execute. Another way to look at unit testing is that you write the tests first. This is known as Test-Driven Development (TDD for short). TDD brings additional advantages: You don't write speculative "I might need this in the future" code -- just enough to make the tests pass The code you've written is always covered by tests By writing the test first, you're forced into thinking about how you want to call the code, which usually improves the design of the code in the long run. If you're not doing unit testing now, I recommend you get started on it. Get a good book, practically any xUnit-book will do because the concepts are very much transferable between them. Sometimes writing unit tests can be painful. When it gets that way, try to find someone to help you, and resist the temptation to "just write the damn code". Unit testing is a lot like washing the dishes. It's not always pleasant, but it keeps your metaphorical kitchen clean, and you really want it to be clean.:) Edit: One misconception comes to mind, although I'm not sure if it's so common. I've heard a project manager say that unit tests made the team write all the code twice. If it looks and feels that way, well, you're doing it wrong. Not only does writing the tests usually speed up development, but it also gives you a convenient "now I'm done" indicator that you wouldn't have otherwise. | What is unit testing? I saw many questions asking 'how' to unit test in a specific language, but no question asking 'what', 'why', and 'when'. What is it? What does it do for me? Why should I use it? When should I use it (also when not)? What are some common pitfalls and misconceptions | TITLE:
What is unit testing?
QUESTION:
I saw many questions asking 'how' to unit test in a specific language, but no question asking 'what', 'why', and 'when'. What is it? What does it do for me? Why should I use it? When should I use it (also when not)? What are some common pitfalls and misconceptions
ANSWER:
Unit testing is, roughly speaking, testing bits of your code in isolation with test code. The immediate advantages that come to mind are: Running the tests becomes automate-able and repeatable You can test at a much more granular level than point-and-click testing via a GUI Note that if your test code writes to a file, opens a database connection or does something over the network, it's more appropriately categorized as an integration test. Integration tests are a good thing, but should not be confused with unit tests. Unit test code should be short, sweet and quick to execute. Another way to look at unit testing is that you write the tests first. This is known as Test-Driven Development (TDD for short). TDD brings additional advantages: You don't write speculative "I might need this in the future" code -- just enough to make the tests pass The code you've written is always covered by tests By writing the test first, you're forced into thinking about how you want to call the code, which usually improves the design of the code in the long run. If you're not doing unit testing now, I recommend you get started on it. Get a good book, practically any xUnit-book will do because the concepts are very much transferable between them. Sometimes writing unit tests can be painful. When it gets that way, try to find someone to help you, and resist the temptation to "just write the damn code". Unit testing is a lot like washing the dishes. It's not always pleasant, but it keeps your metaphorical kitchen clean, and you really want it to be clean.:) Edit: One misconception comes to mind, although I'm not sure if it's so common. I've heard a project manager say that unit tests made the team write all the code twice. If it looks and feels that way, well, you're doing it wrong. Not only does writing the tests usually speed up development, but it also gives you a convenient "now I'm done" indicator that you wouldn't have otherwise. | [
"unit-testing"
] | 229 | 219 | 54,349 | 20 | 0 | 2008-08-04T16:27:39.787000 | 2008-08-04T16:36:51.750000 |
1,390 | 1,394 | Is Windows Server 2008 "Server Core" appropriate for a SQL Server instance? | I'm setting up a dedicated SQL Server 2005 box on Windows Server 2008 this week, and would like to pare it down to be as barebones as possible while still being fully functional. To that end, the "Server Core" option sounds appealing, but I'm not clear about whether or not I can run SQL Server on that SKU. Several services are addressed on the Microsoft website, but I don't see any indication about SQL Server. Does anyone know definitively? | Not sure how credible this source is, but: The Windows Server 2008 Core edition can: Run the file server role. Run the Hyper-V virtualization server role. Run the Directory Services role. Run the DHCP server role. Run the IIS Web server role. Run the DNS server role. Run Active Directory Lightweight Directory Services. Run the print server role. The Windows Server 2008 Core edition cannot: Run a SQL Server. Run an Exchange Server. Run Internet Explorer. Run Windows Explorer. Host a remote desktop session. Run MMC snap-in consoles locally. | Is Windows Server 2008 "Server Core" appropriate for a SQL Server instance? I'm setting up a dedicated SQL Server 2005 box on Windows Server 2008 this week, and would like to pare it down to be as barebones as possible while still being fully functional. To that end, the "Server Core" option sounds appealing, but I'm not clear about whether or not I can run SQL Server on that SKU. Several services are addressed on the Microsoft website, but I don't see any indication about SQL Server. Does anyone know definitively? | TITLE:
Is Windows Server 2008 "Server Core" appropriate for a SQL Server instance?
QUESTION:
I'm setting up a dedicated SQL Server 2005 box on Windows Server 2008 this week, and would like to pare it down to be as barebones as possible while still being fully functional. To that end, the "Server Core" option sounds appealing, but I'm not clear about whether or not I can run SQL Server on that SKU. Several services are addressed on the Microsoft website, but I don't see any indication about SQL Server. Does anyone know definitively?
ANSWER:
Not sure how credible this source is, but: The Windows Server 2008 Core edition can: Run the file server role. Run the Hyper-V virtualization server role. Run the Directory Services role. Run the DHCP server role. Run the IIS Web server role. Run the DNS server role. Run Active Directory Lightweight Directory Services. Run the print server role. The Windows Server 2008 Core edition cannot: Run a SQL Server. Run an Exchange Server. Run Internet Explorer. Run Windows Explorer. Host a remote desktop session. Run MMC snap-in consoles locally. | [
"sql-server",
"windows-server-2008"
] | 27 | 16 | 2,183 | 6 | 0 | 2008-08-04T16:33:36.390000 | 2008-08-04T16:38:03.667000 |
1,401 | 1,418 | ASP.Net Custom Client-Side Validation | I have a custom validation function in JavaScript in a user control on a.Net 2.0 web site which checks to see that the fee paid is not in excess of the fee amount due. I've placed the validator code in the ascx file, and I have also tried using Page.ClientScript.RegisterClientScriptBlock() and in both cases the validation fires, but cannot find the JavaScript function. The output in Firefox's error console is "feeAmountCheck is not defined". Here is the function (this was taken directly from firefox->view source) Any ideas as to why the function isn't being found? How can I remedy this without having to add the function to my master page or consuming page? | Try changing the argument names to sender and args. And, after you have it working, switch the call over to ScriptManager.RegisterClientScriptBlock, regardless of AJAX use. | ASP.Net Custom Client-Side Validation I have a custom validation function in JavaScript in a user control on a.Net 2.0 web site which checks to see that the fee paid is not in excess of the fee amount due. I've placed the validator code in the ascx file, and I have also tried using Page.ClientScript.RegisterClientScriptBlock() and in both cases the validation fires, but cannot find the JavaScript function. The output in Firefox's error console is "feeAmountCheck is not defined". Here is the function (this was taken directly from firefox->view source) Any ideas as to why the function isn't being found? How can I remedy this without having to add the function to my master page or consuming page? | TITLE:
ASP.Net Custom Client-Side Validation
QUESTION:
I have a custom validation function in JavaScript in a user control on a.Net 2.0 web site which checks to see that the fee paid is not in excess of the fee amount due. I've placed the validator code in the ascx file, and I have also tried using Page.ClientScript.RegisterClientScriptBlock() and in both cases the validation fires, but cannot find the JavaScript function. The output in Firefox's error console is "feeAmountCheck is not defined". Here is the function (this was taken directly from firefox->view source) Any ideas as to why the function isn't being found? How can I remedy this without having to add the function to my master page or consuming page?
ANSWER:
Try changing the argument names to sender and args. And, after you have it working, switch the call over to ScriptManager.RegisterClientScriptBlock, regardless of AJAX use. | [
"asp.net",
"javascript",
"validation"
] | 38 | 19 | 3,694 | 4 | 0 | 2008-08-04T16:44:25.167000 | 2008-08-04T17:02:56.237000 |
1,408 | 1,421 | Make XAMPP / Apache serve file outside of htdocs folder | Is it possible to configure xampp to serve up a file outside of the htdocs directory? For instance, say I have a file located as follows: C:\projects\transitCalculator\trunk\TransitCalculator.php and my xampp files are normally served out from: C:\xampp\htdocs\ (because that's the default configuration) Is there some way to make Apache recognize and serve up my TransitCalculator.php file without moving it under htdocs? Preferably I'd like Apache to serve up/have access to the entire contents of the projects directory, and I don't want to move the projects directory under htdocs. edit: edited to add Apache to the question title to make Q/A more "searchable" | Ok, per pix0r 's, Sparks ' and Dave 's answers it looks like there are three ways to do this: Virtual Hosts Open C:\xampp\apache\conf\extra\httpd-vhosts.conf. Un-comment ~line 19 ( NameVirtualHost *:80 ). Add your virtual host (~line 36): DocumentRoot C:\Projects\transitCalculator\trunk ServerName transitcalculator.localhost Order allow,deny Allow from all Open your hosts file (C:\Windows\System32\drivers\etc\hosts). Add 127.0.0.1 transitcalculator.localhost #transitCalculator to the end of the file (before the Spybot - Search & Destroy stuff if you have that installed). Save (You might have to save it to the desktop, change the permissions on the old hosts file (right click > properties), and copy the new one into the directory over the old one (or rename the old one) if you are using Vista and have trouble). Restart Apache. Now you can access that directory by browsing to http://transitcalculator.localhost/. Make an Alias Starting ~line 200 of your http.conf file, copy everything between and (~line 232) and paste it immediately below with C:/xampp/htdocs replaced with your desired directory (in this case C:/Projects ) to give your server the correct permissions for the new directory. Find the section (~line 300) and add Alias /transitCalculator "C:/Projects/transitCalculator/trunk" (or whatever is relevant to your desires) below the Alias comment block, inside the module tags. Change your document root Edit ~line 176 in C:\xampp\apache\conf\httpd.conf; change DocumentRoot "C:/xampp/htdocs" to #DocumentRoot "C:/Projects" (or whatever you want). Edit ~line 203 to match your new location (in this case C:/Projects ). Notes: You have to use forward slashes "/" instead of back slashes "\". Don't include the trailing "/" at the end. restart your server. | Make XAMPP / Apache serve file outside of htdocs folder Is it possible to configure xampp to serve up a file outside of the htdocs directory? For instance, say I have a file located as follows: C:\projects\transitCalculator\trunk\TransitCalculator.php and my xampp files are normally served out from: C:\xampp\htdocs\ (because that's the default configuration) Is there some way to make Apache recognize and serve up my TransitCalculator.php file without moving it under htdocs? Preferably I'd like Apache to serve up/have access to the entire contents of the projects directory, and I don't want to move the projects directory under htdocs. edit: edited to add Apache to the question title to make Q/A more "searchable" | TITLE:
Make XAMPP / Apache serve file outside of htdocs folder
QUESTION:
Is it possible to configure xampp to serve up a file outside of the htdocs directory? For instance, say I have a file located as follows: C:\projects\transitCalculator\trunk\TransitCalculator.php and my xampp files are normally served out from: C:\xampp\htdocs\ (because that's the default configuration) Is there some way to make Apache recognize and serve up my TransitCalculator.php file without moving it under htdocs? Preferably I'd like Apache to serve up/have access to the entire contents of the projects directory, and I don't want to move the projects directory under htdocs. edit: edited to add Apache to the question title to make Q/A more "searchable"
ANSWER:
Ok, per pix0r 's, Sparks ' and Dave 's answers it looks like there are three ways to do this: Virtual Hosts Open C:\xampp\apache\conf\extra\httpd-vhosts.conf. Un-comment ~line 19 ( NameVirtualHost *:80 ). Add your virtual host (~line 36): DocumentRoot C:\Projects\transitCalculator\trunk ServerName transitcalculator.localhost Order allow,deny Allow from all Open your hosts file (C:\Windows\System32\drivers\etc\hosts). Add 127.0.0.1 transitcalculator.localhost #transitCalculator to the end of the file (before the Spybot - Search & Destroy stuff if you have that installed). Save (You might have to save it to the desktop, change the permissions on the old hosts file (right click > properties), and copy the new one into the directory over the old one (or rename the old one) if you are using Vista and have trouble). Restart Apache. Now you can access that directory by browsing to http://transitcalculator.localhost/. Make an Alias Starting ~line 200 of your http.conf file, copy everything between and (~line 232) and paste it immediately below with C:/xampp/htdocs replaced with your desired directory (in this case C:/Projects ) to give your server the correct permissions for the new directory. Find the section (~line 300) and add Alias /transitCalculator "C:/Projects/transitCalculator/trunk" (or whatever is relevant to your desires) below the Alias comment block, inside the module tags. Change your document root Edit ~line 176 in C:\xampp\apache\conf\httpd.conf; change DocumentRoot "C:/xampp/htdocs" to #DocumentRoot "C:/Projects" (or whatever you want). Edit ~line 203 to match your new location (in this case C:/Projects ). Notes: You have to use forward slashes "/" instead of back slashes "\". Don't include the trailing "/" at the end. restart your server. | [
"php",
"apache",
"xampp",
"server-configuration"
] | 334 | 384 | 279,039 | 6 | 0 | 2008-08-04T16:54:49.293000 | 2008-08-04T17:05:48.680000 |
1,409 | 27,335 | Bandwith throttling in IIS 6 by IP Address | I am writing an application that downloads large files in the background. All clients are logged in locally, or through a VPN. When they are logged in locally, I do not want to throttle downloads. However, I would like to limit downloads to 10 KBps when the user is connected via VPN. I can differentiate between these users by IP Address range. Since this is an AIR Application, I figure I will throttle via server-side since I can do it from either the server itself (IIS 6) or the web service (asp.net / C#). Throttling through IIS 6 seems to work fine, but it seems like it has to be done across the entire web site. Is there anyway to do this via IP? Or will I have to rig this up in.NET? | My first thought is this. I don't know if it would work but it would only take a few minutes to try. Create two IIS web sites on the same server. The first site is bound to the public IP, but the second site is bound to the private IP. Both point to the same folder on the file system. Your VPN users will be accessing via the private IP, so you can setup a "site-wide" rule on that site that will only affect VPN users. This should work for almost any IIS6 setting, including bandwidth throttling. Worth a try, at least. -- Edit: Tried this and it worked flawlessly. | Bandwith throttling in IIS 6 by IP Address I am writing an application that downloads large files in the background. All clients are logged in locally, or through a VPN. When they are logged in locally, I do not want to throttle downloads. However, I would like to limit downloads to 10 KBps when the user is connected via VPN. I can differentiate between these users by IP Address range. Since this is an AIR Application, I figure I will throttle via server-side since I can do it from either the server itself (IIS 6) or the web service (asp.net / C#). Throttling through IIS 6 seems to work fine, but it seems like it has to be done across the entire web site. Is there anyway to do this via IP? Or will I have to rig this up in.NET? | TITLE:
Bandwith throttling in IIS 6 by IP Address
QUESTION:
I am writing an application that downloads large files in the background. All clients are logged in locally, or through a VPN. When they are logged in locally, I do not want to throttle downloads. However, I would like to limit downloads to 10 KBps when the user is connected via VPN. I can differentiate between these users by IP Address range. Since this is an AIR Application, I figure I will throttle via server-side since I can do it from either the server itself (IIS 6) or the web service (asp.net / C#). Throttling through IIS 6 seems to work fine, but it seems like it has to be done across the entire web site. Is there anyway to do this via IP? Or will I have to rig this up in.NET?
ANSWER:
My first thought is this. I don't know if it would work but it would only take a few minutes to try. Create two IIS web sites on the same server. The first site is bound to the public IP, but the second site is bound to the private IP. Both point to the same folder on the file system. Your VPN users will be accessing via the private IP, so you can setup a "site-wide" rule on that site that will only affect VPN users. This should work for almost any IIS6 setting, including bandwidth throttling. Worth a try, at least. -- Edit: Tried this and it worked flawlessly. | [
"asp.net",
"iis"
] | 20 | 12 | 2,268 | 1 | 0 | 2008-08-04T16:55:31.243000 | 2008-08-26T03:14:53.987000 |
1,417 | 1,425 | How can I get the authenticated user name under Apache using plain HTTP authentication and PHP? | First, let's get the security considerations out of the way. I'm using simple authentication under Apache for a one-off, internal use only, non-internet connected LAN, PHP web app. How can get I the HTTP authenticated user name in PHP? | I think that you are after this $username = $_SERVER['PHP_AUTH_USER']; $password = $_SERVER['PHP_AUTH_PW']; | How can I get the authenticated user name under Apache using plain HTTP authentication and PHP? First, let's get the security considerations out of the way. I'm using simple authentication under Apache for a one-off, internal use only, non-internet connected LAN, PHP web app. How can get I the HTTP authenticated user name in PHP? | TITLE:
How can I get the authenticated user name under Apache using plain HTTP authentication and PHP?
QUESTION:
First, let's get the security considerations out of the way. I'm using simple authentication under Apache for a one-off, internal use only, non-internet connected LAN, PHP web app. How can get I the HTTP authenticated user name in PHP?
ANSWER:
I think that you are after this $username = $_SERVER['PHP_AUTH_USER']; $password = $_SERVER['PHP_AUTH_PW']; | [
"php",
"apache",
"authentication",
"http-authentication"
] | 54 | 40 | 24,179 | 2 | 0 | 2008-08-04T17:02:31.790000 | 2008-08-04T17:08:26.037000 |
1,451 | 1,477 | What is the best way to handle multiple permission types? | I often encounter the following scenario where I need to offer many different types of permissions. I primarily use ASP.NET / VB.NET with SQL Server 2000. Scenario I want to offer a dynamic permission system that can work on different parameters. Let's say that I want to give either a department or just a specific person access to an application. And pretend that we have a number of applications that keeps growing. In the past, I have chosen one of the following two ways that I know to do this. Use a single permission table with special columns that are used for determining a how to apply the parameters. The special columns in this example are TypeID and TypeAuxID. The SQL would look something like this. SELECT COUNT(PermissionID) FROM application_permissions WHERE (TypeID = 1 AND TypeAuxID = @UserID) OR (TypeID = 2 AND TypeAuxID = @DepartmentID) AND ApplicationID = 1 Use a mapping table for each type of permission, then joining them all together. SELECT COUNT(perm.PermissionID) FROM application_permissions perm LEFT JOIN application_UserPermissions emp ON perm.ApplicationID = emp.ApplicationID LEFT JOIN application_DepartmentPermissions dept ON perm.ApplicationID = dept.ApplicationID WHERE q.SectionID=@SectionID AND (emp.UserID=@UserID OR dept.DeptID=@DeptID OR (emp.UserID IS NULL AND dept.DeptID IS NULL)) AND ApplicationID = 1 ORDER BY q.QID ASC My Thoughts I hope that the examples make sense. I cobbled them together. The first example requires less work, but neither of them feel like the best answer. Is there a better way to handle this? | I agree with John Downey. Personally, I sometimes use a flagged enumeration of permissions. This way you can use AND, OR, NOT and XOR bitwise operations on the enumeration's items. "[Flags] public enum Permission { VIEWUSERS = 1, // 2^0 // 0000 0001 EDITUSERS = 2, // 2^1 // 0000 0010 VIEWPRODUCTS = 4, // 2^2 // 0000 0100 EDITPRODUCTS = 8, // 2^3 // 0000 1000 VIEWCLIENTS = 16, // 2^4 // 0001 0000 EDITCLIENTS = 32, // 2^5 // 0010 0000 DELETECLIENTS = 64, // 2^6 // 0100 0000 }" Then, you can combine several permissions using the AND bitwise operator. For example, if a user can view & edit users, the binary result of the operation is 0000 0011 which converted to decimal is 3. You can then store the permission of one user into a single column of your Database (in our case it would be 3). Inside your application, you just need another bitwise operation (OR) to verify if a user has a particular permission or not. | What is the best way to handle multiple permission types? I often encounter the following scenario where I need to offer many different types of permissions. I primarily use ASP.NET / VB.NET with SQL Server 2000. Scenario I want to offer a dynamic permission system that can work on different parameters. Let's say that I want to give either a department or just a specific person access to an application. And pretend that we have a number of applications that keeps growing. In the past, I have chosen one of the following two ways that I know to do this. Use a single permission table with special columns that are used for determining a how to apply the parameters. The special columns in this example are TypeID and TypeAuxID. The SQL would look something like this. SELECT COUNT(PermissionID) FROM application_permissions WHERE (TypeID = 1 AND TypeAuxID = @UserID) OR (TypeID = 2 AND TypeAuxID = @DepartmentID) AND ApplicationID = 1 Use a mapping table for each type of permission, then joining them all together. SELECT COUNT(perm.PermissionID) FROM application_permissions perm LEFT JOIN application_UserPermissions emp ON perm.ApplicationID = emp.ApplicationID LEFT JOIN application_DepartmentPermissions dept ON perm.ApplicationID = dept.ApplicationID WHERE q.SectionID=@SectionID AND (emp.UserID=@UserID OR dept.DeptID=@DeptID OR (emp.UserID IS NULL AND dept.DeptID IS NULL)) AND ApplicationID = 1 ORDER BY q.QID ASC My Thoughts I hope that the examples make sense. I cobbled them together. The first example requires less work, but neither of them feel like the best answer. Is there a better way to handle this? | TITLE:
What is the best way to handle multiple permission types?
QUESTION:
I often encounter the following scenario where I need to offer many different types of permissions. I primarily use ASP.NET / VB.NET with SQL Server 2000. Scenario I want to offer a dynamic permission system that can work on different parameters. Let's say that I want to give either a department or just a specific person access to an application. And pretend that we have a number of applications that keeps growing. In the past, I have chosen one of the following two ways that I know to do this. Use a single permission table with special columns that are used for determining a how to apply the parameters. The special columns in this example are TypeID and TypeAuxID. The SQL would look something like this. SELECT COUNT(PermissionID) FROM application_permissions WHERE (TypeID = 1 AND TypeAuxID = @UserID) OR (TypeID = 2 AND TypeAuxID = @DepartmentID) AND ApplicationID = 1 Use a mapping table for each type of permission, then joining them all together. SELECT COUNT(perm.PermissionID) FROM application_permissions perm LEFT JOIN application_UserPermissions emp ON perm.ApplicationID = emp.ApplicationID LEFT JOIN application_DepartmentPermissions dept ON perm.ApplicationID = dept.ApplicationID WHERE q.SectionID=@SectionID AND (emp.UserID=@UserID OR dept.DeptID=@DeptID OR (emp.UserID IS NULL AND dept.DeptID IS NULL)) AND ApplicationID = 1 ORDER BY q.QID ASC My Thoughts I hope that the examples make sense. I cobbled them together. The first example requires less work, but neither of them feel like the best answer. Is there a better way to handle this?
ANSWER:
I agree with John Downey. Personally, I sometimes use a flagged enumeration of permissions. This way you can use AND, OR, NOT and XOR bitwise operations on the enumeration's items. "[Flags] public enum Permission { VIEWUSERS = 1, // 2^0 // 0000 0001 EDITUSERS = 2, // 2^1 // 0000 0010 VIEWPRODUCTS = 4, // 2^2 // 0000 0100 EDITPRODUCTS = 8, // 2^3 // 0000 1000 VIEWCLIENTS = 16, // 2^4 // 0001 0000 EDITCLIENTS = 32, // 2^5 // 0010 0000 DELETECLIENTS = 64, // 2^6 // 0100 0000 }" Then, you can combine several permissions using the AND bitwise operator. For example, if a user can view & edit users, the binary result of the operation is 0000 0011 which converted to decimal is 3. You can then store the permission of one user into a single column of your Database (in our case it would be 3). Inside your application, you just need another bitwise operation (OR) to verify if a user has a particular permission or not. | [
"sql",
"permissions"
] | 25 | 14 | 4,506 | 5 | 0 | 2008-08-04T17:46:28.207000 | 2008-08-04T18:23:40.537000 |
1,453 | 1,456 | Using object property as default for method property | I'm trying to do this (which produces an unexpected T_VARIABLE error): public function createShipment($startZip, $endZip, $weight = $this->getDefaultWeight()){} I don't want to put a magic number in there for weight since the object I am using has a "defaultWeight" parameter that all new shipments get if you don't specify a weight. I can't put the defaultWeight in the shipment itself, because it changes from shipment group to shipment group. Is there a better way to do it than the following? public function createShipment($startZip, $endZip, weight = 0){ if($weight <= 0){ $weight = $this->getDefaultWeight(); } } | This isn't much better: public function createShipment($startZip, $endZip, $weight=null){ $weight =!$weight? $this->getDefaultWeight(): $weight; }
// or...
public function createShipment($startZip, $endZip, $weight=null){ if (!$weight ) $weight = $this->getDefaultWeight(); } | Using object property as default for method property I'm trying to do this (which produces an unexpected T_VARIABLE error): public function createShipment($startZip, $endZip, $weight = $this->getDefaultWeight()){} I don't want to put a magic number in there for weight since the object I am using has a "defaultWeight" parameter that all new shipments get if you don't specify a weight. I can't put the defaultWeight in the shipment itself, because it changes from shipment group to shipment group. Is there a better way to do it than the following? public function createShipment($startZip, $endZip, weight = 0){ if($weight <= 0){ $weight = $this->getDefaultWeight(); } } | TITLE:
Using object property as default for method property
QUESTION:
I'm trying to do this (which produces an unexpected T_VARIABLE error): public function createShipment($startZip, $endZip, $weight = $this->getDefaultWeight()){} I don't want to put a magic number in there for weight since the object I am using has a "defaultWeight" parameter that all new shipments get if you don't specify a weight. I can't put the defaultWeight in the shipment itself, because it changes from shipment group to shipment group. Is there a better way to do it than the following? public function createShipment($startZip, $endZip, weight = 0){ if($weight <= 0){ $weight = $this->getDefaultWeight(); } }
ANSWER:
This isn't much better: public function createShipment($startZip, $endZip, $weight=null){ $weight =!$weight? $this->getDefaultWeight(): $weight; }
// or...
public function createShipment($startZip, $endZip, $weight=null){ if (!$weight ) $weight = $this->getDefaultWeight(); } | [
"php",
"parameters",
"error-handling"
] | 28 | 15 | 2,027 | 5 | 0 | 2008-08-04T17:51:13.003000 | 2008-08-04T17:53:00.410000 |
1,457 | 1,468 | Modify Address Bar URL in AJAX App to Match Current State | I'm writing an AJAX app, but as the user moves through the app, I'd like the URL in the address bar to update despite the lack of page reloads. Basically, I'd like for them to be able to bookmark at any point and thereby return to the current state. How are people handling maintaining RESTfulness in AJAX apps? | The way to do this is to manipulate location.hash when AJAX updates result in a state change that you'd like to have a discrete URL. For example, if your page's url is: http://example.com/ If a client side function executed this code: // AJAX code to display the "foo" state goes here.
location.hash = 'foo'; Then, the URL displayed in the browser would be updated to: http://example.com/#foo This allows users to bookmark the "foo" state of the page, and use the browser history to navigate between states. With this mechanism in place, you'll then need to parse out the hash portion of the URL on the client side using JavaScript to create and display the appropriate initial state, as fragment identifiers (the part after the #) are not sent to the server. Ben Alman's hashchange plugin makes the latter a breeze if you're using jQuery. | Modify Address Bar URL in AJAX App to Match Current State I'm writing an AJAX app, but as the user moves through the app, I'd like the URL in the address bar to update despite the lack of page reloads. Basically, I'd like for them to be able to bookmark at any point and thereby return to the current state. How are people handling maintaining RESTfulness in AJAX apps? | TITLE:
Modify Address Bar URL in AJAX App to Match Current State
QUESTION:
I'm writing an AJAX app, but as the user moves through the app, I'd like the URL in the address bar to update despite the lack of page reloads. Basically, I'd like for them to be able to bookmark at any point and thereby return to the current state. How are people handling maintaining RESTfulness in AJAX apps?
ANSWER:
The way to do this is to manipulate location.hash when AJAX updates result in a state change that you'd like to have a discrete URL. For example, if your page's url is: http://example.com/ If a client side function executed this code: // AJAX code to display the "foo" state goes here.
location.hash = 'foo'; Then, the URL displayed in the browser would be updated to: http://example.com/#foo This allows users to bookmark the "foo" state of the page, and use the browser history to navigate between states. With this mechanism in place, you'll then need to parse out the hash portion of the URL on the client side using JavaScript to create and display the appropriate initial state, as fragment identifiers (the part after the #) are not sent to the server. Ben Alman's hashchange plugin makes the latter a breeze if you're using jQuery. | [
"ajax",
"url",
"rest",
"address-bar"
] | 166 | 116 | 74,361 | 8 | 0 | 2008-08-04T17:53:32.500000 | 2008-08-04T18:04:48.547000 |
1,476 | 13,107 | How do you express binary literals in Python? | How do you express an integer as a binary number with Python literals? I was easily able to find the answer for hex: >>> 0x12AF 4783 >>> 0x100 256 and octal: >>> 01267 695 >>> 0100 64 How do you use literals to express binary in Python? Summary of Answers Python 2.5 and earlier: can express binary using int('01010101111',2) but not with a literal. Python 2.5 and earlier: there is no way to express binary literals. Python 2.6 beta: You can do like so: 0b1100111 or 0B1100111. Python 2.6 beta: will also allow 0o27 or 0O27 (second character is the letter O) to represent an octal. Python 3.0 beta: Same as 2.6, but will no longer allow the older 027 syntax for octals. | For reference— future Python possibilities: Starting with Python 2.6 you can express binary literals using the prefix 0b or 0B: >>> 0b101111 47 You can also use the new bin function to get the binary representation of a number: >>> bin(173) '0b10101101' Development version of the documentation: What's New in Python 2.6 | How do you express binary literals in Python? How do you express an integer as a binary number with Python literals? I was easily able to find the answer for hex: >>> 0x12AF 4783 >>> 0x100 256 and octal: >>> 01267 695 >>> 0100 64 How do you use literals to express binary in Python? Summary of Answers Python 2.5 and earlier: can express binary using int('01010101111',2) but not with a literal. Python 2.5 and earlier: there is no way to express binary literals. Python 2.6 beta: You can do like so: 0b1100111 or 0B1100111. Python 2.6 beta: will also allow 0o27 or 0O27 (second character is the letter O) to represent an octal. Python 3.0 beta: Same as 2.6, but will no longer allow the older 027 syntax for octals. | TITLE:
How do you express binary literals in Python?
QUESTION:
How do you express an integer as a binary number with Python literals? I was easily able to find the answer for hex: >>> 0x12AF 4783 >>> 0x100 256 and octal: >>> 01267 695 >>> 0100 64 How do you use literals to express binary in Python? Summary of Answers Python 2.5 and earlier: can express binary using int('01010101111',2) but not with a literal. Python 2.5 and earlier: there is no way to express binary literals. Python 2.6 beta: You can do like so: 0b1100111 or 0B1100111. Python 2.6 beta: will also allow 0o27 or 0O27 (second character is the letter O) to represent an octal. Python 3.0 beta: Same as 2.6, but will no longer allow the older 027 syntax for octals.
ANSWER:
For reference— future Python possibilities: Starting with Python 2.6 you can express binary literals using the prefix 0b or 0B: >>> 0b101111 47 You can also use the new bin function to get the binary representation of a number: >>> bin(173) '0b10101101' Development version of the documentation: What's New in Python 2.6 | [
"python",
"syntax",
"binary",
"integer",
"literals"
] | 407 | 358 | 340,928 | 8 | 0 | 2008-08-04T18:20:36.487000 | 2008-08-16T12:35:36.170000 |
1,496 | 1,517 | What are the preferred versions of Vim and Emacs on Mac OS X? | For those of us that like to use the graphical version of Vim or Emacs, instead of the console version, which version do you recommend? For Vim, there's Mac OS X Vim, MacVim, Vim-Cocoa. For Emacs, CarbonEmacs, XEmacs, and Aquamacs. Are there more? Which of these are ready for prime-time? If it's a tough call, what are the trade-offs? Are all of these still being maintained? No discussion of Vim versus Emacs, if you don't mind, or comparisons with other editors. | MacVim works well and certainly looks more mature than Vim-Cocoa, moreover there is a Cocoa plugin architecture in the pipeline for MacVim (and someone is already working on a TextMate style file browser tray plugin which is a huge ++ IMHO). There was also a Carbon version of Vim, but this didn't offer a great deal over the Terminal version. i.e. only allowed one window open, not very OSX in appearance... Aquamacs is very usable and looks pretty good. Supports both traditional Mac OS style keyboard shortcuts (command-O, command-S) and the Control/Meta shortcuts for those raised on traditional Emacs. It is definitely more Mac-like than Carbon Emacs. It seems stable and fast, but I am not an Emacs guru so I don't stress it all that much when I use it. I can't speak to the extensiveness of the included elisp packages, either. Someone syncs Carbon Emacs with the upstream tree quarterly I think. Aquamacs has a more irregular schedule, but it's seen some pretty major updates over the last year. GNU Emacs for OSX can be found at emacsformacosx.com. In addition to the latest stable release, there are also pre-release test builds and nightly builds, and Atom feeds are provided for tracking all three release types. | What are the preferred versions of Vim and Emacs on Mac OS X? For those of us that like to use the graphical version of Vim or Emacs, instead of the console version, which version do you recommend? For Vim, there's Mac OS X Vim, MacVim, Vim-Cocoa. For Emacs, CarbonEmacs, XEmacs, and Aquamacs. Are there more? Which of these are ready for prime-time? If it's a tough call, what are the trade-offs? Are all of these still being maintained? No discussion of Vim versus Emacs, if you don't mind, or comparisons with other editors. | TITLE:
What are the preferred versions of Vim and Emacs on Mac OS X?
QUESTION:
For those of us that like to use the graphical version of Vim or Emacs, instead of the console version, which version do you recommend? For Vim, there's Mac OS X Vim, MacVim, Vim-Cocoa. For Emacs, CarbonEmacs, XEmacs, and Aquamacs. Are there more? Which of these are ready for prime-time? If it's a tough call, what are the trade-offs? Are all of these still being maintained? No discussion of Vim versus Emacs, if you don't mind, or comparisons with other editors.
ANSWER:
MacVim works well and certainly looks more mature than Vim-Cocoa, moreover there is a Cocoa plugin architecture in the pipeline for MacVim (and someone is already working on a TextMate style file browser tray plugin which is a huge ++ IMHO). There was also a Carbon version of Vim, but this didn't offer a great deal over the Terminal version. i.e. only allowed one window open, not very OSX in appearance... Aquamacs is very usable and looks pretty good. Supports both traditional Mac OS style keyboard shortcuts (command-O, command-S) and the Control/Meta shortcuts for those raised on traditional Emacs. It is definitely more Mac-like than Carbon Emacs. It seems stable and fast, but I am not an Emacs guru so I don't stress it all that much when I use it. I can't speak to the extensiveness of the included elisp packages, either. Someone syncs Carbon Emacs with the upstream tree quarterly I think. Aquamacs has a more irregular schedule, but it's seen some pretty major updates over the last year. GNU Emacs for OSX can be found at emacsformacosx.com. In addition to the latest stable release, there are also pre-release test builds and nightly builds, and Atom feeds are provided for tracking all three release types. | [
"macos",
"vim",
"emacs",
"editor"
] | 35 | 21 | 9,888 | 13 | 0 | 2008-08-04T18:51:38.543000 | 2008-08-04T19:11:02.140000 |
1,503 | 1,514 | Integrating Visual Studio Test Project with Cruise Control | I'm looking into using Visual Studio 2008's built in unit test projects instead of NUnit and I was wondering if anyone has any experience in trying to integrate this type of unit test project with Cruise Control.Net. | From some of the initial research it doesn't appear to be a super simple solution. It appears that doing this involves having Visual Studio 2008 actually installed on the continuous integration server, which could be a deal breaker. Then configure the MSTest.exe to run in the tasks list, but first you'll have to make a batch file to delete the results files from previous passes as this file's existence causes an error. Then create a xslt to format the results and put it into the dashboard.config file. The code project article I found has a lot more detail. Integrating Visual Studio Team System 2008 Unit Tests with CruiseControl.NET | Integrating Visual Studio Test Project with Cruise Control I'm looking into using Visual Studio 2008's built in unit test projects instead of NUnit and I was wondering if anyone has any experience in trying to integrate this type of unit test project with Cruise Control.Net. | TITLE:
Integrating Visual Studio Test Project with Cruise Control
QUESTION:
I'm looking into using Visual Studio 2008's built in unit test projects instead of NUnit and I was wondering if anyone has any experience in trying to integrate this type of unit test project with Cruise Control.Net.
ANSWER:
From some of the initial research it doesn't appear to be a super simple solution. It appears that doing this involves having Visual Studio 2008 actually installed on the continuous integration server, which could be a deal breaker. Then configure the MSTest.exe to run in the tasks list, but first you'll have to make a batch file to delete the results files from previous passes as this file's existence causes an error. Then create a xslt to format the results and put it into the dashboard.config file. The code project article I found has a lot more detail. Integrating Visual Studio Team System 2008 Unit Tests with CruiseControl.NET | [
"visual-studio",
"unit-testing",
"continuous-integration",
"cruisecontrol.net"
] | 20 | 10 | 4,348 | 1 | 0 | 2008-08-04T19:01:14.157000 | 2008-08-04T19:09:44.717000 |
1,508 | 1,525 | Different Distributed Version Control Systems working together | My office has a central Source Safe 2005 install that we use for source control. I can't change what the office uses on the server. I develop on a laptop and would like to have a different local source control repository that can sync with the central server (when available) regardless of the what that central provider is. The reason for the request is so I can maintain a local stable branch/build for client presentations while continuing to develop without having to jump through flaming hoops. Also, as a consultant, my clients may request that I use their source control provider and flexibility here would make life easier. Can any of the existing distributed source control clients handle that? | Well... KernelTrap has something on this. Looks like you can use vss2svn to pipe the Source Safe repo into a Subversion repository, then use the very nice git-svn to pull into a local git repo. I would assume the commits back to VSS would not be a smooth, automatic process using this method. | Different Distributed Version Control Systems working together My office has a central Source Safe 2005 install that we use for source control. I can't change what the office uses on the server. I develop on a laptop and would like to have a different local source control repository that can sync with the central server (when available) regardless of the what that central provider is. The reason for the request is so I can maintain a local stable branch/build for client presentations while continuing to develop without having to jump through flaming hoops. Also, as a consultant, my clients may request that I use their source control provider and flexibility here would make life easier. Can any of the existing distributed source control clients handle that? | TITLE:
Different Distributed Version Control Systems working together
QUESTION:
My office has a central Source Safe 2005 install that we use for source control. I can't change what the office uses on the server. I develop on a laptop and would like to have a different local source control repository that can sync with the central server (when available) regardless of the what that central provider is. The reason for the request is so I can maintain a local stable branch/build for client presentations while continuing to develop without having to jump through flaming hoops. Also, as a consultant, my clients may request that I use their source control provider and flexibility here would make life easier. Can any of the existing distributed source control clients handle that?
ANSWER:
Well... KernelTrap has something on this. Looks like you can use vss2svn to pipe the Source Safe repo into a Subversion repository, then use the very nice git-svn to pull into a local git repo. I would assume the commits back to VSS would not be a smooth, automatic process using this method. | [
"version-control",
"dvcs"
] | 18 | 2 | 733 | 4 | 0 | 2008-08-04T19:04:47.347000 | 2008-08-04T19:13:23.197000 |
1,528 | 1,556 | Hiding inherited members | I'm looking for some way to effectively hide inherited members. I have a library of classes which inherit from common base classes. Some of the more recent descendant classes inherit dependency properties which have become vestigial and can be a little confusing when using IntelliSense or using the classes in a visual designer. These classes are all controls that are written to be compiled for either WPF or Silverlight 2.0. I know about ICustomTypeDescriptor and ICustomPropertyProvider, but I'm pretty certain those can't be used in Silverlight. It's not as much a functional issue as a usability issue. What should I do? Update Some of the properties that I would really like to hide come from ancestors that are not my own and because of a specific tool I'm designing for, I can't do member hiding with the new operator. (I know, it's ridiculous) | Override them like Michael Suggests above and to prevent folks from using the overridden (sp?) methods, mark them as obsolete: [Obsolete("These are not supported in this class.", true)] public override void dontcallmeanymore() { } If the second parm is set to true, a compiler error will be generated if anyone tries to call that method and the string in the first parm is the message. If parm2 is false only a compiler warning will be generated. | Hiding inherited members I'm looking for some way to effectively hide inherited members. I have a library of classes which inherit from common base classes. Some of the more recent descendant classes inherit dependency properties which have become vestigial and can be a little confusing when using IntelliSense or using the classes in a visual designer. These classes are all controls that are written to be compiled for either WPF or Silverlight 2.0. I know about ICustomTypeDescriptor and ICustomPropertyProvider, but I'm pretty certain those can't be used in Silverlight. It's not as much a functional issue as a usability issue. What should I do? Update Some of the properties that I would really like to hide come from ancestors that are not my own and because of a specific tool I'm designing for, I can't do member hiding with the new operator. (I know, it's ridiculous) | TITLE:
Hiding inherited members
QUESTION:
I'm looking for some way to effectively hide inherited members. I have a library of classes which inherit from common base classes. Some of the more recent descendant classes inherit dependency properties which have become vestigial and can be a little confusing when using IntelliSense or using the classes in a visual designer. These classes are all controls that are written to be compiled for either WPF or Silverlight 2.0. I know about ICustomTypeDescriptor and ICustomPropertyProvider, but I'm pretty certain those can't be used in Silverlight. It's not as much a functional issue as a usability issue. What should I do? Update Some of the properties that I would really like to hide come from ancestors that are not my own and because of a specific tool I'm designing for, I can't do member hiding with the new operator. (I know, it's ridiculous)
ANSWER:
Override them like Michael Suggests above and to prevent folks from using the overridden (sp?) methods, mark them as obsolete: [Obsolete("These are not supported in this class.", true)] public override void dontcallmeanymore() { } If the second parm is set to true, a compiler error will be generated if anyone tries to call that method and the string in the first parm is the message. If parm2 is false only a compiler warning will be generated. | [
"c#",
"wpf",
"silverlight",
"polymorphism",
"dependency-properties"
] | 51 | 39 | 34,163 | 9 | 0 | 2008-08-04T19:13:54.693000 | 2008-08-04T20:14:30.547000 |
1,535 | 2,047 | Reducing duplicate error handling code in C#? | I've never been completely happy with the way exception handling works, there's a lot exceptions and try/catch brings to the table (stack unwinding, etc.), but it seems to break a lot of the OO model in the process. Anyway, here's the problem: Let's say you have some class which wraps or includes networked file IO operations (e.g. reading and writing to some file at some particular UNC path somewhere). For various reasons you don't want those IO operations to fail, so if you detect that they fail you retry them and you keep retrying them until they succeed or you reach a timeout. I already have a convenient RetryTimer class which I can instantiate and use to sleep the current thread between retries and determine when the timeout period has elapsed, etc. The problem is that you have a bunch of IO operations in several methods of this class, and you need to wrap each of them in try-catch / retry logic. Here's an example code snippet: RetryTimer fileIORetryTimer = new RetryTimer(TimeSpan.FromHours(10)); bool success = false; while (!success) { try { // do some file IO which may succeed or fail success = true; } catch (IOException e) { if (fileIORetryTimer.HasExceededRetryTimeout) { throw e; } fileIORetryTimer.SleepUntilNextRetry(); } } So, how do you avoid duplicating most of this code for every file IO operation throughout the class? My solution was to use anonymous delegate blocks and a single method in the class which executed the delegate block passed to it. This allowed me to do things like this in other methods: this.RetryFileIO( delegate() { // some code block } ); I like this somewhat, but it leaves a lot to be desired. I'd like to hear how other people would solve this sort of problem. | This looks like an excellent opportunity to have a look at Aspect Oriented Programming. Here is a good article on AOP in.NET. The general idea is that you'd extract the cross-functional concern (i.e. Retry for x hours) into a separate class and then you'd annotate any methods that need to modify their behaviour in that way. Here's how it might look (with a nice extension method on Int32) [RetryFor( 10.Hours() )] public void DeleteArchive() { //.. code to just delete the archive } | Reducing duplicate error handling code in C#? I've never been completely happy with the way exception handling works, there's a lot exceptions and try/catch brings to the table (stack unwinding, etc.), but it seems to break a lot of the OO model in the process. Anyway, here's the problem: Let's say you have some class which wraps or includes networked file IO operations (e.g. reading and writing to some file at some particular UNC path somewhere). For various reasons you don't want those IO operations to fail, so if you detect that they fail you retry them and you keep retrying them until they succeed or you reach a timeout. I already have a convenient RetryTimer class which I can instantiate and use to sleep the current thread between retries and determine when the timeout period has elapsed, etc. The problem is that you have a bunch of IO operations in several methods of this class, and you need to wrap each of them in try-catch / retry logic. Here's an example code snippet: RetryTimer fileIORetryTimer = new RetryTimer(TimeSpan.FromHours(10)); bool success = false; while (!success) { try { // do some file IO which may succeed or fail success = true; } catch (IOException e) { if (fileIORetryTimer.HasExceededRetryTimeout) { throw e; } fileIORetryTimer.SleepUntilNextRetry(); } } So, how do you avoid duplicating most of this code for every file IO operation throughout the class? My solution was to use anonymous delegate blocks and a single method in the class which executed the delegate block passed to it. This allowed me to do things like this in other methods: this.RetryFileIO( delegate() { // some code block } ); I like this somewhat, but it leaves a lot to be desired. I'd like to hear how other people would solve this sort of problem. | TITLE:
Reducing duplicate error handling code in C#?
QUESTION:
I've never been completely happy with the way exception handling works, there's a lot exceptions and try/catch brings to the table (stack unwinding, etc.), but it seems to break a lot of the OO model in the process. Anyway, here's the problem: Let's say you have some class which wraps or includes networked file IO operations (e.g. reading and writing to some file at some particular UNC path somewhere). For various reasons you don't want those IO operations to fail, so if you detect that they fail you retry them and you keep retrying them until they succeed or you reach a timeout. I already have a convenient RetryTimer class which I can instantiate and use to sleep the current thread between retries and determine when the timeout period has elapsed, etc. The problem is that you have a bunch of IO operations in several methods of this class, and you need to wrap each of them in try-catch / retry logic. Here's an example code snippet: RetryTimer fileIORetryTimer = new RetryTimer(TimeSpan.FromHours(10)); bool success = false; while (!success) { try { // do some file IO which may succeed or fail success = true; } catch (IOException e) { if (fileIORetryTimer.HasExceededRetryTimeout) { throw e; } fileIORetryTimer.SleepUntilNextRetry(); } } So, how do you avoid duplicating most of this code for every file IO operation throughout the class? My solution was to use anonymous delegate blocks and a single method in the class which executed the delegate block passed to it. This allowed me to do things like this in other methods: this.RetryFileIO( delegate() { // some code block } ); I like this somewhat, but it leaves a lot to be desired. I'd like to hear how other people would solve this sort of problem.
ANSWER:
This looks like an excellent opportunity to have a look at Aspect Oriented Programming. Here is a good article on AOP in.NET. The general idea is that you'd extract the cross-functional concern (i.e. Retry for x hours) into a separate class and then you'd annotate any methods that need to modify their behaviour in that way. Here's how it might look (with a nice extension method on Int32) [RetryFor( 10.Hours() )] public void DeleteArchive() { //.. code to just delete the archive } | [
"c#",
"exception",
"error-handling"
] | 40 | 14 | 2,780 | 4 | 0 | 2008-08-04T19:21:48.530000 | 2008-08-05T09:43:55 |
1,584 | 44,389 | Linux shell equivalent on IIS | As a LAMP developer considering moving to a.Net IIS platform, one of my concerns is the loss of productivity due to lack of shell... Has anyone else had this experience? Is there possibly a Linux shell equivalent for Windows? | Depending on what version of IIS you're considering, I would second lbrandy's recommendation to check out PowerShell. Microsoft is working on a PowerShell provider for IIS (specifically version 7). There is a decent post about this at http://blogs.iis.net/thomad/archive/2008/04/14/iis-7-0-powershell-provider-tech-preview-1.aspx. The upcoming version of PowerShell will also add remoting capabilities so that you can remotely manage machines. PowerShell is quite different from *NIX shells, though, so that is something to consider. Hope this helps. | Linux shell equivalent on IIS As a LAMP developer considering moving to a.Net IIS platform, one of my concerns is the loss of productivity due to lack of shell... Has anyone else had this experience? Is there possibly a Linux shell equivalent for Windows? | TITLE:
Linux shell equivalent on IIS
QUESTION:
As a LAMP developer considering moving to a.Net IIS platform, one of my concerns is the loss of productivity due to lack of shell... Has anyone else had this experience? Is there possibly a Linux shell equivalent for Windows?
ANSWER:
Depending on what version of IIS you're considering, I would second lbrandy's recommendation to check out PowerShell. Microsoft is working on a PowerShell provider for IIS (specifically version 7). There is a decent post about this at http://blogs.iis.net/thomad/archive/2008/04/14/iis-7-0-powershell-provider-tech-preview-1.aspx. The upcoming version of PowerShell will also add remoting capabilities so that you can remotely manage machines. PowerShell is quite different from *NIX shells, though, so that is something to consider. Hope this helps. | [
"windows",
"iis",
"shell",
"command-line",
"terminal"
] | 21 | 7 | 3,502 | 8 | 0 | 2008-08-04T21:04:06.407000 | 2008-09-04T18:22:38.787000 |
1,598 | 3,490,980 | What are the correct pixel dimensions for an apple-touch-icon? | I'm not sure what the correct size should be. Many sites seem to repeat that the apple-touch-icon should be 57x57 pixels but cite a broken link as their source. Hanselman 's and playgroundblues 's comments suggest different sizes including 163x163 and 60x60. Apple's own apple.com icon is 129x129! See my related question: How do I give my web sites an icon for iPhone? | It seems that Apple guidelines as of August 3, 2010 now include the "High resolution" images (for iPhone 4) in their "required" icon sizes. Looks like we need to provide both a 57x57 and a 114x114 image now, as well as a 640x960 title image. See Custom Icon and Image Creation Guidelines (Javascript required) which is part of a whole document: iOS Human Interface Guidelines (2013; by Apple Inc; PDF; 26,3 MB) | What are the correct pixel dimensions for an apple-touch-icon? I'm not sure what the correct size should be. Many sites seem to repeat that the apple-touch-icon should be 57x57 pixels but cite a broken link as their source. Hanselman 's and playgroundblues 's comments suggest different sizes including 163x163 and 60x60. Apple's own apple.com icon is 129x129! See my related question: How do I give my web sites an icon for iPhone? | TITLE:
What are the correct pixel dimensions for an apple-touch-icon?
QUESTION:
I'm not sure what the correct size should be. Many sites seem to repeat that the apple-touch-icon should be 57x57 pixels but cite a broken link as their source. Hanselman 's and playgroundblues 's comments suggest different sizes including 163x163 and 60x60. Apple's own apple.com icon is 129x129! See my related question: How do I give my web sites an icon for iPhone?
ANSWER:
It seems that Apple guidelines as of August 3, 2010 now include the "High resolution" images (for iPhone 4) in their "required" icon sizes. Looks like we need to provide both a 57x57 and a 114x114 image now, as well as a 640x960 title image. See Custom Icon and Image Creation Guidelines (Javascript required) which is part of a whole document: iOS Human Interface Guidelines (2013; by Apple Inc; PDF; 26,3 MB) | [
"iphone",
"favicon",
"apple-touch-icon"
] | 73 | 40 | 52,507 | 7 | 0 | 2008-08-04T21:17:51.150000 | 2010-08-16T06:15:28.777000 |
1,600 | 1,793 | What is the best way to copy a database? | When I want to make a copy of a database, I always create a new empty database, and then restore a backup of the existing database into it. However, I'm wondering if this is really the least error-prone, least complicated, and most efficient way to do this? | Backup and Restore is the most straight-forward way I know. You have to be careful between servers as security credentials don't come with the restored database. | What is the best way to copy a database? When I want to make a copy of a database, I always create a new empty database, and then restore a backup of the existing database into it. However, I'm wondering if this is really the least error-prone, least complicated, and most efficient way to do this? | TITLE:
What is the best way to copy a database?
QUESTION:
When I want to make a copy of a database, I always create a new empty database, and then restore a backup of the existing database into it. However, I'm wondering if this is really the least error-prone, least complicated, and most efficient way to do this?
ANSWER:
Backup and Restore is the most straight-forward way I know. You have to be careful between servers as security credentials don't come with the restored database. | [
"sql-server",
"sql-server-2008"
] | 28 | 3 | 4,334 | 5 | 0 | 2008-08-04T21:27:53.003000 | 2008-08-05T01:31:16.583000 |
1,607 | 1,666 | Mechanisms for tracking DB schema changes | What are the best methods for tracking and/or automating DB schema changes? Our team uses Subversion for version control and we've been able to automate some of our tasks this way (pushing builds up to a staging server, deploying tested code to a production server) but we're still doing database updates manually. I would like to find or create a solution that allows us to work efficiently across servers with different environments while continuing to use Subversion as a backend through which code and DB updates are pushed around to various servers. Many popular software packages include auto-update scripts which detect DB version and apply the necessary changes. Is this the best way to do this even on a larger scale (across multiple projects and sometimes multiple environments and languages)? If so, is there any existing code out there that simplifies the process or is it best just to roll our own solution? Has anyone implemented something similar before and integrated it into Subversion post-commit hooks, or is this a bad idea? While a solution that supports multiple platforms would be preferable, we definitely need to support the Linux/Apache/MySQL/PHP stack as the majority of our work is on that platform. | In the Rails world, there's the concept of migrations, scripts in which changes to the database are made in Ruby rather than a database-specific flavour of SQL. Your Ruby migration code ends up being converted into the DDL specific to your current database; this makes switching database platforms very easy. For every change you make to the database, you write a new migration. Migrations typically have two methods: an "up" method in which the changes are applied and a "down" method in which the changes are undone. A single command brings the database up to date, and can also be used to bring the database to a specific version of the schema. In Rails, migrations are kept in their own directory in the project directory and get checked into version control just like any other project code. This Oracle guide to Rails migrations covers migrations quite well. Developers using other languages have looked at migrations and have implemented their own language-specific versions. I know of Ruckusing, a PHP migrations system that is modelled after Rails' migrations; it might be what you're looking for. | Mechanisms for tracking DB schema changes What are the best methods for tracking and/or automating DB schema changes? Our team uses Subversion for version control and we've been able to automate some of our tasks this way (pushing builds up to a staging server, deploying tested code to a production server) but we're still doing database updates manually. I would like to find or create a solution that allows us to work efficiently across servers with different environments while continuing to use Subversion as a backend through which code and DB updates are pushed around to various servers. Many popular software packages include auto-update scripts which detect DB version and apply the necessary changes. Is this the best way to do this even on a larger scale (across multiple projects and sometimes multiple environments and languages)? If so, is there any existing code out there that simplifies the process or is it best just to roll our own solution? Has anyone implemented something similar before and integrated it into Subversion post-commit hooks, or is this a bad idea? While a solution that supports multiple platforms would be preferable, we definitely need to support the Linux/Apache/MySQL/PHP stack as the majority of our work is on that platform. | TITLE:
Mechanisms for tracking DB schema changes
QUESTION:
What are the best methods for tracking and/or automating DB schema changes? Our team uses Subversion for version control and we've been able to automate some of our tasks this way (pushing builds up to a staging server, deploying tested code to a production server) but we're still doing database updates manually. I would like to find or create a solution that allows us to work efficiently across servers with different environments while continuing to use Subversion as a backend through which code and DB updates are pushed around to various servers. Many popular software packages include auto-update scripts which detect DB version and apply the necessary changes. Is this the best way to do this even on a larger scale (across multiple projects and sometimes multiple environments and languages)? If so, is there any existing code out there that simplifies the process or is it best just to roll our own solution? Has anyone implemented something similar before and integrated it into Subversion post-commit hooks, or is this a bad idea? While a solution that supports multiple platforms would be preferable, we definitely need to support the Linux/Apache/MySQL/PHP stack as the majority of our work is on that platform.
ANSWER:
In the Rails world, there's the concept of migrations, scripts in which changes to the database are made in Ruby rather than a database-specific flavour of SQL. Your Ruby migration code ends up being converted into the DDL specific to your current database; this makes switching database platforms very easy. For every change you make to the database, you write a new migration. Migrations typically have two methods: an "up" method in which the changes are applied and a "down" method in which the changes are undone. A single command brings the database up to date, and can also be used to bring the database to a specific version of the schema. In Rails, migrations are kept in their own directory in the project directory and get checked into version control just like any other project code. This Oracle guide to Rails migrations covers migrations quite well. Developers using other languages have looked at migrations and have implemented their own language-specific versions. I know of Ruckusing, a PHP migrations system that is modelled after Rails' migrations; it might be what you're looking for. | [
"php",
"mysql",
"database",
"svn",
"migration"
] | 139 | 57 | 44,917 | 20 | 0 | 2008-08-04T21:31:40.390000 | 2008-08-04T22:45:11.443000 |
1,610 | 1,621 | Can I logically reorder columns in a table? | If I'm adding a column to a table in Microsoft SQL Server, can I control where the column is displayed logically in queries? I don't want to mess with the physical layout of columns on disk, but I would like to logically group columns together when possible so that tools like SQL Server Management Studio list the contents of the table in a convenient way. I know that I can do this through SQL Management Studio by going into their "design" mode for tables and dragging the order of columns around, but I'd like to be able to do it in raw SQL so that I can perform the ordering scripted from the command line. | You can not do this programatically (in a safe way that is) without creating a new table. What Enterprise Manager does when you commit a reordering is to create a new table, move the data and then delete the old table and rename the new table to the existing name. If you want your columns in a particular order/grouping without altering their physical order, you can create a view which can be whatever you desire. | Can I logically reorder columns in a table? If I'm adding a column to a table in Microsoft SQL Server, can I control where the column is displayed logically in queries? I don't want to mess with the physical layout of columns on disk, but I would like to logically group columns together when possible so that tools like SQL Server Management Studio list the contents of the table in a convenient way. I know that I can do this through SQL Management Studio by going into their "design" mode for tables and dragging the order of columns around, but I'd like to be able to do it in raw SQL so that I can perform the ordering scripted from the command line. | TITLE:
Can I logically reorder columns in a table?
QUESTION:
If I'm adding a column to a table in Microsoft SQL Server, can I control where the column is displayed logically in queries? I don't want to mess with the physical layout of columns on disk, but I would like to logically group columns together when possible so that tools like SQL Server Management Studio list the contents of the table in a convenient way. I know that I can do this through SQL Management Studio by going into their "design" mode for tables and dragging the order of columns around, but I'd like to be able to do it in raw SQL so that I can perform the ordering scripted from the command line.
ANSWER:
You can not do this programatically (in a safe way that is) without creating a new table. What Enterprise Manager does when you commit a reordering is to create a new table, move the data and then delete the old table and rename the new table to the existing name. If you want your columns in a particular order/grouping without altering their physical order, you can create a view which can be whatever you desire. | [
"sql-server"
] | 105 | 85 | 93,027 | 9 | 0 | 2008-08-04T21:37:31.720000 | 2008-08-04T21:54:18.707000 |
1,615 | 1,628 | How can I modify .xfdl files? (Update #1) | The.XFDL file extension identifies XFDL Formatted Document files. These belong to the XML-based document and template formatting standard. This format is exactly like the XML file format however, contains a level of encryption for use in secure communications. I know how to view XFDL files using a file viewer I found here. I can also modify and save these files by doing File:Save/Save As. I'd like, however, to modify these files on the fly. Any suggestions? Is this even possible? Update #1: I have now successfully decoded and unziped a.xfdl into an XML file which I can then edit. Now, I am looking for a way to re-encode the modified XML file back into base64-gzip (using Ruby or the command line) | If the encoding is base64 then this is the solution I've stumbled upon on the web: "Decoding XDFL files saved with 'encoding=base64'. Files saved with: application/vnd.xfdl;content-encoding="base64-gzip" are simple base64-encoded gzip files. They can be easily restored to XML by first decoding and then unzipping them. This can be done as follows on Ubuntu: sudo apt-get install uudeview uudeview -i yourform.xfdl gunzip -S "" < UNKNOWN.001 > yourform-unpacked.xfdl The first command will install uudeview, a package that can decode base64, among others. You can skip this step once it is installed. Assuming your form is saved as 'yourform.xfdl', the uudeview command will decode the contents as 'UNKNOWN.001', since the xfdl file doesn't contain a file name. The '-i' option makes uudeview uninteractive, remove that option for more control. The last command gunzips the decoded file into a file named 'yourform-unpacked.xfdl'. Another possible solution - here Side Note: Block quoted < code > doesn't work for long strings of code | How can I modify .xfdl files? (Update #1) The.XFDL file extension identifies XFDL Formatted Document files. These belong to the XML-based document and template formatting standard. This format is exactly like the XML file format however, contains a level of encryption for use in secure communications. I know how to view XFDL files using a file viewer I found here. I can also modify and save these files by doing File:Save/Save As. I'd like, however, to modify these files on the fly. Any suggestions? Is this even possible? Update #1: I have now successfully decoded and unziped a.xfdl into an XML file which I can then edit. Now, I am looking for a way to re-encode the modified XML file back into base64-gzip (using Ruby or the command line) | TITLE:
How can I modify .xfdl files? (Update #1)
QUESTION:
The.XFDL file extension identifies XFDL Formatted Document files. These belong to the XML-based document and template formatting standard. This format is exactly like the XML file format however, contains a level of encryption for use in secure communications. I know how to view XFDL files using a file viewer I found here. I can also modify and save these files by doing File:Save/Save As. I'd like, however, to modify these files on the fly. Any suggestions? Is this even possible? Update #1: I have now successfully decoded and unziped a.xfdl into an XML file which I can then edit. Now, I am looking for a way to re-encode the modified XML file back into base64-gzip (using Ruby or the command line)
ANSWER:
If the encoding is base64 then this is the solution I've stumbled upon on the web: "Decoding XDFL files saved with 'encoding=base64'. Files saved with: application/vnd.xfdl;content-encoding="base64-gzip" are simple base64-encoded gzip files. They can be easily restored to XML by first decoding and then unzipping them. This can be done as follows on Ubuntu: sudo apt-get install uudeview uudeview -i yourform.xfdl gunzip -S "" < UNKNOWN.001 > yourform-unpacked.xfdl The first command will install uudeview, a package that can decode base64, among others. You can skip this step once it is installed. Assuming your form is saved as 'yourform.xfdl', the uudeview command will decode the contents as 'UNKNOWN.001', since the xfdl file doesn't contain a file name. The '-i' option makes uudeview uninteractive, remove that option for more control. The last command gunzips the decoded file into a file named 'yourform-unpacked.xfdl'. Another possible solution - here Side Note: Block quoted < code > doesn't work for long strings of code | [
"ruby",
"language-agnostic",
"xfdl"
] | 17 | 5 | 7,918 | 3 | 0 | 2008-08-04T21:42:37.933000 | 2008-08-04T22:02:35.180000 |
1,623 | 1,667 | Folders or Projects in a Visual Studio Solution? | When spliting a solution in to logical layers, when is it best to use a separate project over just grouping by a folder? | By default, always just create new folder within the same project You will get single assembly (without additional ILMerge gymnastic) Easier to obfuscate (because you will have less public types and methods, ideally none at all) Separating your source code into multiple projects makes only sense if you... Have some portions of the source code that are part of the project but not deployable by default or at all (unit tests, extra plugins etc.) More developers involved and you want to treat their work as consumable black box. (not very recommended) If you can clearly separate your project into isolated layers/modules and you want to make sure that they can't cross-consume internal members. (also not recommended because you will need to decide which aspect is the most important) If you think that some portions of your source code could be reusable, still don't create it as a new project. Just wait until you will really want to reuse it in another solution and isolate it out of original project as needed. Programming is not a lego, reusing is usually very difficult and often won't happen as planned. | Folders or Projects in a Visual Studio Solution? When spliting a solution in to logical layers, when is it best to use a separate project over just grouping by a folder? | TITLE:
Folders or Projects in a Visual Studio Solution?
QUESTION:
When spliting a solution in to logical layers, when is it best to use a separate project over just grouping by a folder?
ANSWER:
By default, always just create new folder within the same project You will get single assembly (without additional ILMerge gymnastic) Easier to obfuscate (because you will have less public types and methods, ideally none at all) Separating your source code into multiple projects makes only sense if you... Have some portions of the source code that are part of the project but not deployable by default or at all (unit tests, extra plugins etc.) More developers involved and you want to treat their work as consumable black box. (not very recommended) If you can clearly separate your project into isolated layers/modules and you want to make sure that they can't cross-consume internal members. (also not recommended because you will need to decide which aspect is the most important) If you think that some portions of your source code could be reusable, still don't create it as a new project. Just wait until you will really want to reuse it in another solution and isolate it out of original project as needed. Programming is not a lego, reusing is usually very difficult and often won't happen as planned. | [
"visual-studio",
"projects-and-solutions"
] | 31 | 18 | 5,361 | 7 | 0 | 2008-08-04T22:00:41.347000 | 2008-08-04T22:45:32.940000 |
1,625 | 1,627 | XML Editing/Viewing Software | What software is recommended for working with and editing large XML schemas? I'm looking for both Windows and Linux software (doesn't have to be cross platform, just want suggestions for both) that help with dealing with huge XML files. | I may be old fashioned, but I prefer my text editor. I use emacs, and it has a fairly decent xml mode. Most good text editors will have decent syntax hi-lighting and tag matching facilities. Your IDE might already do it (IntelliJ idea does, and I believe Eclipse does as well). Good text editors will be able to deal with huge files, but some text editors may not be able to handle them. How big are we talking about? | XML Editing/Viewing Software What software is recommended for working with and editing large XML schemas? I'm looking for both Windows and Linux software (doesn't have to be cross platform, just want suggestions for both) that help with dealing with huge XML files. | TITLE:
XML Editing/Viewing Software
QUESTION:
What software is recommended for working with and editing large XML schemas? I'm looking for both Windows and Linux software (doesn't have to be cross platform, just want suggestions for both) that help with dealing with huge XML files.
ANSWER:
I may be old fashioned, but I prefer my text editor. I use emacs, and it has a fairly decent xml mode. Most good text editors will have decent syntax hi-lighting and tag matching facilities. Your IDE might already do it (IntelliJ idea does, and I believe Eclipse does as well). Good text editors will be able to deal with huge files, but some text editors may not be able to handle them. How big are we talking about? | [
"windows",
"xml",
"linux"
] | 40 | 9 | 19,050 | 17 | 0 | 2008-08-04T22:01:10.317000 | 2008-08-04T22:01:59.580000 |
1,669 | 1,672 | Learning to write a compiler | Preferred languages: C/C++, Java, and Ruby. I am looking for some helpful books/tutorials on how to write your own compiler simply for educational purposes. I am most familiar with C/C++, Java, and Ruby, so I prefer resources that involve one of those three, but any good resource is acceptable. | Big List of Resources: A Nanopass Framework for Compiler Education ¶ Advanced Compiler Design and Implementation $ An Incremental Approach to Compiler Construction ¶ ANTLR 3.x Video Tutorial Basics of Compiler Design Building a Parrot Compiler Compiler Basics Compiler Construction $ Compiler Design and Construction $ Crafting a Compiler with C $ Crafting Interpreters [Compiler Design in C] 12 ¶ Compilers: Principles, Techniques, and Tools $ — aka "The Dragon Book"; widely considered "the book" for compiler writing. Engineering a Compiler $ Essentials of Programming Languages Flipcode Article Archive (look for "Implementing A Scripting Engine by Jan Niestadt") Game Scripting Mastery $ How to build a virtual machine from scratch in C# ¶ Implementing Functional Languages Implementing Programming Languages (with BNFC) Implementing Programming Languages using C# 4.0 Interpreter pattern (described in Design Patterns $) specifies a way to evaluate sentences in a language Language Implementation Patterns: Create Your Own Domain-Specific and General Programming Languages $ Let's Build a Compiler by Jack Crenshaw — The PDF ¶ version (examples are in Pascal, but the information is generally applicable) Linkers and Loaders $ (Google Books) Lisp in Small Pieces (LiSP) $ LLVM Tutorial Modern Compiler Implementation in ML $ — There is a Java $ and C $ version as well - widely considered a very good book Object-Oriented Compiler Construction $ Parsing Techniques - A Practical Guide Project Oberon ¶ - Look at chapter 13 Programming a Personal Computer $ Programing Languages: Application and Interpretation Rabbit: A Compiler for Scheme ¶ Reflections on Trusting Trust — A quick guide Roll Your Own Compiler for the.NET framework — A quick tutorial from MSDN Structure and Interpretation of Computer Programs Types and Programming Languages Want to Write a Compiler? - a quick guide Writing a Compiler in Ruby Bottom Up Compiling a Lisp — compile directly to x86-64 Legend: ¶ Link to a PDF file $ Link to a printed book | Learning to write a compiler Preferred languages: C/C++, Java, and Ruby. I am looking for some helpful books/tutorials on how to write your own compiler simply for educational purposes. I am most familiar with C/C++, Java, and Ruby, so I prefer resources that involve one of those three, but any good resource is acceptable. | TITLE:
Learning to write a compiler
QUESTION:
Preferred languages: C/C++, Java, and Ruby. I am looking for some helpful books/tutorials on how to write your own compiler simply for educational purposes. I am most familiar with C/C++, Java, and Ruby, so I prefer resources that involve one of those three, but any good resource is acceptable.
ANSWER:
Big List of Resources: A Nanopass Framework for Compiler Education ¶ Advanced Compiler Design and Implementation $ An Incremental Approach to Compiler Construction ¶ ANTLR 3.x Video Tutorial Basics of Compiler Design Building a Parrot Compiler Compiler Basics Compiler Construction $ Compiler Design and Construction $ Crafting a Compiler with C $ Crafting Interpreters [Compiler Design in C] 12 ¶ Compilers: Principles, Techniques, and Tools $ — aka "The Dragon Book"; widely considered "the book" for compiler writing. Engineering a Compiler $ Essentials of Programming Languages Flipcode Article Archive (look for "Implementing A Scripting Engine by Jan Niestadt") Game Scripting Mastery $ How to build a virtual machine from scratch in C# ¶ Implementing Functional Languages Implementing Programming Languages (with BNFC) Implementing Programming Languages using C# 4.0 Interpreter pattern (described in Design Patterns $) specifies a way to evaluate sentences in a language Language Implementation Patterns: Create Your Own Domain-Specific and General Programming Languages $ Let's Build a Compiler by Jack Crenshaw — The PDF ¶ version (examples are in Pascal, but the information is generally applicable) Linkers and Loaders $ (Google Books) Lisp in Small Pieces (LiSP) $ LLVM Tutorial Modern Compiler Implementation in ML $ — There is a Java $ and C $ version as well - widely considered a very good book Object-Oriented Compiler Construction $ Parsing Techniques - A Practical Guide Project Oberon ¶ - Look at chapter 13 Programming a Personal Computer $ Programing Languages: Application and Interpretation Rabbit: A Compiler for Scheme ¶ Reflections on Trusting Trust — A quick guide Roll Your Own Compiler for the.NET framework — A quick tutorial from MSDN Structure and Interpretation of Computer Programs Types and Programming Languages Want to Write a Compiler? - a quick guide Writing a Compiler in Ruby Bottom Up Compiling a Lisp — compile directly to x86-64 Legend: ¶ Link to a PDF file $ Link to a printed book | [
"compiler-construction",
"language-agnostic"
] | 697 | 1,196 | 361,322 | 38 | 0 | 2008-08-04T22:46:36.900000 | 2008-08-04T22:52:00.650000 |
1,679 | 1,704 | How do I calculate these statistics? | I'm writing an app to help facilitate some research, and part of this involves doing some statistical calculations. Right now, the researchers are using a program called SPSS. Part of the output that they care about looks like this: They're really only concerned about the F and Sig. values. My problem is that I have no background in statistics, and I can't figure out what the tests are called, or how to calculate them. I thought the F value might be the result of the F-test, but after following the steps given on Wikipedia, I got a result that was different from what SPSS gives. | This website might help you out a bit more. Also this one. I'm working from a fairly rusty memory of a statistics course, but here goes nothing: When you're doing analysis of variance (ANOVA), you actually calculate the F statistic as the ratio from the mean-square variances "between the groups" and the mean-square variances "within the groups". The second link above seems pretty good for this calculation. This makes the F statistic measure exactly how powerful your model is, because the "between the groups" variance is explanatory power, and "within the groups" variance is random error. High F implies a highly significant model. As in many statistical operations, you back-determine Sig. using the F statistic. Here's where your Wikipedia information comes in slightly handy. What you want to do is - using the degrees of freedom given to you by SPSS - find the proper P value at which an F table will give you the F statistic you calculated. The P value where this happens [F(table) = F(calculated)] is the significance. Conceptually, a lower significance value shows a very strong ability to reject the null hypothesis (which for these purposes means to determine your model has explanatory power). Sorry to any math folks if any of this is wrong. I'll be checking back to make edits!!! Good luck to you. Stats is fun, just maybe not this part. =) | How do I calculate these statistics? I'm writing an app to help facilitate some research, and part of this involves doing some statistical calculations. Right now, the researchers are using a program called SPSS. Part of the output that they care about looks like this: They're really only concerned about the F and Sig. values. My problem is that I have no background in statistics, and I can't figure out what the tests are called, or how to calculate them. I thought the F value might be the result of the F-test, but after following the steps given on Wikipedia, I got a result that was different from what SPSS gives. | TITLE:
How do I calculate these statistics?
QUESTION:
I'm writing an app to help facilitate some research, and part of this involves doing some statistical calculations. Right now, the researchers are using a program called SPSS. Part of the output that they care about looks like this: They're really only concerned about the F and Sig. values. My problem is that I have no background in statistics, and I can't figure out what the tests are called, or how to calculate them. I thought the F value might be the result of the F-test, but after following the steps given on Wikipedia, I got a result that was different from what SPSS gives.
ANSWER:
This website might help you out a bit more. Also this one. I'm working from a fairly rusty memory of a statistics course, but here goes nothing: When you're doing analysis of variance (ANOVA), you actually calculate the F statistic as the ratio from the mean-square variances "between the groups" and the mean-square variances "within the groups". The second link above seems pretty good for this calculation. This makes the F statistic measure exactly how powerful your model is, because the "between the groups" variance is explanatory power, and "within the groups" variance is random error. High F implies a highly significant model. As in many statistical operations, you back-determine Sig. using the F statistic. Here's where your Wikipedia information comes in slightly handy. What you want to do is - using the degrees of freedom given to you by SPSS - find the proper P value at which an F table will give you the F statistic you calculated. The P value where this happens [F(table) = F(calculated)] is the significance. Conceptually, a lower significance value shows a very strong ability to reject the null hypothesis (which for these purposes means to determine your model has explanatory power). Sorry to any math folks if any of this is wrong. I'll be checking back to make edits!!! Good luck to you. Stats is fun, just maybe not this part. =) | [
"statistics",
"spss"
] | 16 | 3 | 10,739 | 6 | 0 | 2008-08-04T22:56:45.540000 | 2008-08-04T23:32:54.797000 |
1,683 | 3,020 | ASP.NET built in user profile vs. old style user class/tables | I am looking for guidance regarding the best practice around the use of the Profile feature in ASP.NET. How do you decide what should be kept in the built-in user Profile, or if you should create your own database table and add a column for the desired fields? For example, a user has a zip code, should I save the zip code in my own table, or should I add it to the web.config xml profile and access it via the user profile ASP.NET mechanism? The pros/cons I can think of right now are that since I don't know the profile very well (it is a bit of a Matrix right now), I probably can do whatever I want if I go the table route (e.g., SQL to get all the users in the same zip code as the current user). I don't know if I can do the same if I use the ASP.NET profile. | Ive only built 2 applications that used the profile provider. Since then I have stayed away from using it. For both of the apps I used it to store information about the user such as their company name, address and phone number. This worked fine until our client wanted to be able to find a user by one of these fields. Searching involved looping through every users profile and comparing the information to the search criteria. As the user base grew the search time became unacceptable to our client. The only solution was to create a table to store the users information. Search speed was increased immensely. I would recommend storing this type of information in its own table. | ASP.NET built in user profile vs. old style user class/tables I am looking for guidance regarding the best practice around the use of the Profile feature in ASP.NET. How do you decide what should be kept in the built-in user Profile, or if you should create your own database table and add a column for the desired fields? For example, a user has a zip code, should I save the zip code in my own table, or should I add it to the web.config xml profile and access it via the user profile ASP.NET mechanism? The pros/cons I can think of right now are that since I don't know the profile very well (it is a bit of a Matrix right now), I probably can do whatever I want if I go the table route (e.g., SQL to get all the users in the same zip code as the current user). I don't know if I can do the same if I use the ASP.NET profile. | TITLE:
ASP.NET built in user profile vs. old style user class/tables
QUESTION:
I am looking for guidance regarding the best practice around the use of the Profile feature in ASP.NET. How do you decide what should be kept in the built-in user Profile, or if you should create your own database table and add a column for the desired fields? For example, a user has a zip code, should I save the zip code in my own table, or should I add it to the web.config xml profile and access it via the user profile ASP.NET mechanism? The pros/cons I can think of right now are that since I don't know the profile very well (it is a bit of a Matrix right now), I probably can do whatever I want if I go the table route (e.g., SQL to get all the users in the same zip code as the current user). I don't know if I can do the same if I use the ASP.NET profile.
ANSWER:
Ive only built 2 applications that used the profile provider. Since then I have stayed away from using it. For both of the apps I used it to store information about the user such as their company name, address and phone number. This worked fine until our client wanted to be able to find a user by one of these fields. Searching involved looping through every users profile and comparing the information to the search criteria. As the user base grew the search time became unacceptable to our client. The only solution was to create a table to store the users information. Search speed was increased immensely. I would recommend storing this type of information in its own table. | [
"asp.net",
"profile"
] | 24 | 11 | 3,568 | 5 | 0 | 2008-08-04T23:06:23.443000 | 2008-08-06T02:26:35.333000 |
1,709 | 1,724 | How to pass enumerated values to a web service | My dilemma is, basically, how to share an enumeration between two applications. The users upload documents through a front-end application that is on the web. This application calls a web service of the back-end application and passes the document to it. The back-end app saves the document and inserts a row in the Document table. The document type (7 possible document types: Invoice, Contract etc.) is passed as a parameter to the web service's UploadDocument method. The question is, what should the type (and possible values) of this parameter be? Since you need to hardcode these values in both applications, I think it is O.K. to use a descriptive string ( Invoice, Contract, WorkOrder, SignedWorkOrder ). Is it maybe a better approach to create a DocumentTypes enumeration in the first application, and to reproduce it also in the second application, and then pass the corresponding integer value to the web service between them? | I can only speak about.net, but if you have an ASP.net Webservice, you should be able to add an enumeration directly to it. When you then use the "Add Web Reference" in your Client Application, the resulting Class should include that enum But this is from the top of my head, i'm pretty sure i've done it in the past, but I can't say for sure. | How to pass enumerated values to a web service My dilemma is, basically, how to share an enumeration between two applications. The users upload documents through a front-end application that is on the web. This application calls a web service of the back-end application and passes the document to it. The back-end app saves the document and inserts a row in the Document table. The document type (7 possible document types: Invoice, Contract etc.) is passed as a parameter to the web service's UploadDocument method. The question is, what should the type (and possible values) of this parameter be? Since you need to hardcode these values in both applications, I think it is O.K. to use a descriptive string ( Invoice, Contract, WorkOrder, SignedWorkOrder ). Is it maybe a better approach to create a DocumentTypes enumeration in the first application, and to reproduce it also in the second application, and then pass the corresponding integer value to the web service between them? | TITLE:
How to pass enumerated values to a web service
QUESTION:
My dilemma is, basically, how to share an enumeration between two applications. The users upload documents through a front-end application that is on the web. This application calls a web service of the back-end application and passes the document to it. The back-end app saves the document and inserts a row in the Document table. The document type (7 possible document types: Invoice, Contract etc.) is passed as a parameter to the web service's UploadDocument method. The question is, what should the type (and possible values) of this parameter be? Since you need to hardcode these values in both applications, I think it is O.K. to use a descriptive string ( Invoice, Contract, WorkOrder, SignedWorkOrder ). Is it maybe a better approach to create a DocumentTypes enumeration in the first application, and to reproduce it also in the second application, and then pass the corresponding integer value to the web service between them?
ANSWER:
I can only speak about.net, but if you have an ASP.net Webservice, you should be able to add an enumeration directly to it. When you then use the "Add Web Reference" in your Client Application, the resulting Class should include that enum But this is from the top of my head, i'm pretty sure i've done it in the past, but I can't say for sure. | [
"web-services",
"application-integration"
] | 24 | 3 | 18,290 | 8 | 0 | 2008-08-04T23:43:34.757000 | 2008-08-04T23:56:54.403000 |
1,734 | 1,780 | Any experiences with Protocol Buffers? | I was just looking through some information about Google's protocol buffers data interchange format. Has anyone played around with the code or even created a project around it? I'm currently using XML in a Python project for structured content created by hand in a text editor, and I was wondering what the general opinion was on Protocol Buffers as a user-facing input format. The speed and brevity benefits definitely seem to be there, but there are so many factors when it comes to actually generating and processing the data. | If you are looking for user facing interaction, stick with xml. It has more support, understanding, and general acceptance currently. If it's internal, I would say that protocol buffers are a great idea. Maybe in a few years as more tools come out to support protocol buffers, then start looking towards that for a public facing api. Until then... JSON? | Any experiences with Protocol Buffers? I was just looking through some information about Google's protocol buffers data interchange format. Has anyone played around with the code or even created a project around it? I'm currently using XML in a Python project for structured content created by hand in a text editor, and I was wondering what the general opinion was on Protocol Buffers as a user-facing input format. The speed and brevity benefits definitely seem to be there, but there are so many factors when it comes to actually generating and processing the data. | TITLE:
Any experiences with Protocol Buffers?
QUESTION:
I was just looking through some information about Google's protocol buffers data interchange format. Has anyone played around with the code or even created a project around it? I'm currently using XML in a Python project for structured content created by hand in a text editor, and I was wondering what the general opinion was on Protocol Buffers as a user-facing input format. The speed and brevity benefits definitely seem to be there, but there are so many factors when it comes to actually generating and processing the data.
ANSWER:
If you are looking for user facing interaction, stick with xml. It has more support, understanding, and general acceptance currently. If it's internal, I would say that protocol buffers are a great idea. Maybe in a few years as more tools come out to support protocol buffers, then start looking towards that for a public facing api. Until then... JSON? | [
"python",
"xml",
"database",
"protocol-buffers"
] | 36 | 13 | 2,455 | 4 | 0 | 2008-08-05T00:12:55.290000 | 2008-08-05T01:14:30.423000 |
1,746 | 1,749 | How can I get at the matches when using preg_replace in PHP? | I am trying to grab the capital letters of a couple of words and wrap them in span tags. I am using preg_replace for extract and wrapping purposes, but it's not outputting anything. preg_replace("/[A-Z]/", " $1 ", $str) | You need to put the pattern in parentheses /([A-Z])/, like this: preg_replace("/([A-Z])/", " $1 ", $str) | How can I get at the matches when using preg_replace in PHP? I am trying to grab the capital letters of a couple of words and wrap them in span tags. I am using preg_replace for extract and wrapping purposes, but it's not outputting anything. preg_replace("/[A-Z]/", " $1 ", $str) | TITLE:
How can I get at the matches when using preg_replace in PHP?
QUESTION:
I am trying to grab the capital letters of a couple of words and wrap them in span tags. I am using preg_replace for extract and wrapping purposes, but it's not outputting anything. preg_replace("/[A-Z]/", " $1 ", $str)
ANSWER:
You need to put the pattern in parentheses /([A-Z])/, like this: preg_replace("/([A-Z])/", " $1 ", $str) | [
"php",
"regex",
"html-parsing",
"preg-replace"
] | 59 | 59 | 22,319 | 4 | 0 | 2008-08-05T00:35:17.493000 | 2008-08-05T00:36:08.350000 |
1,760 | 1,821 | .NET unit testing packages | I am getting back into a bit more.NET after a few-years of not using it full-time and am wondering what the good unit testing packages are these days. I'm familiar with NUnit (a few years ago) and have played briefly around with IronRuby, with the goal of getting something like RSpec going, but I don't know much beyond that. I realize I could google for this and call it a day, but I believe I'm likely to get a better and more informed response from asking a question here:-) Suggestions? | There are so many it's crazy. Crazy good, I guess. For the conservative types (me), NUnit is still available and still more than capable. For the Microsoft-types, MSTest is adequate, but it is slow and clunky compared to NUnit. It also lacks code coverage without paying the big bucks for the pricey versions of Visual Studio. There's also MbUnit. It's like NUnit, but it has nifty features like RowTest (run the same test with different parameters) and Rollback (put the database back like you found it after a test). And finally, xUnit.net is the trendy option with some attitude. Oh, and TestDriven.NET will give you IDE integration for both NUnit and MbUnit. I'm sure they're all just fine. I'd steer away from MSTest though, unless you just enjoy the convenience of having everything in one IDE out of the box. Scott Hanselman has a podcast on this very topic. | .NET unit testing packages I am getting back into a bit more.NET after a few-years of not using it full-time and am wondering what the good unit testing packages are these days. I'm familiar with NUnit (a few years ago) and have played briefly around with IronRuby, with the goal of getting something like RSpec going, but I don't know much beyond that. I realize I could google for this and call it a day, but I believe I'm likely to get a better and more informed response from asking a question here:-) Suggestions? | TITLE:
.NET unit testing packages
QUESTION:
I am getting back into a bit more.NET after a few-years of not using it full-time and am wondering what the good unit testing packages are these days. I'm familiar with NUnit (a few years ago) and have played briefly around with IronRuby, with the goal of getting something like RSpec going, but I don't know much beyond that. I realize I could google for this and call it a day, but I believe I'm likely to get a better and more informed response from asking a question here:-) Suggestions?
ANSWER:
There are so many it's crazy. Crazy good, I guess. For the conservative types (me), NUnit is still available and still more than capable. For the Microsoft-types, MSTest is adequate, but it is slow and clunky compared to NUnit. It also lacks code coverage without paying the big bucks for the pricey versions of Visual Studio. There's also MbUnit. It's like NUnit, but it has nifty features like RowTest (run the same test with different parameters) and Rollback (put the database back like you found it after a test). And finally, xUnit.net is the trendy option with some attitude. Oh, and TestDriven.NET will give you IDE integration for both NUnit and MbUnit. I'm sure they're all just fine. I'd steer away from MSTest though, unless you just enjoy the convenience of having everything in one IDE out of the box. Scott Hanselman has a podcast on this very topic. | [
"c#",
".net",
"unit-testing",
"testing"
] | 63 | 55 | 11,645 | 11 | 0 | 2008-08-05T00:51:49.177000 | 2008-08-05T02:15:24.873000 |
1,762 | 1,771 | Why is my ternary expression not working? | I am trying to set a flag to show or hide a page element, but it always displays even when the expression is false. $canMerge = ($condition1 && $condition2)? 'true': 'false';... Stuff What's up? | This is broken because 'false' as a string will evaluate to true as a boolean. However, this is an unneeded ternary expression, because the resulting values are simple true and false. This would be equivalent: $canMerge = ($condition1 && $condition2); | Why is my ternary expression not working? I am trying to set a flag to show or hide a page element, but it always displays even when the expression is false. $canMerge = ($condition1 && $condition2)? 'true': 'false';... Stuff What's up? | TITLE:
Why is my ternary expression not working?
QUESTION:
I am trying to set a flag to show or hide a page element, but it always displays even when the expression is false. $canMerge = ($condition1 && $condition2)? 'true': 'false';... Stuff What's up?
ANSWER:
This is broken because 'false' as a string will evaluate to true as a boolean. However, this is an unneeded ternary expression, because the resulting values are simple true and false. This would be equivalent: $canMerge = ($condition1 && $condition2); | [
"php",
"ternary-operator"
] | 26 | 41 | 1,142 | 5 | 0 | 2008-08-05T00:56:43.813000 | 2008-08-05T01:03:12.553000 |
1,790 | 2,017 | Federated (Synced) Subversion servers? | Is it possible to create "federated" Subversion servers? As in one server at location A and another at location B that sync up their local versions of the repository automatically. That way when someone at either location interacts with the repository they are accessing their respective local server and therefore has faster response times. | This is more or less the perfect use case for SVK. SVK is a command line front end for subversion that works with an entire local copy of the repository. So your commits, updates, etc. work on the local repository and you can then sync with a master. I would generally recommend SVK over plain subversion anyway as it makes a lot of things nicer. No.svn folders, better branching and merging, better conflict resolution. | Federated (Synced) Subversion servers? Is it possible to create "federated" Subversion servers? As in one server at location A and another at location B that sync up their local versions of the repository automatically. That way when someone at either location interacts with the repository they are accessing their respective local server and therefore has faster response times. | TITLE:
Federated (Synced) Subversion servers?
QUESTION:
Is it possible to create "federated" Subversion servers? As in one server at location A and another at location B that sync up their local versions of the repository automatically. That way when someone at either location interacts with the repository they are accessing their respective local server and therefore has faster response times.
ANSWER:
This is more or less the perfect use case for SVK. SVK is a command line front end for subversion that works with an entire local copy of the repository. So your commits, updates, etc. work on the local repository and you can then sync with a master. I would generally recommend SVK over plain subversion anyway as it makes a lot of things nicer. No.svn folders, better branching and merging, better conflict resolution. | [
"svn",
"version-control"
] | 20 | 4 | 3,208 | 5 | 0 | 2008-08-05T01:27:34.610000 | 2008-08-05T08:22:05.943000 |
1,836 | 1,843 | Wiggling the mouse | OK. This is a bit of a vanity app, but I had a situation today at work where I was in a training class and the machine was set to lock every 10 minutes. Well, if the trainers got excited about talking - as opposed to changing slides - the machine would lock up. I'd like to write a teeny app that has nothing but a taskbar icon that does nothing but move the mouse by 1 pixel every 4 minutes. I can do that in 3 ways with Delphi (my strong language) but I'm moving to C# for work and I'd like to know the path of least resistance there. | for C# 3.5 without notifyicon therefore you will need to terminate this application in task manager manually using System; using System.Drawing; using System.Windows.Forms;
static class Program { static void Main() { Timer timer = new Timer(); // timer.Interval = 4 minutes timer.Interval = (int)(TimeSpan.TicksPerMinute * 4 / TimeSpan.TicksPerMillisecond); timer.Tick += (sender, args) => { Cursor.Position = new Point(Cursor.Position.X + 1, Cursor.Position.Y + 1); }; timer.Start(); Application.Run(); } } | Wiggling the mouse OK. This is a bit of a vanity app, but I had a situation today at work where I was in a training class and the machine was set to lock every 10 minutes. Well, if the trainers got excited about talking - as opposed to changing slides - the machine would lock up. I'd like to write a teeny app that has nothing but a taskbar icon that does nothing but move the mouse by 1 pixel every 4 minutes. I can do that in 3 ways with Delphi (my strong language) but I'm moving to C# for work and I'd like to know the path of least resistance there. | TITLE:
Wiggling the mouse
QUESTION:
OK. This is a bit of a vanity app, but I had a situation today at work where I was in a training class and the machine was set to lock every 10 minutes. Well, if the trainers got excited about talking - as opposed to changing slides - the machine would lock up. I'd like to write a teeny app that has nothing but a taskbar icon that does nothing but move the mouse by 1 pixel every 4 minutes. I can do that in 3 ways with Delphi (my strong language) but I'm moving to C# for work and I'd like to know the path of least resistance there.
ANSWER:
for C# 3.5 without notifyicon therefore you will need to terminate this application in task manager manually using System; using System.Drawing; using System.Windows.Forms;
static class Program { static void Main() { Timer timer = new Timer(); // timer.Interval = 4 minutes timer.Interval = (int)(TimeSpan.TicksPerMinute * 4 / TimeSpan.TicksPerMillisecond); timer.Tick += (sender, args) => { Cursor.Position = new Point(Cursor.Position.X + 1, Cursor.Position.Y + 1); }; timer.Start(); Application.Run(); } } | [
"c#",
"winapi",
"mouse"
] | 41 | 28 | 17,631 | 6 | 0 | 2008-08-05T02:51:37.420000 | 2008-08-05T03:00:24.750000 |
1,848 | 1,856 | Locating Text within image | I am currently working on a project and my goal is to locate text in an image. OCR'ing the text is not my intention as of yet. I want to basically obtain the bounds of text within an image. I am using the AForge.Net imaging component for manipulation. Any assistance in some sense or another? Update 2/5/09: I've since went along another route in my project. However I did attempt to obtain text using MODI (Microsoft Office Document Imaging). It allows you to OCR an image and pull text from it with some ease. | This is an active area of research. There are literally oodles of academic papers on the subject. It's going to be difficult to give you assistance especially w/o more deatails. Are you looking for specific types of text? Fonts? English-only? Are you familiar with the academic literature? "Text detection" is a standard problem in any OCR (optical character recognition) system and consequently there are lots of bits of code on the interwebs that deal with it. I could start listing piles of links from google but I suggest you just do a search for "text detection" and start reading:). There is ample example code available as well. | Locating Text within image I am currently working on a project and my goal is to locate text in an image. OCR'ing the text is not my intention as of yet. I want to basically obtain the bounds of text within an image. I am using the AForge.Net imaging component for manipulation. Any assistance in some sense or another? Update 2/5/09: I've since went along another route in my project. However I did attempt to obtain text using MODI (Microsoft Office Document Imaging). It allows you to OCR an image and pull text from it with some ease. | TITLE:
Locating Text within image
QUESTION:
I am currently working on a project and my goal is to locate text in an image. OCR'ing the text is not my intention as of yet. I want to basically obtain the bounds of text within an image. I am using the AForge.Net imaging component for manipulation. Any assistance in some sense or another? Update 2/5/09: I've since went along another route in my project. However I did attempt to obtain text using MODI (Microsoft Office Document Imaging). It allows you to OCR an image and pull text from it with some ease.
ANSWER:
This is an active area of research. There are literally oodles of academic papers on the subject. It's going to be difficult to give you assistance especially w/o more deatails. Are you looking for specific types of text? Fonts? English-only? Are you familiar with the academic literature? "Text detection" is a standard problem in any OCR (optical character recognition) system and consequently there are lots of bits of code on the interwebs that deal with it. I could start listing piles of links from google but I suggest you just do a search for "text detection" and start reading:). There is ample example code available as well. | [
"c#",
"image",
"image-processing",
"artificial-intelligence"
] | 30 | 14 | 6,130 | 4 | 0 | 2008-08-05T03:04:43.683000 | 2008-08-05T03:24:27.840000 |
1,854 | 1,857 | How to identify which OS Python is running on | What do I need to look at to see whether I'm on Windows or Unix, etc.? | >>> import os
>>> os.name 'posix'
>>> import platform
>>> platform.system() 'Linux'
>>> platform.release() '2.6.22-15-generic' The output of platform.system() is as follows: Linux: Linux Mac: Darwin Windows: Windows See: platform — Access to underlying platform’s identifying data | How to identify which OS Python is running on What do I need to look at to see whether I'm on Windows or Unix, etc.? | TITLE:
How to identify which OS Python is running on
QUESTION:
What do I need to look at to see whether I'm on Windows or Unix, etc.?
ANSWER:
>>> import os
>>> os.name 'posix'
>>> import platform
>>> platform.system() 'Linux'
>>> platform.release() '2.6.22-15-generic' The output of platform.system() is as follows: Linux: Linux Mac: Darwin Windows: Windows See: platform — Access to underlying platform’s identifying data | [
"python",
"operating-system",
"cross-platform",
"platform-agnostic"
] | 953 | 1,265 | 520,422 | 27 | 0 | 2008-08-05T03:23:18.917000 | 2008-08-05T03:27:03.760000 |
1,873 | 1,886 | Triple Quotes? How do I delimit a databound Javascript string parameter in ASP.NET? | How do I delimit a Javascript data-bound string parameter in an anchor OnClick event? I have an anchor tag in an ASP.NET Repeater control. The OnClick event of the anchor contains a call to a Javascript function. The Javascript function takes a string for its input parameter. The string parameter is populated with a data-bound value from the Repeater. I need the "double quotes" for the Container.DataItem. I need the 'single quotes' for the OnClick. And I still need one more delimiter (triple quotes?) for the input string parameter of the Javascript function call. Since I can't use 'single quotes' again, how do I ensure the Javascript function knows the input parameter is a string and not an integer? Without the extra quotes around the input string parameter, the Javascript function thinks I'm passing in an integer. The anchor: Show/Hide And there is my Javascript: | I had recently similar problem and the only way to solve it was to use plain old HTML codes for single ( ' ) and double quotes ( " ). Source code was total mess of course but it worked. Try Show/Hide or Show/Hide | Triple Quotes? How do I delimit a databound Javascript string parameter in ASP.NET? How do I delimit a Javascript data-bound string parameter in an anchor OnClick event? I have an anchor tag in an ASP.NET Repeater control. The OnClick event of the anchor contains a call to a Javascript function. The Javascript function takes a string for its input parameter. The string parameter is populated with a data-bound value from the Repeater. I need the "double quotes" for the Container.DataItem. I need the 'single quotes' for the OnClick. And I still need one more delimiter (triple quotes?) for the input string parameter of the Javascript function call. Since I can't use 'single quotes' again, how do I ensure the Javascript function knows the input parameter is a string and not an integer? Without the extra quotes around the input string parameter, the Javascript function thinks I'm passing in an integer. The anchor: Show/Hide And there is my Javascript: | TITLE:
Triple Quotes? How do I delimit a databound Javascript string parameter in ASP.NET?
QUESTION:
How do I delimit a Javascript data-bound string parameter in an anchor OnClick event? I have an anchor tag in an ASP.NET Repeater control. The OnClick event of the anchor contains a call to a Javascript function. The Javascript function takes a string for its input parameter. The string parameter is populated with a data-bound value from the Repeater. I need the "double quotes" for the Container.DataItem. I need the 'single quotes' for the OnClick. And I still need one more delimiter (triple quotes?) for the input string parameter of the Javascript function call. Since I can't use 'single quotes' again, how do I ensure the Javascript function knows the input parameter is a string and not an integer? Without the extra quotes around the input string parameter, the Javascript function thinks I'm passing in an integer. The anchor: Show/Hide And there is my Javascript:
ANSWER:
I had recently similar problem and the only way to solve it was to use plain old HTML codes for single ( ' ) and double quotes ( " ). Source code was total mess of course but it worked. Try Show/Hide or Show/Hide | [
"asp.net",
"javascript",
"anchor",
"quotes"
] | 47 | 32 | 23,470 | 5 | 0 | 2008-08-05T04:05:53.230000 | 2008-08-05T04:28:21.983000 |
1,908 | 1,945 | How to map a latitude/longitude to a distorted map? | I have a bunch of latitude/longitude pairs that map to known x/y coordinates on a (geographically distorted) map. Then I have one more latitude/longitude pair. I want to plot it on the map as best is possible. How do I go about doing this? At first I decided to create a system of linear equations for the three nearest lat/long points and compute a transformation from these, but this doesn't work well at all. Since that's a linear system, I can't use more nearby points either. You can't assume North is up: all you have is the existing lat/long->x/y mappings. EDIT: it's not a Mercator projection, or anything like that. It's arbitrarily distorted for readability (think subway map). I want to use only the nearest 5 to 10 mappings so that distortion on other parts of the map doesn't affect the mapping I'm trying to compute. Further, the entire map is in a very small geographical area so there's no need to worry about the globe--flat-earth assumptions are good enough. | Are there any more specific details on the kind of distortion? If, for example, your latitudes and longitudes are "distorted" onto your 2D map using a Mercator projection, the conversion math is readily available. If the map is distorted truly arbitrarily, there are lots of things you could try, but the simplest would probably be to compute a weighted average from your existing point mappings. Your weights could be the squared inverse of the x/y distance from your new point to each of your existing points. Some pseudocode: estimate-latitude-longitude (x, y)
numerator-latitude:= 0 numerator-longitude:= 0 denominator:= 0
for each point, deltaX:= x - point.x deltaY:= y - point.y distSq:= deltaX * deltaX + deltaY * deltaY weight:= 1 / distSq
numerator-latitude += weight * point.latitude numerator-longitude += weight * point.longitude denominator += weight
return (numerator-latitude / denominator, numerator-longitude / denominator) This code will give a relatively simple approximation. If you can be more precise about the way the projection distorts the geographical coordinates, you can probably do much better. | How to map a latitude/longitude to a distorted map? I have a bunch of latitude/longitude pairs that map to known x/y coordinates on a (geographically distorted) map. Then I have one more latitude/longitude pair. I want to plot it on the map as best is possible. How do I go about doing this? At first I decided to create a system of linear equations for the three nearest lat/long points and compute a transformation from these, but this doesn't work well at all. Since that's a linear system, I can't use more nearby points either. You can't assume North is up: all you have is the existing lat/long->x/y mappings. EDIT: it's not a Mercator projection, or anything like that. It's arbitrarily distorted for readability (think subway map). I want to use only the nearest 5 to 10 mappings so that distortion on other parts of the map doesn't affect the mapping I'm trying to compute. Further, the entire map is in a very small geographical area so there's no need to worry about the globe--flat-earth assumptions are good enough. | TITLE:
How to map a latitude/longitude to a distorted map?
QUESTION:
I have a bunch of latitude/longitude pairs that map to known x/y coordinates on a (geographically distorted) map. Then I have one more latitude/longitude pair. I want to plot it on the map as best is possible. How do I go about doing this? At first I decided to create a system of linear equations for the three nearest lat/long points and compute a transformation from these, but this doesn't work well at all. Since that's a linear system, I can't use more nearby points either. You can't assume North is up: all you have is the existing lat/long->x/y mappings. EDIT: it's not a Mercator projection, or anything like that. It's arbitrarily distorted for readability (think subway map). I want to use only the nearest 5 to 10 mappings so that distortion on other parts of the map doesn't affect the mapping I'm trying to compute. Further, the entire map is in a very small geographical area so there's no need to worry about the globe--flat-earth assumptions are good enough.
ANSWER:
Are there any more specific details on the kind of distortion? If, for example, your latitudes and longitudes are "distorted" onto your 2D map using a Mercator projection, the conversion math is readily available. If the map is distorted truly arbitrarily, there are lots of things you could try, but the simplest would probably be to compute a weighted average from your existing point mappings. Your weights could be the squared inverse of the x/y distance from your new point to each of your existing points. Some pseudocode: estimate-latitude-longitude (x, y)
numerator-latitude:= 0 numerator-longitude:= 0 denominator:= 0
for each point, deltaX:= x - point.x deltaY:= y - point.y distSq:= deltaX * deltaX + deltaY * deltaY weight:= 1 / distSq
numerator-latitude += weight * point.latitude numerator-longitude += weight * point.longitude denominator += weight
return (numerator-latitude / denominator, numerator-longitude / denominator) This code will give a relatively simple approximation. If you can be more precise about the way the projection distorts the geographical coordinates, you can probably do much better. | [
"math",
"maps",
"mapping",
"latitude-longitude"
] | 25 | 8 | 6,451 | 4 | 0 | 2008-08-05T04:55:28.683000 | 2008-08-05T05:48:22.353000 |
1,936 | 1,940 | How to RedirectToAction in ASP.NET MVC without losing request data | Using ASP.NET MVC there are situations (such as form submission) that may require a RedirectToAction. One such situation is when you encounter validation errors after a form submission and need to redirect back to the form, but would like the URL to reflect the URL of the form, not the action page it submits to. As I require the form to contain the originally POST ed data, for user convenience, as well as validation purposes, how can I pass the data through the RedirectToAction()? If I use the viewData parameter, my POST parameters will be changed to GET parameters. | The solution is to use the TempData property to store the desired Request components. For instance: public ActionResult Send() { TempData["form"] = Request.Form; return this.RedirectToAction(a => a.Form()); } Then in your "Form" action you can go: public ActionResult Form() { /* Declare viewData etc. */
if (TempData["form"]!= null) { /* Cast TempData["form"] to System.Collections.Specialized.NameValueCollection and use it */ }
return View("Form", viewData); } | How to RedirectToAction in ASP.NET MVC without losing request data Using ASP.NET MVC there are situations (such as form submission) that may require a RedirectToAction. One such situation is when you encounter validation errors after a form submission and need to redirect back to the form, but would like the URL to reflect the URL of the form, not the action page it submits to. As I require the form to contain the originally POST ed data, for user convenience, as well as validation purposes, how can I pass the data through the RedirectToAction()? If I use the viewData parameter, my POST parameters will be changed to GET parameters. | TITLE:
How to RedirectToAction in ASP.NET MVC without losing request data
QUESTION:
Using ASP.NET MVC there are situations (such as form submission) that may require a RedirectToAction. One such situation is when you encounter validation errors after a form submission and need to redirect back to the form, but would like the URL to reflect the URL of the form, not the action page it submits to. As I require the form to contain the originally POST ed data, for user convenience, as well as validation purposes, how can I pass the data through the RedirectToAction()? If I use the viewData parameter, my POST parameters will be changed to GET parameters.
ANSWER:
The solution is to use the TempData property to store the desired Request components. For instance: public ActionResult Send() { TempData["form"] = Request.Form; return this.RedirectToAction(a => a.Form()); } Then in your "Form" action you can go: public ActionResult Form() { /* Declare viewData etc. */
if (TempData["form"]!= null) { /* Cast TempData["form"] to System.Collections.Specialized.NameValueCollection and use it */ }
return View("Form", viewData); } | [
"c#",
"asp.net-mvc"
] | 123 | 82 | 93,516 | 6 | 0 | 2008-08-05T05:33:41.697000 | 2008-08-05T05:43:27.900000 |
1,949 | 5,310 | Are Multiple DataContext classes ever appropriate? | In order to fully use LinqToSql in an ASP.net 3.5 application, it is necessary to create DataContext classes (which is usually done using the designer in VS 2008). From the UI perspective, the DataContext is a design of the sections of your database that you would like to expose to through LinqToSql and is integral in setting up the ORM features of LinqToSql. My question is: I am setting up a project that uses a large database where all tables are interconnected in some way through Foreign Keys. My first inclination is to make one huge DataContext class that models the entire database. That way I could in theory (though I don't know if this would be needed in practice) use the Foreign Key connections that are generated through LinqToSql to easily go between related objects in my code, insert related objects, etc. However, after giving it some thought, I am now thinking that it may make more sense to create multiple DataContext classes, each one relating to a specific namespace or logical interrelated section within my database. My main concern is that instantiating and disposing one huge DataContext class all the time for individual operations that relate to specific areas of the Database would be impose an unnecessary imposition on application resources. Additionally, it is easier to create and manage smaller DataContext files than one big one. The thing that I would lose is that there would be some distant sections of the database that would not be navigable through LinqToSql (even though a chain of relationships connects them in the actual database). Additionally, there would be some table classes that would exist in more than one DataContext. Any thoughts or experience on whether multiple DataContexts (corresponding to DB namespaces) are appropriate in place of (or in addition to) one very large DataContext class (corresponding to the whole DB)? | I disagree with John's answer. The DataContext (or Linq to Entities ObjectContext) is more of a "unit of work" than a connection. It manages change tracking, etc. See this blog post for a description: Lifetime of a LINQ to SQL DataContext The four main points of this blog post are that DataContext: Is ideally suited for a "unit of work" approach Is also designed for "stateless" server operation Is not designed for Long-lived usage Should be used very carefully after any SumbitChanges() operation. Considering that, I don't think using more than one DataContext would do any harm- in fact, creating different DataContexts for different types of work would help make your LinqToSql impelmentation more usuable and organized. The only downside is you wouldn't be able to use sqlmetal to auto-generate your dmbl. | Are Multiple DataContext classes ever appropriate? In order to fully use LinqToSql in an ASP.net 3.5 application, it is necessary to create DataContext classes (which is usually done using the designer in VS 2008). From the UI perspective, the DataContext is a design of the sections of your database that you would like to expose to through LinqToSql and is integral in setting up the ORM features of LinqToSql. My question is: I am setting up a project that uses a large database where all tables are interconnected in some way through Foreign Keys. My first inclination is to make one huge DataContext class that models the entire database. That way I could in theory (though I don't know if this would be needed in practice) use the Foreign Key connections that are generated through LinqToSql to easily go between related objects in my code, insert related objects, etc. However, after giving it some thought, I am now thinking that it may make more sense to create multiple DataContext classes, each one relating to a specific namespace or logical interrelated section within my database. My main concern is that instantiating and disposing one huge DataContext class all the time for individual operations that relate to specific areas of the Database would be impose an unnecessary imposition on application resources. Additionally, it is easier to create and manage smaller DataContext files than one big one. The thing that I would lose is that there would be some distant sections of the database that would not be navigable through LinqToSql (even though a chain of relationships connects them in the actual database). Additionally, there would be some table classes that would exist in more than one DataContext. Any thoughts or experience on whether multiple DataContexts (corresponding to DB namespaces) are appropriate in place of (or in addition to) one very large DataContext class (corresponding to the whole DB)? | TITLE:
Are Multiple DataContext classes ever appropriate?
QUESTION:
In order to fully use LinqToSql in an ASP.net 3.5 application, it is necessary to create DataContext classes (which is usually done using the designer in VS 2008). From the UI perspective, the DataContext is a design of the sections of your database that you would like to expose to through LinqToSql and is integral in setting up the ORM features of LinqToSql. My question is: I am setting up a project that uses a large database where all tables are interconnected in some way through Foreign Keys. My first inclination is to make one huge DataContext class that models the entire database. That way I could in theory (though I don't know if this would be needed in practice) use the Foreign Key connections that are generated through LinqToSql to easily go between related objects in my code, insert related objects, etc. However, after giving it some thought, I am now thinking that it may make more sense to create multiple DataContext classes, each one relating to a specific namespace or logical interrelated section within my database. My main concern is that instantiating and disposing one huge DataContext class all the time for individual operations that relate to specific areas of the Database would be impose an unnecessary imposition on application resources. Additionally, it is easier to create and manage smaller DataContext files than one big one. The thing that I would lose is that there would be some distant sections of the database that would not be navigable through LinqToSql (even though a chain of relationships connects them in the actual database). Additionally, there would be some table classes that would exist in more than one DataContext. Any thoughts or experience on whether multiple DataContexts (corresponding to DB namespaces) are appropriate in place of (or in addition to) one very large DataContext class (corresponding to the whole DB)?
ANSWER:
I disagree with John's answer. The DataContext (or Linq to Entities ObjectContext) is more of a "unit of work" than a connection. It manages change tracking, etc. See this blog post for a description: Lifetime of a LINQ to SQL DataContext The four main points of this blog post are that DataContext: Is ideally suited for a "unit of work" approach Is also designed for "stateless" server operation Is not designed for Long-lived usage Should be used very carefully after any SumbitChanges() operation. Considering that, I don't think using more than one DataContext would do any harm- in fact, creating different DataContexts for different types of work would help make your LinqToSql impelmentation more usuable and organized. The only downside is you wouldn't be able to use sqlmetal to auto-generate your dmbl. | [
"asp.net",
".net",
"linq-to-sql",
"datacontext"
] | 32 | 28 | 5,860 | 5 | 0 | 2008-08-05T05:54:34.697000 | 2008-08-07T21:02:30.057000 |
1,982 | 47,086 | CPU throttling in C++ | I was just wondering if there is an elegant way to set the maximum CPU load for a particular thread doing intensive calculations. Right now I have located the most time-consuming loop in the thread (it does only compression) and use GetTickCount() and Sleep() with hardcoded values. It makes sure that the loop continues for a certain period and then sleeps for a certain minimum time. It more or less does the job, i.e. guarantees that the thread will not use more than 50% of CPU. However, behavior is dependent on the number of CPU cores (huge disadvantage) and simply ugly (smaller disadvantage). Any ideas? | I am not aware of any API to do get the OS's scheduler to do what you want (even if your thread is idle-priority, if there are no higher-priority ready threads, yours will run). However, I think you can improvise a fairly elegant throttling function based on what you are already doing. Essentially (I don't have a Windows dev machine handy): Pick a default amount of time the thread will sleep each iteration. Then, on each iteration (or on every nth iteration, such that the throttling function doesn't itself become a significant CPU load), Compute the amount of CPU time your thread used since the last time your throttling function was called (I'll call this dCPU). You can use the GetThreadTimes() API to get the amount of time your thread has been executing. Compute the amount of real time elapsed since the last time your throttling function was called (I'll call this dClock). dCPU / dClock is the percent CPU usage (of one CPU). If it is higher than you want, increase your sleep time, if lower, decrease the sleep time. Have your thread sleep for the computed time. Depending on how your watchdog computes CPU usage, you might want to use GetProcessAffinityMask() to find out how many CPUs the system has. dCPU / (dClock * CPUs) is the percentage of total CPU time available. You will still have to pick some magic numbers for the initial sleep time and the increment/decrement amount, but I think this algorithm could be tuned to keep a thread running at fairly close to a determined percent of CPU. | CPU throttling in C++ I was just wondering if there is an elegant way to set the maximum CPU load for a particular thread doing intensive calculations. Right now I have located the most time-consuming loop in the thread (it does only compression) and use GetTickCount() and Sleep() with hardcoded values. It makes sure that the loop continues for a certain period and then sleeps for a certain minimum time. It more or less does the job, i.e. guarantees that the thread will not use more than 50% of CPU. However, behavior is dependent on the number of CPU cores (huge disadvantage) and simply ugly (smaller disadvantage). Any ideas? | TITLE:
CPU throttling in C++
QUESTION:
I was just wondering if there is an elegant way to set the maximum CPU load for a particular thread doing intensive calculations. Right now I have located the most time-consuming loop in the thread (it does only compression) and use GetTickCount() and Sleep() with hardcoded values. It makes sure that the loop continues for a certain period and then sleeps for a certain minimum time. It more or less does the job, i.e. guarantees that the thread will not use more than 50% of CPU. However, behavior is dependent on the number of CPU cores (huge disadvantage) and simply ugly (smaller disadvantage). Any ideas?
ANSWER:
I am not aware of any API to do get the OS's scheduler to do what you want (even if your thread is idle-priority, if there are no higher-priority ready threads, yours will run). However, I think you can improvise a fairly elegant throttling function based on what you are already doing. Essentially (I don't have a Windows dev machine handy): Pick a default amount of time the thread will sleep each iteration. Then, on each iteration (or on every nth iteration, such that the throttling function doesn't itself become a significant CPU load), Compute the amount of CPU time your thread used since the last time your throttling function was called (I'll call this dCPU). You can use the GetThreadTimes() API to get the amount of time your thread has been executing. Compute the amount of real time elapsed since the last time your throttling function was called (I'll call this dClock). dCPU / dClock is the percent CPU usage (of one CPU). If it is higher than you want, increase your sleep time, if lower, decrease the sleep time. Have your thread sleep for the computed time. Depending on how your watchdog computes CPU usage, you might want to use GetProcessAffinityMask() to find out how many CPUs the system has. dCPU / (dClock * CPUs) is the percentage of total CPU time available. You will still have to pick some magic numbers for the initial sleep time and the increment/decrement amount, but I think this algorithm could be tuned to keep a thread running at fairly close to a determined percent of CPU. | [
"c++",
"performance",
"cpu",
"throttling"
] | 49 | 22 | 6,095 | 5 | 0 | 2008-08-05T07:11:08.427000 | 2008-09-05T23:33:42.087000 |
1,983 | 2,277 | Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each? | In many places, (1,2,3) (a tuple) and [1,2,3] (a list) can be used interchangeably. When should I use one or the other, and why? | From the Python FAQ: Lists and tuples, while similar in many respects, are generally used in fundamentally different ways. Tuples can be thought of as being similar to Pascal records or C structs; they're small collections of related data which may be of different types which are operated on as a group. For example, a Cartesian coordinate is appropriately represented as a tuple of two or three numbers. Lists, on the other hand, are more like arrays in other languages. They tend to hold a varying number of objects all of which have the same type and which are operated on one-by-one. Generally by convention you wouldn't choose a list or a tuple just based on its (im)mutability. You would choose a tuple for small collections of completely different pieces of data in which a full-blown class would be too heavyweight, and a list for collections of any reasonable size where you have a homogeneous set of data. | Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each? In many places, (1,2,3) (a tuple) and [1,2,3] (a list) can be used interchangeably. When should I use one or the other, and why? | TITLE:
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?
QUESTION:
In many places, (1,2,3) (a tuple) and [1,2,3] (a list) can be used interchangeably. When should I use one or the other, and why?
ANSWER:
From the Python FAQ: Lists and tuples, while similar in many respects, are generally used in fundamentally different ways. Tuples can be thought of as being similar to Pascal records or C structs; they're small collections of related data which may be of different types which are operated on as a group. For example, a Cartesian coordinate is appropriately represented as a tuple of two or three numbers. Lists, on the other hand, are more like arrays in other languages. They tend to hold a varying number of objects all of which have the same type and which are operated on one-by-one. Generally by convention you wouldn't choose a list or a tuple just based on its (im)mutability. You would choose a tuple for small collections of completely different pieces of data in which a full-blown class would be too heavyweight, and a list for collections of any reasonable size where you have a homogeneous set of data. | [
"python",
"list",
"tuples"
] | 60 | 36 | 18,463 | 18 | 0 | 2008-08-05T07:18:55.853000 | 2008-08-05T13:22:43.030000 |
1,988 | 63,737 | How far can LISP macros go? | I have read a lot that LISP can redefine syntax on the fly, presumably with macros. I am curious how far does this actually go? Can you redefine the language structure so much that it borderline becomes a compiler for another language? For example, could you change the functional nature of LISP into a more object oriented syntax and semantics, maybe say having syntax closer to something like Ruby? Especially, is it possible to get rid of the parenthesis hell using macros? I have learned enough (Emacs-)LISP to customize Emacs with my own micro-features, but I am very curious how far macros can go in customizing the language. | That's a really good question. I think it's nuanced but definitely answerable: Macros are not stuck in s-expressions. See the LOOP macro for a very complex language written using keywords (symbols). So, while you may start and end the loop with parentheses, inside it has its own syntax. Example: (loop for x from 0 below 100 when (even x) collect x) That being said, most simple macros just use s-expressions. And you'd be "stuck" using them. But s-expressions, like Sergio has answered, start to feel right. The syntax gets out of the way and you start coding in the syntax tree. As for reader macros, yes, you could conceivably write something like this: #R{ ruby.code.goes.here } But you'd need to write your own Ruby syntax parser. You can also mimic some of the Ruby constructs, like blocks, with macros that compile to the existing Lisp constructs. #B(some lisp (code goes here)) would translate to (lambda () (some lisp (code goes here))) See this page for how to do it. | How far can LISP macros go? I have read a lot that LISP can redefine syntax on the fly, presumably with macros. I am curious how far does this actually go? Can you redefine the language structure so much that it borderline becomes a compiler for another language? For example, could you change the functional nature of LISP into a more object oriented syntax and semantics, maybe say having syntax closer to something like Ruby? Especially, is it possible to get rid of the parenthesis hell using macros? I have learned enough (Emacs-)LISP to customize Emacs with my own micro-features, but I am very curious how far macros can go in customizing the language. | TITLE:
How far can LISP macros go?
QUESTION:
I have read a lot that LISP can redefine syntax on the fly, presumably with macros. I am curious how far does this actually go? Can you redefine the language structure so much that it borderline becomes a compiler for another language? For example, could you change the functional nature of LISP into a more object oriented syntax and semantics, maybe say having syntax closer to something like Ruby? Especially, is it possible to get rid of the parenthesis hell using macros? I have learned enough (Emacs-)LISP to customize Emacs with my own micro-features, but I am very curious how far macros can go in customizing the language.
ANSWER:
That's a really good question. I think it's nuanced but definitely answerable: Macros are not stuck in s-expressions. See the LOOP macro for a very complex language written using keywords (symbols). So, while you may start and end the loop with parentheses, inside it has its own syntax. Example: (loop for x from 0 below 100 when (even x) collect x) That being said, most simple macros just use s-expressions. And you'd be "stuck" using them. But s-expressions, like Sergio has answered, start to feel right. The syntax gets out of the way and you start coding in the syntax tree. As for reader macros, yes, you could conceivably write something like this: #R{ ruby.code.goes.here } But you'd need to write your own Ruby syntax parser. You can also mimic some of the Ruby constructs, like blocks, with macros that compile to the existing Lisp constructs. #B(some lisp (code goes here)) would translate to (lambda () (some lisp (code goes here))) See this page for how to do it. | [
"macros",
"lisp"
] | 50 | 36 | 7,515 | 14 | 0 | 2008-08-05T07:32:54.437000 | 2008-09-15T15:07:21.940000 |
2,034 | 2,036 | What do the result codes in SVN mean? | What do the result codes in SVN mean? I need a quick reference. | For additional details see the SVNBook: "Status of working copy files and directories". The common statuses: U: Working file was updated G: Changes on the repo were automatically merged into the working copy M: Working copy is modified C: This file conflicts with the version in the repo?: This file is not under version control!: This file is under version control but is missing or incomplete A: This file will be added to version control (after commit) A+: This file will be moved (after commit) D: This file will be deleted (after commit) S: This signifies that the file or directory has been switched from the path of the rest of the working copy (using svn switch) to a branch I: Ignored X: External definition ~: Type changed R: Item has been replaced in your working copy. This means the file was scheduled for deletion, and then a new file with the same name was scheduled for addition in its place. L: Item is locked E: Item existed, as it would have been created, by an svn update. | What do the result codes in SVN mean? What do the result codes in SVN mean? I need a quick reference. | TITLE:
What do the result codes in SVN mean?
QUESTION:
What do the result codes in SVN mean? I need a quick reference.
ANSWER:
For additional details see the SVNBook: "Status of working copy files and directories". The common statuses: U: Working file was updated G: Changes on the repo were automatically merged into the working copy M: Working copy is modified C: This file conflicts with the version in the repo?: This file is not under version control!: This file is under version control but is missing or incomplete A: This file will be added to version control (after commit) A+: This file will be moved (after commit) D: This file will be deleted (after commit) S: This signifies that the file or directory has been switched from the path of the rest of the working copy (using svn switch) to a branch I: Ignored X: External definition ~: Type changed R: Item has been replaced in your working copy. This means the file was scheduled for deletion, and then a new file with the same name was scheduled for addition in its place. L: Item is locked E: Item existed, as it would have been created, by an svn update. | [
"svn"
] | 318 | 545 | 227,216 | 9 | 0 | 2008-08-05T09:11:54.877000 | 2008-08-05T09:12:29.947000 |
2,041 | 2,310 | How do I create a branch? | How do I create a branch in SVN? | Branching in Subversion is facilitated by a very very light and efficient copying facility. Branching and tagging are effectively the same. Just copy a whole folder in the repository to somewhere else in the repository using the svn copy command. Basically this means that it is by convention what copying a folder means - whether it be a backup, tag, branch or whatever. Depending upon how you want to think about things (normally depending upon which SCM tool you have used in the past) you need to set up a folder structure within your repository to support your style. Common styles are to have a bunch of folders at the top of your repository called tags, branches, trunk, etc. - that allows you to copy your whole trunk (or sub-sets) into the tags and/or branches folders. If you have more than one project you might want to replicate this kind of structure under each project: It can take a while to get used to the concept - but it works - just make sure you (and your team) are clear on the conventions that you are going to use. It is also a good idea to have a good naming convention - something that tells you why the branch/tag was made and whether it is still appropriate - consider ways of archiving branches that are obsolete. | How do I create a branch? How do I create a branch in SVN? | TITLE:
How do I create a branch?
QUESTION:
How do I create a branch in SVN?
ANSWER:
Branching in Subversion is facilitated by a very very light and efficient copying facility. Branching and tagging are effectively the same. Just copy a whole folder in the repository to somewhere else in the repository using the svn copy command. Basically this means that it is by convention what copying a folder means - whether it be a backup, tag, branch or whatever. Depending upon how you want to think about things (normally depending upon which SCM tool you have used in the past) you need to set up a folder structure within your repository to support your style. Common styles are to have a bunch of folders at the top of your repository called tags, branches, trunk, etc. - that allows you to copy your whole trunk (or sub-sets) into the tags and/or branches folders. If you have more than one project you might want to replicate this kind of structure under each project: It can take a while to get used to the concept - but it works - just make sure you (and your team) are clear on the conventions that you are going to use. It is also a good idea to have a good naming convention - something that tells you why the branch/tag was made and whether it is still appropriate - consider ways of archiving branches that are obsolete. | [
"svn",
"version-control",
"branch",
"branching-and-merging"
] | 671 | 377 | 702,296 | 10 | 0 | 2008-08-05T09:25:29 | 2008-08-05T13:40:20.777000 |
2,043 | 2,044 | Can a Windows dll retrieve its own filename? | A Windows process created from an exe file has access to the command string that invoked it, including its file's path and filename. eg. C:\MyApp\MyApp.exe --help. But this is not so for a DLL invoked via LoadLibrary. Does anyone know of a way for a function loaded via DLL to find out what its path and filename are? Specifically, I'm interested in a solution using the Delphi Programming Language, but I suspect that the answer would be pretty much the same for any language. | I think you're looking for GetModuleFileName. http://www.swissdelphicenter.ch/torry/showcode.php?id=143: { If you are working on a DLL and are interested in the filename of the DLL rather than the filename of the application, then you can use this function: }
function GetModuleName: string; var szFileName: array[0..MAX_PATH] of Char; begin FillChar(szFileName, SizeOf(szFileName), #0); GetModuleFileName(hInstance, szFileName, MAX_PATH); Result:= szFileName; end; Untested though, been some time since I worked with Delphi:) | Can a Windows dll retrieve its own filename? A Windows process created from an exe file has access to the command string that invoked it, including its file's path and filename. eg. C:\MyApp\MyApp.exe --help. But this is not so for a DLL invoked via LoadLibrary. Does anyone know of a way for a function loaded via DLL to find out what its path and filename are? Specifically, I'm interested in a solution using the Delphi Programming Language, but I suspect that the answer would be pretty much the same for any language. | TITLE:
Can a Windows dll retrieve its own filename?
QUESTION:
A Windows process created from an exe file has access to the command string that invoked it, including its file's path and filename. eg. C:\MyApp\MyApp.exe --help. But this is not so for a DLL invoked via LoadLibrary. Does anyone know of a way for a function loaded via DLL to find out what its path and filename are? Specifically, I'm interested in a solution using the Delphi Programming Language, but I suspect that the answer would be pretty much the same for any language.
ANSWER:
I think you're looking for GetModuleFileName. http://www.swissdelphicenter.ch/torry/showcode.php?id=143: { If you are working on a DLL and are interested in the filename of the DLL rather than the filename of the application, then you can use this function: }
function GetModuleName: string; var szFileName: array[0..MAX_PATH] of Char; begin FillChar(szFileName, SizeOf(szFileName), #0); GetModuleFileName(hInstance, szFileName, MAX_PATH); Result:= szFileName; end; Untested though, been some time since I worked with Delphi:) | [
"windows",
"delphi",
"winapi",
"dll",
"path"
] | 34 | 41 | 10,492 | 2 | 0 | 2008-08-05T09:34:49.073000 | 2008-08-05T09:37:13.577000 |
2,046 | 7,641 | How do I unit test persistence? | As a novice in practicing test-driven development, I often end up in a quandary as to how to unit test persistence to a database. I know that technically this would be an integration test (not a unit test), but I want to find out the best strategies for the following: Testing queries. Testing inserts. How do I know that the insert that has gone wrong if it fails? I can test it by inserting and then querying, but how can I know that the query wasn't wrong? Testing updates and deletes -- same as testing inserts What are the best practices for doing these? Regarding testing SQL: I am aware that this could be done, but if I use an O/R Mapper like NHibernate, it attaches some naming warts in the aliases used for the output queries, and as that is somewhat unpredictable I'm not sure I could test for that. Should I just, abandon everything and simply trust NHibernate? I'm not sure that's prudent. | Look into DB Unit. It is a Java library, but there must be a C# equivalent. It lets you prepare the database with a set of data so that you know what is in the database, then you can interface with DB Unit to see what is in the database. It can run against many database systems, so you can use your actual database setup, or use something else, like HSQL in Java (a Java database implementation with an in memory option). If you want to test that your code is using the database properly (which you most likely should be doing), then this is the way to go to isolate each test and ensure the database has expected data prepared. | How do I unit test persistence? As a novice in practicing test-driven development, I often end up in a quandary as to how to unit test persistence to a database. I know that technically this would be an integration test (not a unit test), but I want to find out the best strategies for the following: Testing queries. Testing inserts. How do I know that the insert that has gone wrong if it fails? I can test it by inserting and then querying, but how can I know that the query wasn't wrong? Testing updates and deletes -- same as testing inserts What are the best practices for doing these? Regarding testing SQL: I am aware that this could be done, but if I use an O/R Mapper like NHibernate, it attaches some naming warts in the aliases used for the output queries, and as that is somewhat unpredictable I'm not sure I could test for that. Should I just, abandon everything and simply trust NHibernate? I'm not sure that's prudent. | TITLE:
How do I unit test persistence?
QUESTION:
As a novice in practicing test-driven development, I often end up in a quandary as to how to unit test persistence to a database. I know that technically this would be an integration test (not a unit test), but I want to find out the best strategies for the following: Testing queries. Testing inserts. How do I know that the insert that has gone wrong if it fails? I can test it by inserting and then querying, but how can I know that the query wasn't wrong? Testing updates and deletes -- same as testing inserts What are the best practices for doing these? Regarding testing SQL: I am aware that this could be done, but if I use an O/R Mapper like NHibernate, it attaches some naming warts in the aliases used for the output queries, and as that is somewhat unpredictable I'm not sure I could test for that. Should I just, abandon everything and simply trust NHibernate? I'm not sure that's prudent.
ANSWER:
Look into DB Unit. It is a Java library, but there must be a C# equivalent. It lets you prepare the database with a set of data so that you know what is in the database, then you can interface with DB Unit to see what is in the database. It can run against many database systems, so you can use your actual database setup, or use something else, like HSQL in Java (a Java database implementation with an in memory option). If you want to test that your code is using the database properly (which you most likely should be doing), then this is the way to go to isolate each test and ensure the database has expected data prepared. | [
"sql-server",
"unit-testing",
"tdd"
] | 50 | 18 | 9,373 | 10 | 0 | 2008-08-05T09:43:01.257000 | 2008-08-11T09:40:44.607000 |
2,048 | 2,080 | Monitor a specific RSS | For all the RSS feeds I subscribe to I use Google Reader, which I love. I do however have a couple of specific RSS feeds that I'd like to be notified of as soon as they get updated (say, for example, an RSS feed for a forum I like to monitor and respond to as quickly as possible). Are there any tools out there for this kind of monitoring which also have some kind of alert functionality (for example, a prompt window)? I've tried Simbolic RSS Alert but I found it a bit buggy and couldn't get it to alert me as often as I liked. Suggestions? Or perhaps a different experience with Simbolic? | If you have access to Microsoft Outlook 2007 or Thunderbird, these email clients allow you to add RSS feeds in the same way you would add an email account. I use Google Reader generally but when I want to keep up-to-date with something specific, I add the RSS feed to Outlook and it arrives in my inbox as if it was an email. | Monitor a specific RSS For all the RSS feeds I subscribe to I use Google Reader, which I love. I do however have a couple of specific RSS feeds that I'd like to be notified of as soon as they get updated (say, for example, an RSS feed for a forum I like to monitor and respond to as quickly as possible). Are there any tools out there for this kind of monitoring which also have some kind of alert functionality (for example, a prompt window)? I've tried Simbolic RSS Alert but I found it a bit buggy and couldn't get it to alert me as often as I liked. Suggestions? Or perhaps a different experience with Simbolic? | TITLE:
Monitor a specific RSS
QUESTION:
For all the RSS feeds I subscribe to I use Google Reader, which I love. I do however have a couple of specific RSS feeds that I'd like to be notified of as soon as they get updated (say, for example, an RSS feed for a forum I like to monitor and respond to as quickly as possible). Are there any tools out there for this kind of monitoring which also have some kind of alert functionality (for example, a prompt window)? I've tried Simbolic RSS Alert but I found it a bit buggy and couldn't get it to alert me as often as I liked. Suggestions? Or perhaps a different experience with Simbolic?
ANSWER:
If you have access to Microsoft Outlook 2007 or Thunderbird, these email clients allow you to add RSS feeds in the same way you would add an email account. I use Google Reader generally but when I want to keep up-to-date with something specific, I add the RSS feed to Outlook and it arrives in my inbox as if it was an email. | [
"rss"
] | 13 | 4 | 4,075 | 9 | 0 | 2008-08-05T09:45:41.377000 | 2008-08-05T10:50:35.393000 |
2,056 | 101,561 | What are MVP and MVC and what is the difference? | When looking beyond the RAD (drag-drop and configure) way of building user interfaces that many tools encourage you are likely to come across three design patterns called Model-View-Controller, Model-View-Presenter and Model-View-ViewModel. My question has three parts to it: What issues do these patterns address? How are they similar? How are they different? | Model-View-Presenter In MVP, the Presenter contains the UI business logic for the View. All invocations from the View delegate directly to the Presenter. The Presenter is also decoupled directly from the View and talks to it through an interface. This is to allow mocking of the View in a unit test. One common attribute of MVP is that there has to be a lot of two-way dispatching. For example, when someone clicks the "Save" button, the event handler delegates to the Presenter's "OnSave" method. Once the save is completed, the Presenter will then call back the View through its interface so that the View can display that the save has completed. MVP tends to be a very natural pattern for achieving separated presentation in WebForms. The reason is that the View is always created first by the ASP.NET runtime. You can find out more about both variants. Two primary variations Passive View: The View is as dumb as possible and contains almost zero logic. A Presenter is a middle man that talks to the View and the Model. The View and Model are completely shielded from one another. The Model may raise events, but the Presenter subscribes to them for updating the View. In Passive View there is no direct data binding, instead, the View exposes setter properties that the Presenter uses to set the data. All state is managed in the Presenter and not the View. Pro: maximum testability surface; clean separation of the View and Model Con: more work (for example all the setter properties) as you are doing all the data binding yourself. Supervising Controller: The Presenter handles user gestures. The View binds to the Model directly through data binding. In this case, it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation, etc. Pro: by leveraging data binding the amount of code is reduced. Con: there's a less testable surface (because of data binding), and there's less encapsulation in the View since it talks directly to the Model. Model-View-Controller In the MVC, the Controller is responsible for determining which View to display in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View correlates with a call to a Controller along with an action. In the web, each action involves a call to a URL on the other side of which there is a Controller who responds. Once that Controller has completed its processing, it will return the correct View. The sequence continues in that manner throughout the life of the application: Action in the View -> Call to Controller -> Controller Logic -> Controller returns the View. One other big difference about MVC is that the View does not directly bind to the Model. The view simply renders and is completely stateless. In implementations of MVC, the View usually will not have any logic in the code behind. This is contrary to MVP where it is absolutely necessary because, if the View does not delegate to the Presenter, it will never get called. Presentation Model One other pattern to look at is the Presentation Model pattern. In this pattern, there is no Presenter. Instead, the View binds directly to a Presentation Model. The Presentation Model is a Model crafted specifically for the View. This means this Model can expose properties that one would never put on a domain model as it would be a violation of separation-of-concerns. In this case, the Presentation Model binds to the domain model and may subscribe to events coming from that Model. The View then subscribes to events coming from the Presentation Model and updates itself accordingly. The Presentation Model can expose commands which the view uses for invoking actions. The advantage of this approach is that you can essentially remove the code-behind altogether as the PM completely encapsulates all of the behavior for the view. This pattern is a very strong candidate for use in WPF applications and is also called Model-View-ViewModel. There is a MSDN article about the Presentation Model and a section in the Composite Application Guidance for WPF (former Prism) about Separated Presentation Patterns | What are MVP and MVC and what is the difference? When looking beyond the RAD (drag-drop and configure) way of building user interfaces that many tools encourage you are likely to come across three design patterns called Model-View-Controller, Model-View-Presenter and Model-View-ViewModel. My question has three parts to it: What issues do these patterns address? How are they similar? How are they different? | TITLE:
What are MVP and MVC and what is the difference?
QUESTION:
When looking beyond the RAD (drag-drop and configure) way of building user interfaces that many tools encourage you are likely to come across three design patterns called Model-View-Controller, Model-View-Presenter and Model-View-ViewModel. My question has three parts to it: What issues do these patterns address? How are they similar? How are they different?
ANSWER:
Model-View-Presenter In MVP, the Presenter contains the UI business logic for the View. All invocations from the View delegate directly to the Presenter. The Presenter is also decoupled directly from the View and talks to it through an interface. This is to allow mocking of the View in a unit test. One common attribute of MVP is that there has to be a lot of two-way dispatching. For example, when someone clicks the "Save" button, the event handler delegates to the Presenter's "OnSave" method. Once the save is completed, the Presenter will then call back the View through its interface so that the View can display that the save has completed. MVP tends to be a very natural pattern for achieving separated presentation in WebForms. The reason is that the View is always created first by the ASP.NET runtime. You can find out more about both variants. Two primary variations Passive View: The View is as dumb as possible and contains almost zero logic. A Presenter is a middle man that talks to the View and the Model. The View and Model are completely shielded from one another. The Model may raise events, but the Presenter subscribes to them for updating the View. In Passive View there is no direct data binding, instead, the View exposes setter properties that the Presenter uses to set the data. All state is managed in the Presenter and not the View. Pro: maximum testability surface; clean separation of the View and Model Con: more work (for example all the setter properties) as you are doing all the data binding yourself. Supervising Controller: The Presenter handles user gestures. The View binds to the Model directly through data binding. In this case, it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation, etc. Pro: by leveraging data binding the amount of code is reduced. Con: there's a less testable surface (because of data binding), and there's less encapsulation in the View since it talks directly to the Model. Model-View-Controller In the MVC, the Controller is responsible for determining which View to display in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View correlates with a call to a Controller along with an action. In the web, each action involves a call to a URL on the other side of which there is a Controller who responds. Once that Controller has completed its processing, it will return the correct View. The sequence continues in that manner throughout the life of the application: Action in the View -> Call to Controller -> Controller Logic -> Controller returns the View. One other big difference about MVC is that the View does not directly bind to the Model. The view simply renders and is completely stateless. In implementations of MVC, the View usually will not have any logic in the code behind. This is contrary to MVP where it is absolutely necessary because, if the View does not delegate to the Presenter, it will never get called. Presentation Model One other pattern to look at is the Presentation Model pattern. In this pattern, there is no Presenter. Instead, the View binds directly to a Presentation Model. The Presentation Model is a Model crafted specifically for the View. This means this Model can expose properties that one would never put on a domain model as it would be a violation of separation-of-concerns. In this case, the Presentation Model binds to the domain model and may subscribe to events coming from that Model. The View then subscribes to events coming from the Presentation Model and updates itself accordingly. The Presentation Model can expose commands which the view uses for invoking actions. The advantage of this approach is that you can essentially remove the code-behind altogether as the PM completely encapsulates all of the behavior for the view. This pattern is a very strong candidate for use in WPF applications and is also called Model-View-ViewModel. There is a MSDN article about the Presentation Model and a section in the Composite Application Guidance for WPF (former Prism) about Separated Presentation Patterns | [
"user-interface",
"model-view-controller",
"design-patterns",
"terminology",
"mvp"
] | 2,368 | 2,130 | 570,601 | 24 | 0 | 2008-08-05T10:06:33.020000 | 2008-09-19T12:46:52.687000 |
2,120 | 2,382 | Convert HashBytes to VarChar | I want to get the MD5 Hash of a string value in SQL Server 2005. I do this with the following command: SELECT HashBytes('MD5', 'HelloWorld') However, this returns a VarBinary instead of a VarChar value. If I attempt to convert 0x68E109F0F40CA72A15E05CC22786F8E6 into a VarChar I get há ðô§*à\Â'†øæ instead of 68E109F0F40CA72A15E05CC22786F8E6. Is there any SQL-based solution? Yes | I have found the solution else where: SELECT SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('MD5', 'HelloWorld')), 3, 32) | Convert HashBytes to VarChar I want to get the MD5 Hash of a string value in SQL Server 2005. I do this with the following command: SELECT HashBytes('MD5', 'HelloWorld') However, this returns a VarBinary instead of a VarChar value. If I attempt to convert 0x68E109F0F40CA72A15E05CC22786F8E6 into a VarChar I get há ðô§*à\Â'†øæ instead of 68E109F0F40CA72A15E05CC22786F8E6. Is there any SQL-based solution? Yes | TITLE:
Convert HashBytes to VarChar
QUESTION:
I want to get the MD5 Hash of a string value in SQL Server 2005. I do this with the following command: SELECT HashBytes('MD5', 'HelloWorld') However, this returns a VarBinary instead of a VarChar value. If I attempt to convert 0x68E109F0F40CA72A15E05CC22786F8E6 into a VarChar I get há ðô§*à\Â'†øæ instead of 68E109F0F40CA72A15E05CC22786F8E6. Is there any SQL-based solution? Yes
ANSWER:
I have found the solution else where: SELECT SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('MD5', 'HelloWorld')), 3, 32) | [
"sql",
"sql-server"
] | 141 | 163 | 165,677 | 7 | 0 | 2008-08-05T11:49:11.360000 | 2008-08-05T14:26:41.870000 |
2,123 | 2,223 | How do I make a checkbox toggle from clicking on the text label as well? | Checkboxes in HTML forms don't have implicit labels with them. Adding an explicit label (some text) next to it doesn't toggle the checkbox. How do I make a checkbox toggle from clicking on the text label as well? | Set the CSS display property for the label to be a block element and use that instead of your div - it keeps the semantic meaning of a label while allowing whatever styling you like. For example: label {
width: 100px;
height: 100px;
display: block;
background-color: #e0e0ff;
} A ticky box! | How do I make a checkbox toggle from clicking on the text label as well? Checkboxes in HTML forms don't have implicit labels with them. Adding an explicit label (some text) next to it doesn't toggle the checkbox. How do I make a checkbox toggle from clicking on the text label as well? | TITLE:
How do I make a checkbox toggle from clicking on the text label as well?
QUESTION:
Checkboxes in HTML forms don't have implicit labels with them. Adding an explicit label (some text) next to it doesn't toggle the checkbox. How do I make a checkbox toggle from clicking on the text label as well?
ANSWER:
Set the CSS display property for the label to be a block element and use that instead of your div - it keeps the semantic meaning of a label while allowing whatever styling you like. For example: label {
width: 100px;
height: 100px;
display: block;
background-color: #e0e0ff;
} A ticky box! | [
"html",
"checkbox"
] | 47 | 26 | 32,530 | 8 | 0 | 2008-08-05T11:51:16.507000 | 2008-08-05T12:52:50.047000 |
2,134 | 2,183 | Do sealed classes really offer performance benefits? | I have come across a lot of optimization tips which say that you should mark your classes as sealed to get extra performance benefits. I ran some tests to check the performance differential and found none. Am I doing something wrong? Am I missing the case where sealed classes will give better results? Has anyone run tests and seen a difference? | The JITter will sometimes use non-virtual calls to methods in sealed classes since there is no way they can be extended further. There are complex rules regarding calling type, virtual/nonvirtual, and I don't know them all so I can't really outline them for you, but if you google for sealed classes and virtual methods you might find some articles on the topic. Note that any kind of performance benefit you would obtain from this level of optimization should be regarded as last-resort, always optimize on the algorithmic level before you optimize on the code-level. Here's one link mentioning this: Rambling on the sealed keyword | Do sealed classes really offer performance benefits? I have come across a lot of optimization tips which say that you should mark your classes as sealed to get extra performance benefits. I ran some tests to check the performance differential and found none. Am I doing something wrong? Am I missing the case where sealed classes will give better results? Has anyone run tests and seen a difference? | TITLE:
Do sealed classes really offer performance benefits?
QUESTION:
I have come across a lot of optimization tips which say that you should mark your classes as sealed to get extra performance benefits. I ran some tests to check the performance differential and found none. Am I doing something wrong? Am I missing the case where sealed classes will give better results? Has anyone run tests and seen a difference?
ANSWER:
The JITter will sometimes use non-virtual calls to methods in sealed classes since there is no way they can be extended further. There are complex rules regarding calling type, virtual/nonvirtual, and I don't know them all so I can't really outline them for you, but if you google for sealed classes and virtual methods you might find some articles on the topic. Note that any kind of performance benefit you would obtain from this level of optimization should be regarded as last-resort, always optimize on the algorithmic level before you optimize on the code-level. Here's one link mentioning this: Rambling on the sealed keyword | [
".net",
"performance",
"optimization"
] | 171 | 65 | 42,794 | 13 | 0 | 2008-08-05T12:00:28.733000 | 2008-08-05T12:32:40.510000 |
2,138 | 2,147 | LINQ on the .NET 2.0 Runtime | Can a LINQ enabled app run on a machine that only has the.NET 2.0 runtime installed? In theory, LINQ is nothing more than syntactic sugar, and the resulting IL code should look the same as it would have in.NET 2.0. How can I write LINQ without using the.NET 3.5 libraries? Will it run on.NET 2.0? | There are some "Hacks" that involve using a System.Core.dll from the 3.5 Framework to make it run with.net 2.0, but personally I would not want use such a somewhat shaky foundation. See here: LINQ support on.NET 2.0 Create a new console application Keep only System and System.Core as referenced assemblies Set Copy Local to true for System.Core, because it does not exist in.NET 2.0 Use a LINQ query in the Main method. For example the one below. Build Copy all the bin output to a machine where only.NET 2.0 is installed Run (Requires.net 2.0 SP1 and I have no idea if bundling the System.Core.dll violates the EULA) | LINQ on the .NET 2.0 Runtime Can a LINQ enabled app run on a machine that only has the.NET 2.0 runtime installed? In theory, LINQ is nothing more than syntactic sugar, and the resulting IL code should look the same as it would have in.NET 2.0. How can I write LINQ without using the.NET 3.5 libraries? Will it run on.NET 2.0? | TITLE:
LINQ on the .NET 2.0 Runtime
QUESTION:
Can a LINQ enabled app run on a machine that only has the.NET 2.0 runtime installed? In theory, LINQ is nothing more than syntactic sugar, and the resulting IL code should look the same as it would have in.NET 2.0. How can I write LINQ without using the.NET 3.5 libraries? Will it run on.NET 2.0?
ANSWER:
There are some "Hacks" that involve using a System.Core.dll from the 3.5 Framework to make it run with.net 2.0, but personally I would not want use such a somewhat shaky foundation. See here: LINQ support on.NET 2.0 Create a new console application Keep only System and System.Core as referenced assemblies Set Copy Local to true for System.Core, because it does not exist in.NET 2.0 Use a LINQ query in the Main method. For example the one below. Build Copy all the bin output to a machine where only.NET 2.0 is installed Run (Requires.net 2.0 SP1 and I have no idea if bundling the System.Core.dll violates the EULA) | [
".net",
"linq",
".net-3.5",
".net-2.0",
"clr"
] | 61 | 34 | 57,342 | 8 | 0 | 2008-08-05T12:03:10.927000 | 2008-08-05T12:07:41.603000 |
2,154 | 2,335 | Developing for ASP.NET-MVC without Visual Studio | Instead of writing my ASP.NET C# applications in Visual Studio, I used my favorite text editor UltraEdit32. Is there any way I can implement MVC without the use of VS? | There is nothing VS specific with the MVC framework - it is just a bunch of DLLs that you can use. The wizards in VS just build you a quick-start framework. ASP.NET MVC is "bin-deployable" - there is nothing too clever to set up on the server either - just point the wildcard ISAPI filter to ASP.NET | Developing for ASP.NET-MVC without Visual Studio Instead of writing my ASP.NET C# applications in Visual Studio, I used my favorite text editor UltraEdit32. Is there any way I can implement MVC without the use of VS? | TITLE:
Developing for ASP.NET-MVC without Visual Studio
QUESTION:
Instead of writing my ASP.NET C# applications in Visual Studio, I used my favorite text editor UltraEdit32. Is there any way I can implement MVC without the use of VS?
ANSWER:
There is nothing VS specific with the MVC framework - it is just a bunch of DLLs that you can use. The wizards in VS just build you a quick-start framework. ASP.NET MVC is "bin-deployable" - there is nothing too clever to set up on the server either - just point the wildcard ISAPI filter to ASP.NET | [
"c#",
"asp.net-mvc",
"visual-studio"
] | 31 | 12 | 6,383 | 4 | 0 | 2008-08-05T12:13:40.483000 | 2008-08-05T13:58:52.473000 |
2,155 | 2,928 | How do I define custom web.config sections with potential child elements and attributes for the properties? | The web applications I develop often require co-dependent configuration settings and there are also settings that have to change as we move between each of our environments. All our settings are currently simple key-value pairs but it would be useful to create custom config sections so that it is obvious when two values need to change together or when the settings need to change for an environment. What's the best way to create custom config sections and are there any special considerations to make when retrieving the values? | Using attributes, child config sections and constraints There is also the possibility to use attributes which automatically takes care of the plumbing, as well as providing the ability to easily add constraints. I here present an example from code I use myself in one of my sites. With a constraint I dictate the maximum amount of disk space any one user is allowed to use. MailCenterConfiguration.cs: namespace Ani {
public sealed class MailCenterConfiguration: ConfigurationSection { [ConfigurationProperty("userDiskSpace", IsRequired = true)] [IntegerValidator(MinValue = 0, MaxValue = 1000000)] public int UserDiskSpace { get { return (int)base["userDiskSpace"]; } set { base["userDiskSpace"] = value; } } } } This is set up in web.config like so... Child elements The child xml element mail is created in the same.cs file as the one above. Here I've added constraints on the port. If the port is assigned a value not in this range the runtime will complain when the config is loaded. MailCenterConfiguration.cs: public sealed class MailCenterConfiguration: ConfigurationSection { [ConfigurationProperty("mail", IsRequired=true)] public MailElement Mail { get { return (MailElement)base["mail"]; } set { base["mail"] = value; } }
public class MailElement: ConfigurationElement { [ConfigurationProperty("host", IsRequired = true)] public string Host { get { return (string)base["host"]; } set { base["host"] = value; } }
[ConfigurationProperty("port", IsRequired = true)] [IntegerValidator(MinValue = 0, MaxValue = 65535)] public int Port { get { return (int)base["port"]; } set { base["port"] = value; } } Use To then use it practically in code, all you have to do is instantiate the MailCenterConfigurationObject, this will automatically read the relevant sections from web.config. MailCenterConfiguration.cs private static MailCenterConfiguration instance = null; public static MailCenterConfiguration Instance { get { if (instance == null) { instance = (MailCenterConfiguration)WebConfigurationManager.GetSection("mailCenter"); }
return instance; } } AnotherFile.cs public void SendMail() { MailCenterConfiguration conf = MailCenterConfiguration.Instance; SmtpClient smtpClient = new SmtpClient(conf.Mail.Host, conf.Mail.Port); } Check for validity I previously mentioned that the runtime will complain when the configuration is loaded and some data does not comply to the rules you have set up (e.g. in MailCenterConfiguration.cs). I tend to want to know these things as soon as possible when my site fires up. One way to solve this is load the configuration in _Global.asax.cx.Application_Start_, if the configuration is invalid you will be notified of this with the means of an exception. Your site won't start and instead you will be presented detailed exception information in the Yellow screen of death. Global.asax.cs protected void Application_ Start(object sender, EventArgs e) { MailCenterConfiguration.Instance; } | How do I define custom web.config sections with potential child elements and attributes for the properties? The web applications I develop often require co-dependent configuration settings and there are also settings that have to change as we move between each of our environments. All our settings are currently simple key-value pairs but it would be useful to create custom config sections so that it is obvious when two values need to change together or when the settings need to change for an environment. What's the best way to create custom config sections and are there any special considerations to make when retrieving the values? | TITLE:
How do I define custom web.config sections with potential child elements and attributes for the properties?
QUESTION:
The web applications I develop often require co-dependent configuration settings and there are also settings that have to change as we move between each of our environments. All our settings are currently simple key-value pairs but it would be useful to create custom config sections so that it is obvious when two values need to change together or when the settings need to change for an environment. What's the best way to create custom config sections and are there any special considerations to make when retrieving the values?
ANSWER:
Using attributes, child config sections and constraints There is also the possibility to use attributes which automatically takes care of the plumbing, as well as providing the ability to easily add constraints. I here present an example from code I use myself in one of my sites. With a constraint I dictate the maximum amount of disk space any one user is allowed to use. MailCenterConfiguration.cs: namespace Ani {
public sealed class MailCenterConfiguration: ConfigurationSection { [ConfigurationProperty("userDiskSpace", IsRequired = true)] [IntegerValidator(MinValue = 0, MaxValue = 1000000)] public int UserDiskSpace { get { return (int)base["userDiskSpace"]; } set { base["userDiskSpace"] = value; } } } } This is set up in web.config like so... Child elements The child xml element mail is created in the same.cs file as the one above. Here I've added constraints on the port. If the port is assigned a value not in this range the runtime will complain when the config is loaded. MailCenterConfiguration.cs: public sealed class MailCenterConfiguration: ConfigurationSection { [ConfigurationProperty("mail", IsRequired=true)] public MailElement Mail { get { return (MailElement)base["mail"]; } set { base["mail"] = value; } }
public class MailElement: ConfigurationElement { [ConfigurationProperty("host", IsRequired = true)] public string Host { get { return (string)base["host"]; } set { base["host"] = value; } }
[ConfigurationProperty("port", IsRequired = true)] [IntegerValidator(MinValue = 0, MaxValue = 65535)] public int Port { get { return (int)base["port"]; } set { base["port"] = value; } } Use To then use it practically in code, all you have to do is instantiate the MailCenterConfigurationObject, this will automatically read the relevant sections from web.config. MailCenterConfiguration.cs private static MailCenterConfiguration instance = null; public static MailCenterConfiguration Instance { get { if (instance == null) { instance = (MailCenterConfiguration)WebConfigurationManager.GetSection("mailCenter"); }
return instance; } } AnotherFile.cs public void SendMail() { MailCenterConfiguration conf = MailCenterConfiguration.Instance; SmtpClient smtpClient = new SmtpClient(conf.Mail.Host, conf.Mail.Port); } Check for validity I previously mentioned that the runtime will complain when the configuration is loaded and some data does not comply to the rules you have set up (e.g. in MailCenterConfiguration.cs). I tend to want to know these things as soon as possible when my site fires up. One way to solve this is load the configuration in _Global.asax.cx.Application_Start_, if the configuration is invalid you will be notified of this with the means of an exception. Your site won't start and instead you will be presented detailed exception information in the Yellow screen of death. Global.asax.cs protected void Application_ Start(object sender, EventArgs e) { MailCenterConfiguration.Instance; } | [
"asp.net"
] | 72 | 84 | 44,592 | 5 | 0 | 2008-08-05T12:13:40.640000 | 2008-08-05T22:17:29.610000 |
2,158 | 2,245 | Creating a custom JButton in Java | Is there a way to create a JButton with your own button graphic and not just with an image inside the button? If not, is there another way to create a custom JButton in java? | When I was first learning Java we had to make Yahtzee and I thought it would be cool to create custom Swing components and containers instead of just drawing everything on one JPanel. The benefit of extending Swing components, of course, is to have the ability to add support for keyboard shortcuts and other accessibility features that you can't do just by having a paint() method print a pretty picture. It may not be done the best way however, but it may be a good starting point for you. Edit 8/6 - If it wasn't apparent from the images, each Die is a button you can click. This will move it to the DiceContainer below. Looking at the source code you can see that each Die button is drawn dynamically, based on its value. Here are the basic steps: Create a class that extends JComponent Call parent constructor super() in your constructors Make sure you class implements MouseListener Put this in the constructor: enableInputMethods(true); addMouseListener(this); Override these methods: public Dimension getPreferredSize() public Dimension getMinimumSize() public Dimension getMaximumSize() Override this method: public void paintComponent(Graphics g) The amount of space you have to work with when drawing your button is defined by getPreferredSize(), assuming getMinimumSize() and getMaximumSize() return the same value. I haven't experimented too much with this but, depending on the layout you use for your GUI your button could look completely different. And finally, the source code. In case I missed anything. | Creating a custom JButton in Java Is there a way to create a JButton with your own button graphic and not just with an image inside the button? If not, is there another way to create a custom JButton in java? | TITLE:
Creating a custom JButton in Java
QUESTION:
Is there a way to create a JButton with your own button graphic and not just with an image inside the button? If not, is there another way to create a custom JButton in java?
ANSWER:
When I was first learning Java we had to make Yahtzee and I thought it would be cool to create custom Swing components and containers instead of just drawing everything on one JPanel. The benefit of extending Swing components, of course, is to have the ability to add support for keyboard shortcuts and other accessibility features that you can't do just by having a paint() method print a pretty picture. It may not be done the best way however, but it may be a good starting point for you. Edit 8/6 - If it wasn't apparent from the images, each Die is a button you can click. This will move it to the DiceContainer below. Looking at the source code you can see that each Die button is drawn dynamically, based on its value. Here are the basic steps: Create a class that extends JComponent Call parent constructor super() in your constructors Make sure you class implements MouseListener Put this in the constructor: enableInputMethods(true); addMouseListener(this); Override these methods: public Dimension getPreferredSize() public Dimension getMinimumSize() public Dimension getMaximumSize() Override this method: public void paintComponent(Graphics g) The amount of space you have to work with when drawing your button is defined by getPreferredSize(), assuming getMinimumSize() and getMaximumSize() return the same value. I haven't experimented too much with this but, depending on the layout you use for your GUI your button could look completely different. And finally, the source code. In case I missed anything. | [
"java",
"swing",
"jbutton"
] | 104 | 99 | 114,853 | 5 | 0 | 2008-08-05T12:15:08.283000 | 2008-08-05T13:03:43.707000 |
2,196 | 2,373 | Easy way to AJAX WebControls | I've got a web application that I'm trying to optimize. Some of the controls are hidden in dialog-style DIVs. So, I'd like to have them load in via AJAX only when the user wants to see them. This is fine for controls that are mostly literal-based (various menus and widgets), but when I have what I call "dirty" controls - ones that write extensive information to the ViewState, put tons of CSS or script on the page, require lots of references, etc - these are seemingly impossible to move "out of page", especially considering how ASP.NET will react on postback. I was considering some kind of step where I override Render, find markers for the bits I want to move out and put AJAX placeholders in there, but not only does the server overhead seem extreme, it also feels like a complete hack. Besides, the key element here is the dialog boxes that contain forms with validation controls on them, and I can't imagine how I would move the controls and their required scripts. In my fevered imagination, I want to do this: AJAXifier.AJAXify(ctlEditForm); Sadly, I know this is a dream. How close can I really get to a quick-and-easy AJAXification without causing too much load on the server? | Check out the RadAjax control from Telerik - it allows you to avoid using UpdatePanels, and limit the amount of info passed back and forth between server and client by declaring direct relationships between calling controls, and controls that should be "Ajaxified" when the calling controls submit postbacks. | Easy way to AJAX WebControls I've got a web application that I'm trying to optimize. Some of the controls are hidden in dialog-style DIVs. So, I'd like to have them load in via AJAX only when the user wants to see them. This is fine for controls that are mostly literal-based (various menus and widgets), but when I have what I call "dirty" controls - ones that write extensive information to the ViewState, put tons of CSS or script on the page, require lots of references, etc - these are seemingly impossible to move "out of page", especially considering how ASP.NET will react on postback. I was considering some kind of step where I override Render, find markers for the bits I want to move out and put AJAX placeholders in there, but not only does the server overhead seem extreme, it also feels like a complete hack. Besides, the key element here is the dialog boxes that contain forms with validation controls on them, and I can't imagine how I would move the controls and their required scripts. In my fevered imagination, I want to do this: AJAXifier.AJAXify(ctlEditForm); Sadly, I know this is a dream. How close can I really get to a quick-and-easy AJAXification without causing too much load on the server? | TITLE:
Easy way to AJAX WebControls
QUESTION:
I've got a web application that I'm trying to optimize. Some of the controls are hidden in dialog-style DIVs. So, I'd like to have them load in via AJAX only when the user wants to see them. This is fine for controls that are mostly literal-based (various menus and widgets), but when I have what I call "dirty" controls - ones that write extensive information to the ViewState, put tons of CSS or script on the page, require lots of references, etc - these are seemingly impossible to move "out of page", especially considering how ASP.NET will react on postback. I was considering some kind of step where I override Render, find markers for the bits I want to move out and put AJAX placeholders in there, but not only does the server overhead seem extreme, it also feels like a complete hack. Besides, the key element here is the dialog boxes that contain forms with validation controls on them, and I can't imagine how I would move the controls and their required scripts. In my fevered imagination, I want to do this: AJAXifier.AJAXify(ctlEditForm); Sadly, I know this is a dream. How close can I really get to a quick-and-easy AJAXification without causing too much load on the server?
ANSWER:
Check out the RadAjax control from Telerik - it allows you to avoid using UpdatePanels, and limit the amount of info passed back and forth between server and client by declaring direct relationships between calling controls, and controls that should be "Ajaxified" when the calling controls submit postbacks. | [
"asp.net",
"ajax",
"web-controls"
] | 20 | 5 | 1,027 | 3 | 0 | 2008-08-05T12:40:30.680000 | 2008-08-05T14:19:26.860000 |
2,209 | 2,233 | How can I change the background of a masterpage from the code behind of a content page? | I specifically want to add the style of background-color to the tag of a master page, from the code behind (C#) of a content page that uses that master page. I have different content pages that need to make the master page has different colors depending on which content page is loaded, so that the master page matches the content page's theme. I have a solution below: I'm looking for something more like: Master.Attributes.Add("style", "background-color: 2e6095"); Inside of the page load function of the content page. But I can't get the above line to work. I only need to change the background-color for the tag of the page. | What I would do for the particular case is: i. Define the body as a server side control ii. In your content aspx page, register the MasterPage with the register: <% MasterPageFile="..." %> iii. In the Content Page, you can now simply use Master.FindControl("masterpageBody") and have access to the control. Now, you can change whatever properties/style that you like! | How can I change the background of a masterpage from the code behind of a content page? I specifically want to add the style of background-color to the tag of a master page, from the code behind (C#) of a content page that uses that master page. I have different content pages that need to make the master page has different colors depending on which content page is loaded, so that the master page matches the content page's theme. I have a solution below: I'm looking for something more like: Master.Attributes.Add("style", "background-color: 2e6095"); Inside of the page load function of the content page. But I can't get the above line to work. I only need to change the background-color for the tag of the page. | TITLE:
How can I change the background of a masterpage from the code behind of a content page?
QUESTION:
I specifically want to add the style of background-color to the tag of a master page, from the code behind (C#) of a content page that uses that master page. I have different content pages that need to make the master page has different colors depending on which content page is loaded, so that the master page matches the content page's theme. I have a solution below: I'm looking for something more like: Master.Attributes.Add("style", "background-color: 2e6095"); Inside of the page load function of the content page. But I can't get the above line to work. I only need to change the background-color for the tag of the page.
ANSWER:
What I would do for the particular case is: i. Define the body as a server side control ii. In your content aspx page, register the MasterPage with the register: <% MasterPageFile="..." %> iii. In the Content Page, you can now simply use Master.FindControl("masterpageBody") and have access to the control. Now, you can change whatever properties/style that you like! | [
"c#",
"asp.net",
".net",
"master-pages"
] | 25 | 10 | 13,982 | 3 | 0 | 2008-08-05T12:46:45.003000 | 2008-08-05T12:56:54.220000 |
2,214 | 3,443 | What's the best way to implement BDD/TDD in .NET 2.0? | I'm looking to add a testing suite to my application, however I can't move to the newer testing frameworks for.NET 3.5. Does anyone have a suggestion about good testing frameworks to use? | We use MbUnit and Rihno Mocks and they prove to work very well together. When doing TDD you will almost certainly need to do some form of dependency injection, while this can be done manually, its worth looking at an IoC container such as Castle Windsor. It well worth looking at John Paul Bodhood's screen casts to get you started. JPB's Blog | What's the best way to implement BDD/TDD in .NET 2.0? I'm looking to add a testing suite to my application, however I can't move to the newer testing frameworks for.NET 3.5. Does anyone have a suggestion about good testing frameworks to use? | TITLE:
What's the best way to implement BDD/TDD in .NET 2.0?
QUESTION:
I'm looking to add a testing suite to my application, however I can't move to the newer testing frameworks for.NET 3.5. Does anyone have a suggestion about good testing frameworks to use?
ANSWER:
We use MbUnit and Rihno Mocks and they prove to work very well together. When doing TDD you will almost certainly need to do some form of dependency injection, while this can be done manually, its worth looking at an IoC container such as Castle Windsor. It well worth looking at John Paul Bodhood's screen casts to get you started. JPB's Blog | [
"c#",
".net",
"testing",
"tdd",
"bdd"
] | 26 | 9 | 3,198 | 12 | 0 | 2008-08-05T12:50:15.543000 | 2008-08-06T14:16:35.790000 |
2,222 | 8,753 | How can I unit test Flex applications from within the IDE or a build script? | I'm currently working on an application with a frontend written in Adobe Flex 3. I'm aware of FlexUnit but what I'd really like is a unit test runner for Ant/NAnt and a runner that integrates with the Flex Builder IDE (AKA Eclipse). Does one exist? Also, are there any other resources on how to do Flex development "the right way" besides the Cairngorm microarchitecture example? | The dpUint testing framework has a test runner built with AIR which can be integrated with a build script. There is also my FlexUnit automation kit which does more or less the same for FlexUnit. It has an Ant macro that makes it possible to run the tests as a part of an Ant script, for example: | How can I unit test Flex applications from within the IDE or a build script? I'm currently working on an application with a frontend written in Adobe Flex 3. I'm aware of FlexUnit but what I'd really like is a unit test runner for Ant/NAnt and a runner that integrates with the Flex Builder IDE (AKA Eclipse). Does one exist? Also, are there any other resources on how to do Flex development "the right way" besides the Cairngorm microarchitecture example? | TITLE:
How can I unit test Flex applications from within the IDE or a build script?
QUESTION:
I'm currently working on an application with a frontend written in Adobe Flex 3. I'm aware of FlexUnit but what I'd really like is a unit test runner for Ant/NAnt and a runner that integrates with the Flex Builder IDE (AKA Eclipse). Does one exist? Also, are there any other resources on how to do Flex development "the right way" besides the Cairngorm microarchitecture example?
ANSWER:
The dpUint testing framework has a test runner built with AIR which can be integrated with a build script. There is also my FlexUnit automation kit which does more or less the same for FlexUnit. It has an Ant macro that makes it possible to run the tests as a part of an Ant script, for example: | [
"apache-flex",
"eclipse",
"unit-testing",
"build-automation",
"cairngorm"
] | 18 | 5 | 2,752 | 4 | 0 | 2008-08-05T12:52:42.573000 | 2008-08-12T12:28:18.340000 |
2,232 | 2,400 | How to call shell commands from Ruby | How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby? | This explanation is based on a commented Ruby script from a friend of mine. If you want to improve the script, feel free to update it at the link. First, note that when Ruby calls out to a shell, it typically calls /bin/sh, not Bash. Some Bash syntax is not supported by /bin/sh on all systems. Here are ways to execute a shell script: cmd = "echo 'hi'" # Sample string that can be used Kernel#`, commonly called backticks – `cmd` This is like many other languages, including Bash, PHP, and Perl. Returns the result (i.e. standard output) of the shell command. Docs: http://ruby-doc.org/core/Kernel.html#method-i-60 value = `echo 'hi'` value = `#{cmd}` Built-in syntax, %x( cmd ) Following the x character is a delimiter, which can be any character. If the delimiter is one of the characters (, [, {, or <, the literal consists of the characters up to the matching closing delimiter, taking account of nested delimiter pairs. For all other delimiters, the literal comprises the characters up to the next occurrence of the delimiter character. String interpolation #{... } is allowed. Returns the result (i.e. standard output) of the shell command, just like the backticks. Docs: https://docs.ruby-lang.org/en/master/syntax/literals_rdoc.html#label-Percent+Strings value = %x( echo 'hi' ) value = %x[ #{cmd} ] Kernel#system Executes the given command in a subshell. Returns true if the command was found and run successfully, false otherwise. Docs: http://ruby-doc.org/core/Kernel.html#method-i-system wasGood = system( "echo 'hi'" ) wasGood = system( cmd ) Kernel#exec Replaces the current process by running the given external command. Returns none, the current process is replaced and never continues. Docs: http://ruby-doc.org/core/Kernel.html#method-i-exec exec( "echo 'hi'" ) exec( cmd ) # Note: this will never be reached because of the line above Here's some extra advice: $?, which is the same as $CHILD_STATUS, accesses the status of the last system executed command if you use the backticks, system() or %x{}. You can then access the exitstatus and pid properties: $?.exitstatus For more reading see: http://www.elctech.com/blog/i-m-in-ur-commandline-executin-ma-commands http://blog.jayfields.com/2006/06/ruby-kernel-system-exec-and-x.html http://tech.natemurray.com/2007/03/ruby-shell-commands.html | How to call shell commands from Ruby How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby? | TITLE:
How to call shell commands from Ruby
QUESTION:
How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby?
ANSWER:
This explanation is based on a commented Ruby script from a friend of mine. If you want to improve the script, feel free to update it at the link. First, note that when Ruby calls out to a shell, it typically calls /bin/sh, not Bash. Some Bash syntax is not supported by /bin/sh on all systems. Here are ways to execute a shell script: cmd = "echo 'hi'" # Sample string that can be used Kernel#`, commonly called backticks – `cmd` This is like many other languages, including Bash, PHP, and Perl. Returns the result (i.e. standard output) of the shell command. Docs: http://ruby-doc.org/core/Kernel.html#method-i-60 value = `echo 'hi'` value = `#{cmd}` Built-in syntax, %x( cmd ) Following the x character is a delimiter, which can be any character. If the delimiter is one of the characters (, [, {, or <, the literal consists of the characters up to the matching closing delimiter, taking account of nested delimiter pairs. For all other delimiters, the literal comprises the characters up to the next occurrence of the delimiter character. String interpolation #{... } is allowed. Returns the result (i.e. standard output) of the shell command, just like the backticks. Docs: https://docs.ruby-lang.org/en/master/syntax/literals_rdoc.html#label-Percent+Strings value = %x( echo 'hi' ) value = %x[ #{cmd} ] Kernel#system Executes the given command in a subshell. Returns true if the command was found and run successfully, false otherwise. Docs: http://ruby-doc.org/core/Kernel.html#method-i-system wasGood = system( "echo 'hi'" ) wasGood = system( cmd ) Kernel#exec Replaces the current process by running the given external command. Returns none, the current process is replaced and never continues. Docs: http://ruby-doc.org/core/Kernel.html#method-i-exec exec( "echo 'hi'" ) exec( cmd ) # Note: this will never be reached because of the line above Here's some extra advice: $?, which is the same as $CHILD_STATUS, accesses the status of the last system executed command if you use the backticks, system() or %x{}. You can then access the exitstatus and pid properties: $?.exitstatus For more reading see: http://www.elctech.com/blog/i-m-in-ur-commandline-executin-ma-commands http://blog.jayfields.com/2006/06/ruby-kernel-system-exec-and-x.html http://tech.natemurray.com/2007/03/ruby-shell-commands.html | [
"ruby",
"shell",
"interop"
] | 1,264 | 1,473 | 646,565 | 22 | 0 | 2008-08-05T12:56:52.770000 | 2008-08-05T14:42:45.927000 |
2,250 | 2,258 | Datatable vs Dataset | I currently use a DataTable to get results from a database which I can use in my code. However, many example on the web show using a DataSet instead and accessing the table(s) through the collections method. Is there any advantage, performance wise or otherwise, of using DataSets or DataTables as a storage method for SQL results? | It really depends on the sort of data you're bringing back. Since a DataSet is (in effect) just a collection of DataTable objects, you can return multiple distinct sets of data into a single, and therefore more manageable, object. Performance-wise, you're more likely to get inefficiency from unoptimized queries than from the "wrong" choice of.NET construct. At least, that's been my experience. | Datatable vs Dataset I currently use a DataTable to get results from a database which I can use in my code. However, many example on the web show using a DataSet instead and accessing the table(s) through the collections method. Is there any advantage, performance wise or otherwise, of using DataSets or DataTables as a storage method for SQL results? | TITLE:
Datatable vs Dataset
QUESTION:
I currently use a DataTable to get results from a database which I can use in my code. However, many example on the web show using a DataSet instead and accessing the table(s) through the collections method. Is there any advantage, performance wise or otherwise, of using DataSets or DataTables as a storage method for SQL results?
ANSWER:
It really depends on the sort of data you're bringing back. Since a DataSet is (in effect) just a collection of DataTable objects, you can return multiple distinct sets of data into a single, and therefore more manageable, object. Performance-wise, you're more likely to get inefficiency from unoptimized queries than from the "wrong" choice of.NET construct. At least, that's been my experience. | [
"c#",
"dataset",
"datatable"
] | 144 | 104 | 135,245 | 7 | 0 | 2008-08-05T13:07:40.563000 | 2008-08-05T13:12:15.873000 |
2,256 | 2,490 | Mapping Stream data to data structures in C# | Is there a way of mapping data collected on a stream or array to a data structure or vice-versa? In C++ this would simply be a matter of casting a pointer to the stream as a data type I want to use (or vice-versa for the reverse). e.g in C++: Mystruct * pMyStrct = (Mystruct*)&SomeDataStream pMyStrct->Item1 = 25;
int iReadData = pMyStrct->Item2; obviously, the C++ way is pretty unsafe unless you are sure of the quality of the stream data when reading incoming data, but for outgoing data is super quick and easy. | Most people use.NET serialization (there is faster binary and slower XML formatter, they both depend on reflection and are version tolerant to certain degree) However, if you want the fastest (unsafe) way - why not: Writing: YourStruct o = new YourStruct(); byte[] buffer = new byte[Marshal.SizeOf(typeof(YourStruct))]; GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); Marshal.StructureToPtr(o, handle.AddrOfPinnedObject(), false); handle.Free(); Reading: handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); o = (YourStruct)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(YourStruct)); handle.Free(); | Mapping Stream data to data structures in C# Is there a way of mapping data collected on a stream or array to a data structure or vice-versa? In C++ this would simply be a matter of casting a pointer to the stream as a data type I want to use (or vice-versa for the reverse). e.g in C++: Mystruct * pMyStrct = (Mystruct*)&SomeDataStream pMyStrct->Item1 = 25;
int iReadData = pMyStrct->Item2; obviously, the C++ way is pretty unsafe unless you are sure of the quality of the stream data when reading incoming data, but for outgoing data is super quick and easy. | TITLE:
Mapping Stream data to data structures in C#
QUESTION:
Is there a way of mapping data collected on a stream or array to a data structure or vice-versa? In C++ this would simply be a matter of casting a pointer to the stream as a data type I want to use (or vice-versa for the reverse). e.g in C++: Mystruct * pMyStrct = (Mystruct*)&SomeDataStream pMyStrct->Item1 = 25;
int iReadData = pMyStrct->Item2; obviously, the C++ way is pretty unsafe unless you are sure of the quality of the stream data when reading incoming data, but for outgoing data is super quick and easy.
ANSWER:
Most people use.NET serialization (there is faster binary and slower XML formatter, they both depend on reflection and are version tolerant to certain degree) However, if you want the fastest (unsafe) way - why not: Writing: YourStruct o = new YourStruct(); byte[] buffer = new byte[Marshal.SizeOf(typeof(YourStruct))]; GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); Marshal.StructureToPtr(o, handle.AddrOfPinnedObject(), false); handle.Free(); Reading: handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); o = (YourStruct)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(YourStruct)); handle.Free(); | [
"c#",
"c++",
"data-structures"
] | 29 | 20 | 8,509 | 4 | 0 | 2008-08-05T13:11:14.223000 | 2008-08-05T15:46:35.157000 |
2,262 | 2,268 | ASP.NET URL Rewriting | How do I rewrite a URL in ASP.NET? I would like users to be able to go to http://www.website.com/users/smith instead of http://www.website.com/?user=smith | Try the Managed Fusion Url Rewriter and Reverse Proxy: http://urlrewriter.codeplex.com The rule for rewriting this would be: # clean up old rules and forward to new URL RewriteRule ^/?user=(.*) /users/$1 [NC,R=301]
# rewrite the rule internally RewriteRule ^/users/(.*) /?user=$1 [NC,L] | ASP.NET URL Rewriting How do I rewrite a URL in ASP.NET? I would like users to be able to go to http://www.website.com/users/smith instead of http://www.website.com/?user=smith | TITLE:
ASP.NET URL Rewriting
QUESTION:
How do I rewrite a URL in ASP.NET? I would like users to be able to go to http://www.website.com/users/smith instead of http://www.website.com/?user=smith
ANSWER:
Try the Managed Fusion Url Rewriter and Reverse Proxy: http://urlrewriter.codeplex.com The rule for rewriting this would be: # clean up old rules and forward to new URL RewriteRule ^/?user=(.*) /users/$1 [NC,R=301]
# rewrite the rule internally RewriteRule ^/users/(.*) /?user=$1 [NC,L] | [
"asp.net",
"url",
"url-rewriting",
"url-routing"
] | 36 | 25 | 10,666 | 3 | 0 | 2008-08-05T13:14:48.350000 | 2008-08-05T13:18:39.340000 |
2,279 | 2,314 | Add Custom Tag to Visual Studio Validation | How can I add rules to Visual Studio (2005 and up) for validating property markup (HTML) for a vendor's proprietary controls? My client uses a control which requires several properties to be set as tags in the aspx file which generates something like 215 validation errors on each build. It's not preventing me from building, but real errors are getting lost in the noise. | Right-click on the Source view of an HTML / ASP page and select "Formatting and Validation". Click "Tag Specific Options". Expand "Client HTML Tags" and select the heading. Click "New Tag...". And just fill it in! I wish that I could add custom CSS values as well. | Add Custom Tag to Visual Studio Validation How can I add rules to Visual Studio (2005 and up) for validating property markup (HTML) for a vendor's proprietary controls? My client uses a control which requires several properties to be set as tags in the aspx file which generates something like 215 validation errors on each build. It's not preventing me from building, but real errors are getting lost in the noise. | TITLE:
Add Custom Tag to Visual Studio Validation
QUESTION:
How can I add rules to Visual Studio (2005 and up) for validating property markup (HTML) for a vendor's proprietary controls? My client uses a control which requires several properties to be set as tags in the aspx file which generates something like 215 validation errors on each build. It's not preventing me from building, but real errors are getting lost in the noise.
ANSWER:
Right-click on the Source view of an HTML / ASP page and select "Formatting and Validation". Click "Tag Specific Options". Expand "Client HTML Tags" and select the heading. Click "New Tag...". And just fill it in! I wish that I could add custom CSS values as well. | [
"visual-studio"
] | 19 | 5 | 1,836 | 1 | 0 | 2008-08-05T13:24:11.763000 | 2008-08-05T13:43:27.387000 |
2,300 | 2,312 | How do I traverse a collection in classic ASP? | I want to be able to do: For Each thing In things End For CLASSIC ASP - NOT.NET! | Whatever your [things] are need to be written outside of VBScript. In VB6, you can write a Custom Collection class, then you'll need to compile to an ActiveX DLL and register it on your webserver to access it. | How do I traverse a collection in classic ASP? I want to be able to do: For Each thing In things End For CLASSIC ASP - NOT.NET! | TITLE:
How do I traverse a collection in classic ASP?
QUESTION:
I want to be able to do: For Each thing In things End For CLASSIC ASP - NOT.NET!
ANSWER:
Whatever your [things] are need to be written outside of VBScript. In VB6, you can write a Custom Collection class, then you'll need to compile to an ActiveX DLL and register it on your webserver to access it. | [
"asp-classic",
"vbscript"
] | 16 | 4 | 11,462 | 6 | 0 | 2008-08-05T13:30:46.290000 | 2008-08-05T13:42:15.593000 |
2,308 | 2,320 | ASP.NET Display SVN Revision Number | I see in the Stack Overflow footer that the SVN Revision number is displayed. Is this automated and if so, how does one implement it in ASP.NET? (Solutions in other languages are acceptable) | Make sure that the file has s vn:keywords "Rev Id" and then put $Rev$ somewhere in there. See this question and the answers to it. | ASP.NET Display SVN Revision Number I see in the Stack Overflow footer that the SVN Revision number is displayed. Is this automated and if so, how does one implement it in ASP.NET? (Solutions in other languages are acceptable) | TITLE:
ASP.NET Display SVN Revision Number
QUESTION:
I see in the Stack Overflow footer that the SVN Revision number is displayed. Is this automated and if so, how does one implement it in ASP.NET? (Solutions in other languages are acceptable)
ANSWER:
Make sure that the file has s vn:keywords "Rev Id" and then put $Rev$ somewhere in there. See this question and the answers to it. | [
"asp.net",
"svn"
] | 18 | 6 | 2,935 | 3 | 0 | 2008-08-05T13:38:42.310000 | 2008-08-05T13:47:00.077000 |
2,311 | 2,316 | File size differences after copying a file to a server vía FTP | I have created a PHP-script to update a web server that is live inside a local directory. I'm migrating the script into Python. It works fine for the most part, but after a PUT command, the size of the file appears to change. Thus, the size of the file is different from that of the file on the server. Once I download again the file from the FTP server, the only difference is the CR/LF mark. This annoys me because the same script is comparing the size of the files to update. Also, in case it means anything, the script works perfectly in PHP vía ftp_put. from ftplib import FTP
ftpserver = "myserver" ftpuser = "myuser" ftppass = "mypwd"
locfile = "g:/test/style.css" ftpfile = "/temp/style.css"
try: ftp = FTP(ftpserver, ftpuser, ftppass) except: exit ("Cannot connect")
f = open (locfile, "r") try: ftp.delete (ftpfile) except: pass
# ftp.sendcmd ("TYPE I") # ftp.storlines("STOR %s" % ftpfile, f) ftp.storbinary("STOR %s" % ftpfile, f) f.close()
ftp.dir (ftpfile) ftp.quit() Any suggestions? | Do you need to open the locfile in binary using rb? f = open (locfile, "rb") | File size differences after copying a file to a server vía FTP I have created a PHP-script to update a web server that is live inside a local directory. I'm migrating the script into Python. It works fine for the most part, but after a PUT command, the size of the file appears to change. Thus, the size of the file is different from that of the file on the server. Once I download again the file from the FTP server, the only difference is the CR/LF mark. This annoys me because the same script is comparing the size of the files to update. Also, in case it means anything, the script works perfectly in PHP vía ftp_put. from ftplib import FTP
ftpserver = "myserver" ftpuser = "myuser" ftppass = "mypwd"
locfile = "g:/test/style.css" ftpfile = "/temp/style.css"
try: ftp = FTP(ftpserver, ftpuser, ftppass) except: exit ("Cannot connect")
f = open (locfile, "r") try: ftp.delete (ftpfile) except: pass
# ftp.sendcmd ("TYPE I") # ftp.storlines("STOR %s" % ftpfile, f) ftp.storbinary("STOR %s" % ftpfile, f) f.close()
ftp.dir (ftpfile) ftp.quit() Any suggestions? | TITLE:
File size differences after copying a file to a server vía FTP
QUESTION:
I have created a PHP-script to update a web server that is live inside a local directory. I'm migrating the script into Python. It works fine for the most part, but after a PUT command, the size of the file appears to change. Thus, the size of the file is different from that of the file on the server. Once I download again the file from the FTP server, the only difference is the CR/LF mark. This annoys me because the same script is comparing the size of the files to update. Also, in case it means anything, the script works perfectly in PHP vía ftp_put. from ftplib import FTP
ftpserver = "myserver" ftpuser = "myuser" ftppass = "mypwd"
locfile = "g:/test/style.css" ftpfile = "/temp/style.css"
try: ftp = FTP(ftpserver, ftpuser, ftppass) except: exit ("Cannot connect")
f = open (locfile, "r") try: ftp.delete (ftpfile) except: pass
# ftp.sendcmd ("TYPE I") # ftp.storlines("STOR %s" % ftpfile, f) ftp.storbinary("STOR %s" % ftpfile, f) f.close()
ftp.dir (ftpfile) ftp.quit() Any suggestions?
ANSWER:
Do you need to open the locfile in binary using rb? f = open (locfile, "rb") | [
"php",
"python",
"ftp",
"webserver",
"ftplib"
] | 46 | 17 | 5,593 | 3 | 0 | 2008-08-05T13:40:47.470000 | 2008-08-05T13:45:38.413000 |
2,328 | 4,910 | Tracking state using ASP.NET AJAX / ICallbackEventHandler | I have a problem with maintaining state in an ASP.NET AJAX page. Short version: I need some way to update the page ViewState after an async callback has been made, to reflect any state changes the server made during the async call. This seems to be a common problem, but I will describe my scenario to help explain: I have a grid-like control which has some JavaScript enhancements - namely, the ability to drag and drop columns and rows. When a column or row is dropped into a new position, an AJAX method is invoked to notify the control server-side and fire a corresponding server-side event ("OnColumnMoved" or "OnRowMoved"). ASP.NET AJAX calls, by default, send the entire page as the request. That way the page goes through a complete lifecycle, viewstate is persisted and the state of the control is restored before the RaiseCallbackEvent method is invoked. However, since the AJAX call does not update the page, the ViewState reflects the original state of the control, even after the column or row has been moved. So the second time a client-side action occurs, the AJAX request goes to the server and the page & control are built back up again to reflect the first state of the control, not the state after the first column or row was moved. This problem extends to many implications. For example if we have a client-side/AJAX action to add a new item to the grid, and then a row is dragged, the grid is built server-side with one less item than on the client-side. And finally & most seriously for my specific example, the actual data source object we are acting upon is stored in the page ViewState. That was a design decision to allow keeping a stateful copy of the manipulated data which can either be committed to DB after many manipulations or discarded if the user backs out. That is very difficult to change. So, again, I need a way for the page ViewState to be updated on callback after the AJAX method is fired. | If you're already shuffling the ViewState around anyway, you might as well use an UpdatePanel. Its partial postbacks will update the page's ViewState automatically. | Tracking state using ASP.NET AJAX / ICallbackEventHandler I have a problem with maintaining state in an ASP.NET AJAX page. Short version: I need some way to update the page ViewState after an async callback has been made, to reflect any state changes the server made during the async call. This seems to be a common problem, but I will describe my scenario to help explain: I have a grid-like control which has some JavaScript enhancements - namely, the ability to drag and drop columns and rows. When a column or row is dropped into a new position, an AJAX method is invoked to notify the control server-side and fire a corresponding server-side event ("OnColumnMoved" or "OnRowMoved"). ASP.NET AJAX calls, by default, send the entire page as the request. That way the page goes through a complete lifecycle, viewstate is persisted and the state of the control is restored before the RaiseCallbackEvent method is invoked. However, since the AJAX call does not update the page, the ViewState reflects the original state of the control, even after the column or row has been moved. So the second time a client-side action occurs, the AJAX request goes to the server and the page & control are built back up again to reflect the first state of the control, not the state after the first column or row was moved. This problem extends to many implications. For example if we have a client-side/AJAX action to add a new item to the grid, and then a row is dragged, the grid is built server-side with one less item than on the client-side. And finally & most seriously for my specific example, the actual data source object we are acting upon is stored in the page ViewState. That was a design decision to allow keeping a stateful copy of the manipulated data which can either be committed to DB after many manipulations or discarded if the user backs out. That is very difficult to change. So, again, I need a way for the page ViewState to be updated on callback after the AJAX method is fired. | TITLE:
Tracking state using ASP.NET AJAX / ICallbackEventHandler
QUESTION:
I have a problem with maintaining state in an ASP.NET AJAX page. Short version: I need some way to update the page ViewState after an async callback has been made, to reflect any state changes the server made during the async call. This seems to be a common problem, but I will describe my scenario to help explain: I have a grid-like control which has some JavaScript enhancements - namely, the ability to drag and drop columns and rows. When a column or row is dropped into a new position, an AJAX method is invoked to notify the control server-side and fire a corresponding server-side event ("OnColumnMoved" or "OnRowMoved"). ASP.NET AJAX calls, by default, send the entire page as the request. That way the page goes through a complete lifecycle, viewstate is persisted and the state of the control is restored before the RaiseCallbackEvent method is invoked. However, since the AJAX call does not update the page, the ViewState reflects the original state of the control, even after the column or row has been moved. So the second time a client-side action occurs, the AJAX request goes to the server and the page & control are built back up again to reflect the first state of the control, not the state after the first column or row was moved. This problem extends to many implications. For example if we have a client-side/AJAX action to add a new item to the grid, and then a row is dragged, the grid is built server-side with one less item than on the client-side. And finally & most seriously for my specific example, the actual data source object we are acting upon is stored in the page ViewState. That was a design decision to allow keeping a stateful copy of the manipulated data which can either be committed to DB after many manipulations or discarded if the user backs out. That is very difficult to change. So, again, I need a way for the page ViewState to be updated on callback after the AJAX method is fired.
ANSWER:
If you're already shuffling the ViewState around anyway, you might as well use an UpdatePanel. Its partial postbacks will update the page's ViewState automatically. | [
"asp.net",
"ajax",
"asp.net-ajax",
"viewstate"
] | 13 | 2 | 3,205 | 5 | 0 | 2008-08-05T13:52:12.720000 | 2008-08-07T16:19:34.683000 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.