source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
1,040
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.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/1040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/254/" ] }
1,041
I'm looking for a robust, easy-to-use, regular expression evaluator for native C++, either platform-independent or Windows-specific. Requirements: Can't use Boost or ACE regex libraries (unfortunately) Can't use .NET Regex (or any managed code) The main requirement is that it should be standalone and open.
C++11 now includes the support of regular expressions.It will be platform independent. You just need a recent compiler.Check the following list to know which one to use. http://wiki.apache.org/stdcxx/C%2B%2B0xCompilerSupport Hope it helps
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/1041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
1,042
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).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/1042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2/" ] }
1,053
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.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/1053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13/" ] }
1,069
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 behaviour 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 behaviuor 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 behaviour 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 identify the cause) or being able to idenify the cause or 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 mis-behaviour 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 towards 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 a 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 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 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, 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?
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/1069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/257/" ] }
1,070
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.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/1070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/236/" ] }
1,083
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 …
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/1083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260/" ] }
1,104
Exceptions in C++ don't need to be caught (no compile time errors) by the calling function. So it's up to 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.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/1104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/236/" ] }
1,108
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 diskid (Primary key) Unsigned INT 4 bytesfirstName Char(50) 50 byteslastName Char(50) 50 bytesemailAddress 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 diskfirstName 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.
{ "score": 13, "source": [ "https://Stackoverflow.com/questions/1108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/264/" ] }
1,131
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.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/1131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ] }
1,145
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 <stdio.h>#include <string.h>#include <stdlib.h>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);
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/1145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/188/" ] }
1,156
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] )
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/1156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/264/" ] }
1,160
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: <labeller type="assemblyVersionLabeller" incrementOnFailure="true" major="1" minor="2"/> (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 : <Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets"/><Target Name="BeforeBuild"> <AssemblyInfo Condition="'$(CCNetLabel)' != ''" CodeLanguage="CS" OutputFile="Properties\AssemblyInfo.cs" AssemblyTitle="MyTitle" AssemblyCompany="MyCompany" AssemblyProduct="MyProduct" AssemblyCopyright="Copyright © 2009" ComVisible="false" Guid="some-random-guid" AssemblyVersion="$(CCNetLabel)" AssemblyFileVersion="$(CCNetLabel)"/></Target> For sake of completness, it's just as easy for projects using NAnt instead of MSBuild: <target name="setversion" description="Sets the version number to CruiseControl.Net label."> <script language="C#"> <references> <include name="System.dll" /> </references> <imports> <import namespace="System.Text.RegularExpressions" /> </imports> <code><![CDATA[ [TaskName("setversion-task")] public class SetVersionTask : Task { protected override void ExecuteTask() { StreamReader reader = new StreamReader(Project.Properties["filename"]); string contents = reader.ReadToEnd(); reader.Close(); string replacement = "[assembly: AssemblyVersion(\"" + Project.Properties["CCNetLabel"] + "\")]"; string newText = Regex.Replace(contents, @"\[assembly: AssemblyVersion\("".*""\)\]", replacement); StreamWriter writer = new StreamWriter(Project.Properties["filename"], false); writer.Write(newText); writer.Close(); } } ]]> </code> </script> <foreach item="File" property="filename"> <in> <items basedir=".."> <include name="**\AssemblyInfo.cs"></include> </items> </in> <do> <setversion-task /> </do> </foreach></target>
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/1160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/120/" ] }
1,171
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 edgesand report some properties.This graph is sometimes called the Erd##[m~Qs-Rényi graphbut is different from G{n,p} or binomial_graph which is alsosometimes called the Erd##[m~Qs-Rényi graph."""__author__ = """Aric Hagberg ([email protected])"""__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.htmlfrom networkx import *import sysn=10 # 10 nodesm=20 # 20 edgesG=gnm_random_graph(n,m)# some propertiesprint "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
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/1171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/280/" ] }
1,180
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.comServerAlias *.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.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/1180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/281/" ] }
1,237
I have a file in the following format: Data DataData[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\](.*?)\[end\] Zhich'll put the text in the middle within a capture.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/1237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230/" ] }
1,261
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!
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/1261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/292/" ] }
1,276
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.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/1276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30/" ] }
1,292
I have a Queue<T> 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<T> : Queue<T>{ 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); }}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/1292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192/" ] }
1,300
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.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/1300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ] }
1,304
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.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/1304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/121/" ] }
1,306
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.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/1306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/302/" ] }
1,313
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.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/1313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2089740/" ] }
1,329
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?
Use Robocopy (Robust File Copy) . NOTE: In Windows Vista and Server 2008 when you type: xcopy /? you get: NOTE: Xcopy is now deprecated, please use Robocopy. So start getting used to robocopy :)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/1329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ] }
1,383
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.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/1383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/314/" ] }
1,390
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.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/1390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/60/" ] }
1,401
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) <script type="text/javascript"> function feeAmountCheck(source, arguments) { var amountDue = document.getElementById('ctl00_footerContentHolder_Fees1_FeeDue'); var amountPaid = document.getElementById('ctl00_footerContentHolder_Fees1_FeePaid'); if (amountDue.value > 0 && amountDue >= amountPaid) { arguments.IsValid = true; } else { arguments.IsValid = false; } return arguments; }</script> 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.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/1401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/149/" ] }
1,408
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): <VirtualHost *:80> DocumentRoot C:\Projects\transitCalculator\trunk ServerName transitcalculator.localhost <Directory C:\Projects\transitCalculator\trunk> Order allow,deny Allow from all </Directory></VirtualHost> 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 <Directory "C:/xampp/htdocs"> and </Directory> (~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 <IfModule alias_module></IfModule> 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 .
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/1408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58/" ] }
1,451
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 fordetermining a how to apply the parameters. The special columns inthis example are TypeID and TypeAuxID . The SQL would look somethinglike this. SELECT COUNT(PermissionID)FROM application_permissionsWHERE(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 themall together. SELECT COUNT(perm.PermissionID)FROM application_permissions permLEFT JOIN application_UserPermissions empON perm.ApplicationID = emp.ApplicationIDLEFT JOIN application_DepartmentPermissions deptON perm.ApplicationID = dept.ApplicationIDWHERE q.SectionID=@SectionID AND (emp.UserID=@UserID OR dept.DeptID=@DeptID OR (emp.UserID IS NULL AND dept.DeptID IS NULL)) AND ApplicationID = 1ORDER 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.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/1451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/106/" ] }
1,453
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();}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/1453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58/" ] }
1,457
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.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/1457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/331/" ] }
1,476
How do you express an integer as a binary number with Python literals? I was easily able to find the answer for hex: >>> 0x12AF4783>>> 0x100256 and octal: >>> 01267695>>> 010064 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 : >>> 0b10111147 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
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/1476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/92/" ] }
1,496
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.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/1496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/136/" ] }
1,528
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.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/1528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93/" ] }
1,535
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}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/1535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/332/" ] }
1,598
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)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/1598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ] }
1,607
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.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/1607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72/" ] }
1,610
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.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/1610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/328/" ] }
1,623
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.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/1623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230/" ] }
1,644
Yes, Podcasts, those nice little Audiobooks I can listen to on the way to work. With the current amount of Podcasts, it's like searching a needle in a haystack, except that the haystack happens to be the Internet and is filled with too many of these "Hot new Gadgets" stuff :( Now, even though I am mainly a .NET developer nowadays, maybe anyone knows some good Podcasts from people regarding the whole software lifecycle? Unit Testing, Continous Integration, Documentation, Deployment... So - what are you guys and gals listening to? Please note that the categorizations are somewhat subjective and may not be 100% accurate as many podcasts cover several areas. Categorization is made against what is considered the "main" area. General Software Engineering / Productivity [Stack Overflow ] 1 (inactive, but still a good listen) TekPub (Requires Paid Subscription) Software Engineering Radio 43 Folders Perspectives Dr. Dobb's (now a video feed) The Pragmatic Podcast (Inactive) IT Matters Agile Toolkit Podcast The Stack Trace (Inactive) Parleys Techzing The Startup Success Podcast Berkeley CS class lectures FLOSS Weekly This Developer's Life .NET / Visual Studio / Microsoft Herding Code Hanselminutes .NET Rocks! Deep Fried Bytes Alt.Net Podcast (inactive) Polymorphic Podcast (inconsistent) Sparkling Client (The Silverlight Podcast) dnrTV! Spaghetti Code ASP.NET Podcast Channel 9 Radio TFS PowerScripting Podcast The Thirsty Developer Elegant Code (inactive) ConnectedShow Crafty Coders Coding QA jQuery yayQuery The official jQuery podcast Java / Groovy The Java Posse Grails Podcast Java Technology Insider Basement Coders Ruby / Rails Railscasts Rails Envy The Ruby on Rails Podcast Rubiverse Ruby5 Web Design / JavaScript / Ajax WebDevRadio Boagworld The Rissington podcast Ajaxian YUI Theater Unix / Linux / Mac / iPhone Mac Developer Network Hacker Public Radio Linux Outlaws Mac OS Ken LugRadio Linux radio show (Inactive) The Linux Action Show! Linux Kernel Mailing List (LKML) Summary Podcast Stanford's iPhone programming class Advanced iPhone Development Course - Madison Area Technical College WWDC 2010 Session Videos (requires Apple Developer registration) System Administration, Security or Infrastructure RunAs Radio Security Now! Crypto-Gram Security Podcast Hak5 VMWare VMTN Windows Weekly PaulDotCom Security The Register - Semi-Coherent Computing FeatherCast General Tech / Business Tekzilla This Week in Tech The Guardian Tech Weekly PCMag Radio Podcast (Inactive) Entrepreneurship Corner Manager Tools Other / Misc. / Podcast Networks IT Conversations Retrobits Podcast No Agenda Netcast Cranky Geeks The Command Line Freelance Radio IBM developerWorks The Register - Open Season Drunk and Retired Technometria Sod This Radio4Nerds Hacker Medley
I like General Software Stackoverflow (perhaps too obvious) Deep Fried Bytes Hanselminutes Software Engineering Radio (via Brenden) Herding Code Dot Net Alt.NET Podcast Polymorphic Podcast Productivity 43 Folders
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/1644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ] }
1,669
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
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/1669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/340/" ] }
1,683
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.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/1683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/350/" ] }
1,711
If you could go back in time and tell yourself to read a specific book at the beginning of your career as a developer, which book would it be? I expect this list to be varied and to cover a wide range of things. To search: Use the search box in the upper-right corner. To search the answers of the current question, use inquestion:this . For example: inquestion:this "Code Complete"
Code Complete (2nd edition) by Steve McConnell The Pragmatic Programmer Structure and Interpretation of Computer Programs The C Programming Language by Kernighan and Ritchie Introduction to Algorithms by Cormen, Leiserson, Rivest & Stein Design Patterns by the Gang of Four Refactoring: Improving the Design of Existing Code The Mythical Man Month The Art of Computer Programming by Donald Knuth Compilers: Principles, Techniques and Tools by Alfred V. Aho, Ravi Sethi and Jeffrey D. Ullman Gödel, Escher, Bach by Douglas Hofstadter Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin Effective C++ More Effective C++ CODE by Charles Petzold Programming Pearls by Jon Bentley Working Effectively with Legacy Code by Michael C. Feathers Peopleware by Demarco and Lister Coders at Work by Peter Seibel Surely You're Joking, Mr. Feynman! Effective Java 2nd edition Patterns of Enterprise Application Architecture by Martin Fowler The Little Schemer The Seasoned Schemer Why's (Poignant) Guide to Ruby The Inmates Are Running The Asylum: Why High Tech Products Drive Us Crazy and How to Restore the Sanity The Art of Unix Programming Test-Driven Development: By Example by Kent Beck Practices of an Agile Developer Don't Make Me Think Agile Software Development, Principles, Patterns, and Practices by Robert C. Martin Domain Driven Designs by Eric Evans The Design of Everyday Things by Donald Norman Modern C++ Design by Andrei Alexandrescu Best Software Writing I by Joel Spolsky The Practice of Programming by Kernighan and Pike Pragmatic Thinking and Learning: Refactor Your Wetware by Andy Hunt Software Estimation: Demystifying the Black Art by Steve McConnel The Passionate Programmer (My Job Went To India) by Chad Fowler Hackers: Heroes of the Computer Revolution Algorithms + Data Structures = Programs Writing Solid Code JavaScript - The Good Parts Getting Real by 37 Signals Foundations of Programming by Karl Seguin Computer Graphics: Principles and Practice in C (2nd Edition) Thinking in Java by Bruce Eckel The Elements of Computing Systems Refactoring to Patterns by Joshua Kerievsky Modern Operating Systems by Andrew S. Tanenbaum The Annotated Turing Things That Make Us Smart by Donald Norman The Timeless Way of Building by Christopher Alexander The Deadline: A Novel About Project Management by Tom DeMarco The C++ Programming Language (3rd edition) by Stroustrup Patterns of Enterprise Application Architecture Computer Systems - A Programmer's Perspective Agile Principles, Patterns, and Practices in C# by Robert C. Martin Growing Object-Oriented Software, Guided by Tests Framework Design Guidelines by Brad Abrams Object Thinking by Dr. David West Advanced Programming in the UNIX Environment by W. Richard Stevens Hackers and Painters: Big Ideas from the Computer Age The Soul of a New Machine by Tracy Kidder CLR via C# by Jeffrey Richter The Timeless Way of Building by Christopher Alexander Design Patterns in C# by Steve Metsker Alice in Wonderland by Lewis Carol Zen and the Art of Motorcycle Maintenance by Robert M. Pirsig About Face - The Essentials of Interaction Design Here Comes Everybody: The Power of Organizing Without Organizations by Clay Shirky The Tao of Programming Computational Beauty of Nature Writing Solid Code by Steve Maguire Philip and Alex's Guide to Web Publishing Object-Oriented Analysis and Design with Applications by Grady Booch Effective Java by Joshua Bloch Computability by N. J. Cutland Masterminds of Programming The Tao Te Ching The Productive Programmer The Art of Deception by Kevin Mitnick The Career Programmer: Guerilla Tactics for an Imperfect World by Christopher Duncan Paradigms of Artificial Intelligence Programming: Case studies in Common Lisp Masters of Doom Pragmatic Unit Testing in C# with NUnit by Andy Hunt and Dave Thomas with Matt Hargett How To Solve It by George Polya The Alchemist by Paulo Coelho Smalltalk-80: The Language and its Implementation Writing Secure Code (2nd Edition) by Michael Howard Introduction to Functional Programming by Philip Wadler and Richard Bird No Bugs! by David Thielen Rework by Jason Freid and DHH JUnit in Action
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/1711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303/" ] }
1,734
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 ?
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/1734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59/" ] }
1,746
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]/", "<span class=\"initial\">$1</span>", $str)
You need to put the pattern in parentheses /([A-Z])/ , like this: preg_replace("/([A-Z])/", "<span class=\"initial\">$1</span>", $str)
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/1746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/137/" ] }
1,760
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.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/1760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234/" ] }
1,762
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';...<?php if ($canMerge) { ?>Stuff<?php } ?> 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);
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/1762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/137/" ] }
1,836
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(); }}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/1836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172/" ] }
1,848
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.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/1848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36/" ] }
1,854
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
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/1854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ] }
1,873
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: <a id="aShowHide" onclick='ToggleDisplay(<%# DataBinder.Eval(Container.DataItem, "JobCode") %>);' >Show/Hide</a> And there is my Javascript: <script language="JavaScript" type="text/javascript">/* Shows/Hides the Jobs Div */function ToggleDisplay(jobCode){ /* Each div has its ID set dynamically ('d' plus the JobCode) */ var elem = document.getElementById('d' + jobCode); if (elem) { if (elem.style.display != 'block') { elem.style.display = 'block'; elem.style.visibility = 'visible'; } else { elem.style.display = 'none'; elem.style.visibility = 'hidden'; } }}</script>
I had recently similar problem and the only way to solve it was to use plain old HTML codes for single ( &#39; ) and double quotes ( &#34; ). Source code was total mess of course but it worked. Try <a id="aShowHide" onclick='ToggleDisplay(&#34;<%# DataBinder.Eval(Container.DataItem, "JobCode") %>&#34;);'>Show/Hide</a> or <a id="aShowHide" onclick='ToggleDisplay(&#39;<%# DataBinder.Eval(Container.DataItem, "JobCode") %>&#39;);'>Show/Hide</a>
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/1873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/242/" ] }
1,898
What's the best way to import a CSV file into a strongly-typed data structure?
Microsoft's TextFieldParser is stable and follows RFC 4180 for CSV files. Don't be put off by the Microsoft.VisualBasic namespace; it's a standard component in the .NET Framework, just add a reference to the global Microsoft.VisualBasic assembly. If you're compiling for Windows (as opposed to Mono) and don't anticipate having to parse "broken" (non-RFC-compliant) CSV files, then this would be the obvious choice, as it's free, unrestricted, stable, and actively supported, most of which cannot be said for FileHelpers. See also: How to: Read From Comma-Delimited Text Files in Visual Basic for a VB code example.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/1898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/81/" ] }
1,936
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);}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/1936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ] }
1,949
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 suitedfor a "unit of work" approach Is also designed for"stateless" server operation Is not designed for Long-lived usage Should be used very carefully afterany 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.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/1949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51/" ] }
1,982
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.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/1982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2090742/" ] }
1,983
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.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/1983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ] }
1,988
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.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/1988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ] }
2,027
When learning a new programming language, one of the possible roadblocks you might encounter is the question whether the language is, by default, pass-by-value or pass-by-reference . So here is my question to all of you, in your favorite language, how is it actually done? And what are the possible pitfalls ? Your favorite language can, of course, be anything you have ever played with: popular , obscure , esoteric , new , old ...
Here is my own contribution for the Java programming language . first some code: public void swap(int x, int y){ int tmp = x; x = y; y = tmp;} calling this method will result in this: int pi = 3;int everything = 42;swap(pi, everything);System.out.println("pi: " + pi);System.out.println("everything: " + everything);"Output:pi: 3everything: 42" even using 'real' objects will show a similar result: public class MyObj { private String msg; private int number; //getters and setters public String getMsg() { return this.msg; } public void setMsg(String msg) { this.msg = msg; } public int getNumber() { return this.number; } public void setNumber(int number) { this.number = number; } //constructor public MyObj(String msg, int number) { setMsg(msg); setNumber(number); }}public static void swap(MyObj x, MyObj y){ MyObj tmp = x; x = y; y = tmp;}public static void main(String args[]) { MyObj x = new MyObj("Hello world", 1); MyObj y = new MyObj("Goodbye Cruel World", -1); swap(x, y); System.out.println(x.getMsg() + " -- "+ x.getNumber()); System.out.println(y.getMsg() + " -- "+ y.getNumber());}"Output:Hello world -- 1Goodbye Cruel World -- -1" thus it is clear that Java passes its parameters by value , as the value for pi and everything and the MyObj objects aren't swapped.be aware that "by value" is the only way in java to pass parameters to a method. (for example a language like c++ allows the developer to pass a parameter by reference using ' & ' after the parameter's type) now the tricky part , or at least the part that will confuse most of the new java developers: (borrowed from javaworld ) Original author: Tony Sintes public void tricky(Point arg1, Point arg2){ arg1.x = 100; arg1.y = 100; Point temp = arg1; arg1 = arg2; arg2 = temp;}public static void main(String [] args){ Point pnt1 = new Point(0,0); Point pnt2 = new Point(0,0); System.out.println("X: " + pnt1.x + " Y: " +pnt1.y); System.out.println("X: " + pnt2.x + " Y: " +pnt2.y); System.out.println(" "); tricky(pnt1,pnt2); System.out.println("X: " + pnt1.x + " Y:" + pnt1.y); System.out.println("X: " + pnt2.x + " Y: " +pnt2.y); }"OutputX: 0 Y: 0X: 0 Y: 0X: 100 Y: 100X: 0 Y: 0" tricky successfully changes the value of pnt1!This would imply that Objects are passed by reference, this is not the case!A correct statement would be: the Object references are passed by value. more from Tony Sintes: The method successfully alters the value of pnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In the main() method, pnt1 and pnt2 are nothing more than object references. When you pass pnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references. Figure 1 below shows two references pointing to the same object after Java passes an object to a method. (source: javaworld.com ) Conclusion or a long story short: Java passes it parameters by value "by value" is the only way in java to pass a parameter to a method using methods from the object given as parameter will alter the object as the references point to the original objects. (if that method itself alters some values) useful links: http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html http://www.ibm.com/developerworks/java/library/j-passbyval/ http://www.ibm.com/developerworks/library/j-praxis/pr1.html http://javadude.com/articles/passbyvalue.htm
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46/" ] }
2,034
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.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/2034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/137/" ] }
2,041
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.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/2041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/269/" ] }
2,046
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.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/372/" ] }
2,056
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
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/2056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/358/" ] }
2,120
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)
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/2120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ] }
2,123
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?
If you correctly markup your HTML code, there is no need for javascript. The following code will allow the user to click on the label text to tick the checkbox. <label for="surname">Surname</label><input type="checkbox" name="surname" id="surname" /> The for attribute on the label element links to the id attribute on the input element and the browser does the rest. This has been testing to work in: IE6 IE7 Firefox
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/2123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193/" ] }
2,134
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? Help me learn :)
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
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/2134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380/" ] }
2,138
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)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/2138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/373/" ] }
2,154
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
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ] }
2,155
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 <configSections> <!-- Mailcenter configuration file --> <section name="mailCenter" type="Ani.MailCenterConfiguration" requirePermission="false"/></configSections>...<mailCenter userDiskSpace="25000"> <mail host="my.hostname.com" port="366" /></mailCenter> 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;}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/2155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/371/" ] }
2,158
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.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/2158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/340/" ] }
2,232
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, theliteral comprises the characters up to the next occurrence of thedelimiter 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
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/2232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25/" ] }
2,250
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.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/2250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ] }
2,256
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)eg: 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();
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/379/" ] }
2,262
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 URLRewriteRule ^/?user=(.*) /users/$1 [NC,R=301]# rewrite the rule internallyRewriteRule ^/users/(.*) /?user=$1 [NC,L]
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/2262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ] }
2,311
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 FTPftpserver = "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")
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/394/" ] }
2,348
In the code below For i = LBound(arr) To UBound(arr) What is the point in asking using LBound ? Surely that is always 0.
Why not use For Each ? That way you don't need to care what the LBound and UBound are. Dim x, y, zx = Array(1, 2, 3)For Each y In x z = DoSomethingWith(y)Next
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/2348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193/" ] }
2,349
In Windows, in any windows form or web browser, you can use the tab button to switch focus through all of the form fields. It will stop on textboxes, radiobuttons, checkboxes, dropdown menus, etc. However, in Mac OSX, tab skips dropdown menus. Is there anyway to change this behavior, or access the above items mentioned, without using a mouse?
Go to System Preferences > Keyboard and Mouse, then choose Keyboard Shortcuts. At the bottom, ensure Full Keyboard Access is set to "All controls". It's a long time since I turned it on but I think that's all you need to do
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/2349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26/" ] }
2,384
I'm trying to read binary data using C#. I have all the information about the layout of the data in the files I want to read. I'm able to read the data "chunk by chunk", i.e. getting the first 40 bytes of data converting it to a string, get the next 40 bytes. Since there are at least three slightly different version of the data, I would like to read the data directly into a struct. It just feels so much more right than by reading it "line by line". I have tried the following approach but to no avail: StructType aStruct;int count = Marshal.SizeOf(typeof(StructType));byte[] readBuffer = new byte[count];BinaryReader reader = new BinaryReader(stream);readBuffer = reader.ReadBytes(count);GCHandle handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned);aStruct = (StructType) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(StructType));handle.Free(); The stream is an opened FileStream from which I have began to read from. I get an AccessViolationExceptio n when using Marshal.PtrToStructure . The stream contains more information than I'm trying to read since I'm not interested in data at the end of the file. The struct is defined like: [StructLayout(LayoutKind.Explicit)]struct StructType{ [FieldOffset(0)] public string FileDate; [FieldOffset(8)] public string FileTime; [FieldOffset(16)] public int Id1; [FieldOffset(20)] public string Id2;} The examples code is changed from original to make this question shorter. How would I read binary data from a file into a struct?
The problem is the string s in your struct. I found that marshaling types like byte/short/int is not a problem; but when you need to marshal into a complex type such as a string, you need your struct to explicitly mimic an unmanaged type. You can do this with the MarshalAs attrib. For your example, the following should work: [StructLayout(LayoutKind.Explicit)]struct StructType{ [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] public string FileDate; [FieldOffset(8)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] public string FileTime; [FieldOffset(16)] public int Id1; [FieldOffset(20)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 66)] //Or however long Id2 is. public string Id2;}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143/" ] }
2,472
What is the best way to record statistics on the number of visitors visiting my site that have set their browser to block ads?
Since programs like AdBlock actually never request the advert, you would have to look the server logs to see if the same user accessed a webpage but didn't access an advert. This is assuming the advert is on the same server. If your adverts are on a separate server, then I would suggest it's impossible to do so. The best way to stop users from blocking adverts, is to have inline text adverts which are generated by the server and dished up inside your html.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ] }
2,482
With the rise of multicore CPUs on the desktop, multithreading skills will become a valuable asset for programmers. Can you recommend some good resources (books, tutorials, websites, etc.) for a programmer who is looking to learn about threaded programming?
Take a look at Herb Sutter's " The Free Lunch Is Over " and then his series of articles on Effective Concurrency .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/311/" ] }
2,483
What is actually the difference between these two casts? SomeClass sc = (SomeClass)SomeObject;SomeClass sc2 = SomeObject as SomeClass; Normally, shouldn't they both be explicit casts to the specified type?
The former will throw an exception if the source type can't be cast to the target type. The latter will result in sc2 being a null reference, but no exception. [Edit] My original answer is certainly the most pronounced difference, but as Eric Lippert points out , it's not the only one. Other differences include: You can't use the 'as' operator to cast to a type that doesn't accept 'null' as a value You can't use 'as' to convert things, like numbers to a different representation (float to int, for example). And finally, using 'as' vs. the cast operator, you're also saying "I'm not sure if this will succeed."
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/2483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ] }
2,488
I'm tired of opening Dia and creating a database diagram at the beginning of every project. Is there a tool out there that will let me select specific tables and then create a database diagram for me based on a MySQL database? Preferably it would allow me to edit the diagram afterward since none of the foreign keys are set... Here is what I am picturing diagram-wise (please excuse the horrible data design, I didn't design it. Let's focus on the diagram concept and not on the actual data it represents for this example ;) ): see full size diagram
Try MySQL Workbench, formerly DBDesigner 4: http://dev.mysql.com/workbench/ This has a "Reverse Engineer Database" mode: Database -> Reverse Engineer
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/2488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58/" ] }
2,509
Test Driven Development has been the rage in the .NET community for the last few years. Recently, I have heard grumblings in the ALT.NET community about BDD. What is it? What makes it different from TDD?
I understand BDD to be more about specification than testing . It is linked to Domain Driven Design (don't you love these *DD acronyms?). It is linked with a certain way to write user stories, including high-level tests. An example by Tom ten Thij : Story: User logging in As a user I want to login with my details So that I can get access to the siteScenario: User uses wrong password Given a username 'jdoe' And a password 'letmein' When the user logs in with username and password Then the login form should be shown again (In his article, Tom goes on to directly execute this test specification in Ruby.) The pope of BDD is Dan North . You'll find a great introduction in his Introducing BDD article. You will find a comparison of BDD and TDD in this video . Also an opinion about BDD as "TDD done right" by Jeremy D. Miller March 25, 2013 update The video above has been missing for a while. Here is a recent one by Llewellyn Falco, BDD vs TDD (explained) . I find his explanation clear and to the point.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/2509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303/" ] }
2,524
I get the following error pretty regularly when compiling in Visual Studio and running my web application: "Unable to start debugging on the web server. The web server did not respond in a timely manner. This may be because another debugger is already attached to the web server." Normally this is after having debug the application once already. From the command line I run "iisreset /restart" and it fixes the problem. How do I prevent this from happening in the first place?
I find that this happens if I'm debugging with Firefox as my browser. When I exit Firefox the VS2005/8 debug session doesn't terminate. I have not found a solution for this (yet). If this is what's happening with you then a quicker solution than running iisreset is to hit Shift-F5 when in Visual Studio and this will terminate the current debug session. You can then hit F5 and this will start a new debug session.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/2524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/417/" ] }
2,525
My product has several components: ASP.NET, Windows Forms App and Windows Service. 95% or so of the code is written in VB.NET. For Intellectual Property reasons, I need to obfuscate the code, and until now I have been using a version of dotfuscator which is now over 5 years old. I'm thinking it is time to move to a new generation tool. What I'm looking for is a list of requirements which I should consider when searching for a new obfuscator. What I know I should look for so far: Serialization/De-serialization . In my current solution, I simply tell the tool not to obfuscate any class data members because the pain of not being able to load data which was previously serialized is simply too big. Integration with Build Process Working with ASP.NET . In the past, I have found this problematic due to changing .dll names (you often have one per page) - which not all tools handle well.
Back with .Net 1.1 obfuscation was essential: decompiling code was easy, and you could go from assembly, to IL, to C# code and have it compiled again with very little effort. Now with .Net 3.5 I'm not at all sure. Try decompiling a 3.5 assembly; what you get is a long long way from compiling. Add the optimisations from 3.5 (far better than 1.1) and the way anonymous types, delegates and so on are handled by reflection (they are a nightmare to recompile). Add lambda expressions, compiler 'magic' like Linq-syntax and var , and C#2 functions like yield (which results in new classes with unreadable names). Your decompiled code ends up a long long way from compilable. A professional team with lots of time could still reverse engineer it back again, but then the same is true of any obfuscated code. What code they got out of that would be unmaintainable and highly likely to be very buggy. I would recommend key-signing your assemblies (meaning if hackers can recompile one they have to recompile all) but I don't think obfuscation's worth it.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/2525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/350/" ] }
2,527
How can I find out which node in a tree list the context menu has been activated? For instance right-clicking a node and selecting an option from the menu. I can't use the TreeViews' SelectedNode property because the node is only been right-clicked and not selected.
You can add a mouse click event to the TreeView, then select the correct node using GetNodeAt given the mouse coordinates provided by the MouseEventArgs. void treeView1MouseUp(object sender, MouseEventArgs e){ if(e.Button == MouseButtons.Right) { // Select the clicked node treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y); if(treeView1.SelectedNode != null) { myContextMenuStrip.Show(treeView1, e.Location); } }}
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/2527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428/" ] }
2,530
How do you disable autocomplete in the major browsers for a specific input (or form field)?
Firefox 30 ignores autocomplete="off" for passwords, opting to prompt the user instead whether the password should be stored on the client. Note the following commentary from May 5, 2014: The password manager always prompts if it wants to save a password. Passwords are not saved without permission from the user. We are the third browser to implement this change, after IE and Chrome. According to the Mozilla Developer Network documentation, the Boolean form element attribute autocomplete prevents form data from being cached in older browsers. <input type="text" name="foo" autocomplete="off" />
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/2530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/307/" ] }
2,540
What are good libraries for C with datastructures like vectors, deques, stacks, hashmaps, treemaps, sets, etc.? Plain C, please, and platform-independent.
The Glib library used on the Gnome project may also be some use. Moreover it is pretty well tested. IBM developer works has a good tutorial on its use: Manage C data using the GLib collections
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/2540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/136/" ] }
2,550
A quick glance at the present-day internet would seem to indicate that Adobe Flash is the obvious choice for embedding video in a web page. Is this accurate, or are they other effective choices? Does the choice of ASP.NET as a platform influence this decision?
Flash is certainly the most ubiquitous and portable solution. 98% of browsers have Flash installed. Other alternatives are Quicktime , Windows Media Player , or even Silverlight (Microsoft's Flash competitor, which can be used to embed several video formats). I would recommend using Flash (and it's FLV video file format) for embedding your video unless you have very specific requirements as far as video quality or DRM.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/308/" ] }
2,556
Should be available to non-U.S. companies, easy to setup, reliable, cheap, customizable, etc. What are your experiences?
You can't really answer this kind of question with a "I like 'insert provide name here'" type answer because like so many things it is a balance and the reasons for choosing a payment processing solution tend to be complex. Volume / Value The most important factor in choosing a secure payment clearance service (the people who will connect to the banking networks and clear the money for you - will refer to them as SPCS) is how many widgets will you be selling at what cost. The pricing models of all the SCPS providers is based around this equation. This dictates the economics of using the service, which is nearly always the most important factor. For example, in the UK securetrading.net have a large annual fee and high minimum transaction values (been a while since I've seen the exact numbers and they don't make it immediately obvious on the site, but this is for illustration only anyway) making it one of the most expensive solutions to use if you are selling high value low volume. Most smaller clients will fall into this model. High value is really anything over a couple of dollars. Low volume is typically anything less than tens of thousands of units per month. However , if you are running a donations service in the aftermath of an international environmental disaster (relatively low value very high volume) then they become one of the cheapest. Factor in to this the setup costs (relatively high), and the cost to tie the service into the site (in SecureTrading's case it's very easy to do, but still a lot harder than adding a PayPal button) and you start to build up a true picture. On the flip side, a service such as PayPal has very low setup costs (no fee to pay, and trivially easy to integrate), but relatively high transaction costs. It is great for high value / low volume transactions. The Bank There are two main categories of payment clearance service - Bureau and Bank Acquired. In the UK at least NetBanx , SecureTrading and WorldPay offer both bank acquired and bureau services. ProtX and SecPay offer only bank acquired services. PayPal and its ilk operates slightly outside both definitions (see Protection below). A Bank Acquired service plumbs into your normal banking merchant account and clears the funds straight into it. As well as charging you for this service, your bank will also take a slice, typically this is more than the SPCS provider will charge and so it actually is the bank that becomes the deciding factor. Some banks will only work with their preferred provider. In the UK, most banks want you to have a separate Internet Merchant Account even if you already have a Merchant Account with them. I always tell clients to shop around, as this will make a huge difference to how much their e-commerce venture can bring in. All banks are not created equal. Bureau services effectively act as your bank at the same time as providing the clearance service. They were popular in a time when banks hadn't grasped the concept of the Internet and would prefer transactions be chiseled into stone tablets if they got their way. Often the choice between a bureau service and a bank acquired service is made for you based on circumstances. Trading History In many countries (including the UK), most banks won't give you a merchant account until you have been trading for a particular period of time (2 years in the UK). Your only option is then a bureau service. Cash flow Most bureau services will hold onto your cash as security against "charge backs". If you sell me a Ferrari and I am horrified to learn that you've sold me a small metal toy rather than the 1.5 tonnes of Italian automotive passion I was expecting, I will complain to my credit card company who will refund me and then chase your merchant services provider for a refund. They will have to give them the refund and then chase you for the money. It's therefore in their interests to hold on to your money for a period of 4-6 weeks to protect against this. If you sell services or goods with no capital outlay (software for instance), then you can afford this. If on the other hand, you really are having to pay your luxury car importer to provide you with stock, then cash flow becomes very important and you're going to need a bank acquired service where you can be paid immediately. Protection One major downside to PayPal and similar services is that it is not covered under the same regulations that govern credit cards. Simply put, if you buy something on a credit card your card provider is liable for ensure you get what you paid for (broadly speaking, in most countries, does not constitute legal advice etc.) and if you have a problem with your purchase they will refund you very quickly and then will go and chase the person that you paid. This is the kind of protection you hear about when Leo Laporte advertises American Express on his podcasts. It is a "Good Thing"TM. You don't have that protection with PayPal because when you use your credit card on PayPal, you are actually buying PayPal's service. So, even if you are mis-sold a product, the person you paid for the service (PayPal) didn't mis-sell, they provided the service you paid for. This breaks the chain. PayPal don't have a legal obligation to protect you in the same way, and their record on refunding ripped off customers is less than spangly. I'm guessing they have "Caveat Emptor" writ large on the walls of their head office. :) I'm not dissing PayPal, they are way ahead of the curve on many other security features, but just another factor to bear in mind. End to end integration Different services differ in their ease of integration. Oh boy do they differ. I'm sitting on some work right now to do an HSBC integration. I'd rather have a root canal. Some of the systems make big assumptions about the way you have to work with them, and are poorly designed or inflexible. Retro-fitting them to an active site can be very painful. Some of them are beautiful and easy to work with (and not necessarily less secure). The biggest difference is how you choose to integrate though. Most services integrate by allowing you to redirect to a secure site where your customer fills in his / her details. They are finally redirected back to a page on your own site with the results of the transaction. This works well in most cases and is easiest to integrate. When you buy something on Amazon, you don't get redirected to WorldPay, or PayPal however. If you want end-to-end integration, most services now will let the communication happen behind the scenes. Your own site has to have a decent secure server certificate of course, and the integration is necessarily more complex. Reputation It used to be that PayPal was used on dinky sites. You wouldn't catch Amazon using it. That perception has changed a lot, and in fact in some senses PayPal does security better than most. If your audience expects to see PayPal and you give them some other service then you may lose custom, or vice versa. These days many merchants offer a choice to customers. UK Providers WorldPay . Well established. Bureau and bank acquired. Relatively high transaction costs and annual costs. Fairly easy to integrate. Owned ultimately by Royal Bank of Scotland. SecPay . Bank Acquired. Low per transaction cost and low annual cost and flexible payment models. ProtX . Bank Acquired. Low per transaction cost and low annual cost, flexible payment models. Can be quite demanding to integrate. HSBC . Bank Acquired. Low per transaction cost. High set up and annual costs. Very inflexible to integrate. SecureTrading . Bureau and Bank Acquired. Low per transaction cost but high setup and annual costs. Was a doddle to integrate last time I used it (9 years ago!) NetBanx . Bureau and Bank Acquired. Haven't used since 1996 so can't comment! And of course PayPal , Google Checkout and Amazon FPS are well worth looking at and worth a whole answer on their own! Summary Told you it wasn't that simple! Usually, as developers, we're not in the position to choose for ourselves, and these decisions should be driven by the business needs of our employer / client. Most e-commerce projects would start with PayPal or similar. When the business gets enough orders that they could save money by switching to another service, then they've got enough money to pay for the switch. Disclaimer: I am UK based, and have performed many integrations with a whole slew of these services over the years, however the market changes all the time and things may have changed and your mileage may vary! I am not a lawyer or accountant, and if you take my advice it's not my fault :)
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/2556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/136/" ] }
2,588
Does any know a good rule of thumb for the appropriate pagefile size for a Windows 2003 server running SQL Server?
Irrelevant of the size of the RAM, you still need a pagefile at least 1.5 times the amount of physical RAM. This is true even if you have a 1 TB RAM machine, you'll need 1.5 TB pagefile on disk (sounds crazy, but is true). When a process asks MEM_COMMIT memory via VirtualAlloc/VirtualAllocEx, the requested size needs to be reserved in the pagefile. This was true in the first Win NT system, and is still true today see Managing Virtual Memory in Win32 : When memory is committed, physical pages of memory are allocated and space is reserved in a pagefile . Bare some extreme odd cases, SQL Server will always ask for MEM_COMMIT pages. And given the fact that SQL uses a Dynamic Memory Management policy that reserves upfront as much buffer pool as possible (reserves and commits in terms of VAS), SQL Server will request at start up a huge reservation of space in the pagefile. If the pagefile is not properly sized errors 801/802 will start showing up in SQL's ERRORLOG file and operations. This always causes some confusion, as administrators erroneously assume that a large RAM eliminates the need for a pagefile. In truth the contrary happens, a large RAM increases the need for pagefile, just because of the inner workings of the Windows NT memory manager. The reserved pagefile is, hopefully, never used.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/423/" ] }
2,647
Using SQL Server, how do I split a string so I can access item x? Take a string "Hello John Smith". How can I split the string by space and access the item at index 1 which should return "John"?
You may find the solution in SQL User Defined Function to Parse a Delimited String helpful (from The Code Project ). You can use this simple logic: Declare @products varchar(200) = '1|20|3|343|44|6|8765'Declare @individual varchar(20) = nullWHILE LEN(@products) > 0BEGIN IF PATINDEX('%|%', @products) > 0 BEGIN SET @individual = SUBSTRING(@products, 0, PATINDEX('%|%', @products)) SELECT @individual SET @products = SUBSTRING(@products, LEN(@individual + '|') + 1, LEN(@products)) END ELSE BEGIN SET @individual = @products SET @products = NULL SELECT @individual ENDEND
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/2647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ] }
2,649
When writing a T-SQL script that I plan on re-running, often times I use temporary tables to store temporary data. Since the temp table is created on the fly, I'd like to be able to drop that table only if it exists (before I create it). I'll post the method that I use, but I'd like to see if there is a better way.
IF Object_Id('TempDB..#TempTable') IS NOT NULLBEGIN DROP TABLE #TempTableEND
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/2649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/434/" ] }
2,658
I need to implement version control, even for just the developing I do at home. I have read about how great subversion is for the past couple of years and was about to dedicate myself to learning this on the side until I heard about Git being the up and coming version control system. Given the situation, should I hold off and see which one comes out on top? What are their relative advantages? One issue I noticed with Git is, there are not many full featured GUIs, which is important to many users on my team. Also, wouldn't mind suggestions on how to get started with one or the other. (tutorials, etc.)
The most important thing about version control is: JUST START USING IT Not using version control is a horrible idea. If you are not using version control, stop reading right now and start using it. It is very easy to convert from cvs<->svn<->git<->hg It doesn't matter which one you choose. Just pick the easiest one for you to use and start recording the history of your code. You can always migrate to another (D)VCS later. If you are looking for a easy to use GUI look at TortoiseSVN (Windows) and Versions (Mac) (Suggested by codingwithoutcomments ) Edit: pix0r said: Git has some nice features, but you won't be able to appreciate them unless you've already used something more standard like CVS or Subversion. This. Using git is pointless if you don't know what version control can do for you. Edit 2: Just saw this link on reddit: Subversion Cheat Sheet . Good quick reference for the svn command line.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/2658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/406/" ] }
2,702
I know I need to have (although I don't know why) a GROUP BY clause on the end of a SQL query that uses any aggregate functions like count , sum , avg , etc: SELECT count(userID), userNameFROM usersGROUP BY userName When else would GROUP BY be useful, and what are the performance ramifications?
To retrieve the number of widgets from each widget category that has more than 5 widgets, you could do this: SELECT WidgetCategory, count(*)FROM WidgetsGROUP BY WidgetCategoryHAVING count(*) > 5 The "having" clause is something people often forget about, instead opting to retrieve all their data to the client and iterating through it there.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/2702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ] }
2,711
Let's aggregate a list of free quality web site design templates. There are a million of these sites out there, but most are repetitive and boring. I'll start with freeCSStemplates.org I also think other sites should follow some sort of standards, for example here are freeCSStemplates standards Released for FREE under the Creative Commons Attribution 2.5 license Very lightweight in terms of images Tables-free (ie. they use no tables for layout purposes) W3C standards compliant and valid (XHTML Strict) Provided with public domain photos, generously provided by PDPhoto.org and Wikimedia Commons
Check out: Open Source Web Designs CSS Remix Best Web Gallery CSS Based CSS Beauty CSS Genius
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45/" ] }
2,714
I think most people know how to do this via the GUI (right click table, properties), but doing this in T-SQL totally rocks.
CREATE TABLE #tmpSizeChar ( table_name sysname , row_count int, reserved_size varchar(50), data_size varchar(50), index_size varchar(50), unused_size varchar(50)) CREATE TABLE #tmpSizeInt ( table_name sysname , row_count int, reserved_size_KB int, data_size_KB int, index_size_KB int, unused_size_KB int) SET NOCOUNT ONINSERT #tmpSizeCharEXEC sp_msforeachtable 'sp_spaceused ''?''' INSERT INTO #tmpSizeInt ( table_name, row_count, reserved_size_KB, data_size_KB, index_size_KB, unused_size_KB )SELECT [table_name], row_count, CAST(SUBSTRING(reserved_size, 0, PATINDEX('% %', reserved_size)) AS int)reserved_size, CAST(SUBSTRING(data_size, 0, PATINDEX('% %', data_size)) AS int)data_size, CAST(SUBSTRING(index_size, 0, PATINDEX('% %', index_size)) AS int)index_size, CAST(SUBSTRING(unused_size, 0, PATINDEX('% %', unused_size)) AS int)unused_sizeFROM #tmpSizeChar /*DROP TABLE #tmpSizeCharDROP TABLE #tmpSizeInt*/SELECT * FROM #tmpSizeIntORDER BY reserved_size_KB DESC
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/434/" ] }
2,732
Can anyone explain this behavior?Running: #!/bin/shecho "hello world" | read var1 var2echo $var1echo $var2 results in nothing being ouput, while: #!/bin/shecho "hello world" > test.fileread var1 var2 < test.fileecho $var1echo $var2 produces the expected output: helloworld Shouldn't the pipe do in one step what the redirection to test.file did in the second example? I tried the same code with both the dash and bash shells and got the same behavior from both of them.
A recent addition to bash is the lastpipe option, which allows the last command in a pipeline to run in the current shell, not a subshell, when job control is deactivated. #!/bin/bashset +m # Deactiveate job controlshopt -s lastpipeecho "hello world" | read var1 var2echo $var1echo $var2 will indeed output helloworld
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/75/" ] }
2,750
I'm wondering if it's a good idea to make verifications in getters and setters , or elsewhere in the code. This might surprise you be when it comes to optimizations and speeding up the code, I think you should not make verifications in getters and setters, but in the code where you're updating your files or database. Am I wrong?
Well, one of the reasons why classes usually contain private members with public getters/setters is exactly because they can verify data. If you have a Number than can be between 1 and 100, i would definitely put something in the setter that validates that and then maybe throw an exception that is being caught by the code. The reason is simple: If you don't do it in the setter, you have to remember that 1 to 100 limitation every time you set it, which leads to duplicated code or when you forget it, it leads to an invalid state. As for performance, i'm with Knuth here: "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/435/" ] }
2,756
Even though I have a robust and fast computer (Pentium Dual Core 2.0 with 2Gb RAM), I'm always searching for lightweight software to have on it, so it runs fast even when many apps are up and running simultaneously. On the last few weeks I've been migrating gradually to Linux and want to install a free lightweight yet useful IDE to program on C++ and PHP. Syntax highlighting and code completion tips are must-haves.
gedit Syntax highlighting Fast, lightweight Tabs GUI
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/431/" ] }
2,767
Can anyone recommend any good add-ons or plugins for Microsoft Visual Studio ? Freebies are preferred, but if it is worth the cost then that's fine.
SmartPaster - (FREE) Copy/Paste code generator for strings AnkhSvn - (FREE) SVN Source Control Integration for VS.NET VisualSVN Server - (FREE) Source Control ReSharper - IDE enhancement that helps with refactoring and productivity CodeRush - Code gen macros on steroids Refactor - Code refactoring aid CodeMaid (FREE) - Code cleanup, organization and complexity analysis CodeSmith - Code Generator GhostDoc - (FREE) Simple code commenting tool DXCore (FREE) and its many awesome plugins: DxCore Community Plugins , CR_Documentor , CodeStyleEnforcer , RedGreen TestDriven.Net - (FREE/PAY) Unit Testing Aid Reflector - (PAY) Feature rich .Net Disassembler Reflector AddIn's Web Deployment Projects - Provides additional functionality to build and deploy Web sites and Web applications ( source ). StudioTools - (FREE) Navigation assistant, code metrics tool, incremental search, file explorer in visual studio and tear off editor windows. Moved from old site (archive.org) to new site and discontinued.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/2767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/396/" ] }