source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
24,580 | How do you turn a Visual Studio build that you'd perform in the IDE into a script that you can run from the command line? | With VS2008 you can do this: devenv solution.sln /build configuration | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/24580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2541/"
]
} |
24,596 | I am considering creating my own website using Java and am trying to decide what framework to use. However, doing a quick search for Java frameworks returns more than 50 to choose from! My website is just going to be for my own enjoyment of building it in the beginning, but if it becomes popular, it would be good for it to have some scalability, or to at least be able to redesign for that. What are the main differences between the more popular frameworks? Are there instances where one significantly outperforms the others? For example, high-traffic enterprise applications versus low-traffic small applications. I'm also wondering if some are much easier to learn and use than others. Is there anyone who has experience with some of these frameworks and can make a recommendation? Does the sheer number of choices just serve as an early warning to avoid Java-based web development where possible? | I've used Tapestry 3 , Wicket , Echo , and JSF fairly extensively. I'd really recommend you look those over and pick the one that appears the easiest for you, and to most closely fit the way you prefer to work. Of them, the most comfortable for me to work with was Wicket , due to the lightweight nature of component building and simplicity of page templating. That goes doubly so if you are using your own db code instead of Hibernate or some other framework (I was never completely happy with Wicket Hibernate or Spring Integration). Echo is great if you don't mind writing all of your layout in Java. I know that is different now, but I still think that product serves a fairly narrow niche. They change the development model with every major release as well it seems. Tapestry is a great product, but it is obviously very different from the others in terms of development model as it is led mainly by one dude. Howard Lewis Ship is no doubt quite smart, but I am disappointed with their decision to basically forget backwards compatibility with each release. Again, though, for your needs this may not matter, and I've always found the Tapestry products pleasurable to work against. JSF has been out for years, and still feels like something that a Struts guy built to fix all of the problems of Struts. Without really understanding all of the problems with Struts. It still has an unfinished feel to it, although the product is obviously very flexible. I use it and have some fondness for it, with great hopes for its future. I think the next release (2.0) to be delivered in JEE6 will really bring it into its own, with a new template syntax (similar to Facelets) and a simplified component model (custom components in only 1 file... finally). And, of course, there are a million smaller frameworks and tools that get their own following ( Velocity for basic needs, raw JSPs , Struts, etc). I generally prefer component oriented frameworks myself, though. In the end, I'd recommend just taking a look at Tapestry, Wicket, and JSF and just picking the one that feels the best to you. You'll probably find one that just fits the way you like to work very quickly. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/24596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2628/"
]
} |
24,620 | What can be reasons to prevent a class from being inherited? (e.g. using sealed on a c# class)Right now I can't think of any. | Because writing classes to be substitutably extended is damn hard and requires you to make accurate predictions of how future users will want to extend what you've written. Sealing your class forces them to use composition, which is much more robust. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/24620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2374/"
]
} |
24,622 | I can set the PHP include path in the php.ini : include_path = /path/to/site/includes/ But then other websites are affected so that is no good. I can set the PHP include in the start of every file: $path = '/path/to/site/includes/';set_include_path(get_include_path() . PATH_SEPARATOR . $path); But that seems like bad practice and clutters things up. So I can make an include of that and then include it into every file: include 'includes/config.php'; or include '../includes/config.php'; This is what I'm doing right now, but the include path of config.php will change depending on what is including it. Is there a better way? Does it matter? | If you're using apache as a webserver you can override (if you allow it) settings using .htaccess files. See the PHP manual for details. Basically you put a file called .htaccess in your website root, which contains some PHP ini values. Provided you configured Apache to allow overrides, this site will use all values in your PHP config, + the values you specify in the .htaccess file. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives as stated in the page I linked. If you click through to the full listing, you see that the include path is a PHP_INI_ALL directive. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/24622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2118/"
]
} |
24,626 | Can you tell me what is the difference between abstraction and information hiding in software development? I am confused. Abstraction hides detail implementation andinformation hiding abstracts whole details of something. Update: I found a good answer for these three concepts. See the separate answer below for several citations taken from there . | Go to the source! Grady Booch says (in Object Oriented Analysis and Design, page 49, second edition): Abstraction and encapsulation are complementary concepts: abstraction focuses on the observable behavior of an object... encapsulation focuses upon the implementation that gives rise to this behavior... encapsulation is most often achieved through information hiding, which is the process of hiding all of the secrets of object that do not contribute to its essential characteristics. In other words: abstraction = the object externally; encapsulation (achieved through information hiding) = the object internally, Example: In the .NET Framework, the System.Text.StringBuilder class provides an abstraction over a string buffer. This buffer abstraction lets you work with the buffer without regard for its implementation. Thus, you're able to append strings to the buffer without regard for how the StringBuilder internally keeps track of things such the pointer to the buffer and managing memory when the buffer gets full (which it does with encapsulation via information hiding). rp | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/24626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1556/"
]
} |
24,648 | I'd like to gain better knowledge of operating system internals. Process management, memory management, and stuff like that. I was thinking of learning by getting to know either linux or BSD kernel. Which one kernel is better for learning purposes? What's the best place to start? Can you recommend any good books? | In college, I had an operating systems class where we used a book by Tanenbaum . In the class, we implemented a device driver in the Minix operating system . It was a lot of fun, and we learned a lot. One thing to note though, if you pick Minix, it is designed for learning. It is a microkernel, while Linux and BSD are a monolithic kernel, so what you learn may not be 100% translatable to be able to work with Linux or BSD, but you can still gain a lot out of it, without having to process quite as much information. As a side note, if you've read Just for Fun , Linus actually was playing with Minix before he wrote Linux, but it just wasn't enough for his purposes. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/24648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1534/"
]
} |
24,675 | Before you answer this I have never developed anything popular enough to attain high server loads. Treat me as (sigh) an alien that has just landed on the planet, albeit one that knows PHP and a few optimisation techniques. I'm developing a tool in PHP that could attain quite a lot of users, if it works out right. However while I'm fully capable of developing the program I'm pretty much clueless when it comes to making something that can deal with huge traffic. So here's a few questions on it (feel free to turn this question into a resource thread as well). Databases At the moment I plan to use the MySQLi features in PHP5. However how should I setup the databases in relation to users and content? Do I actually need multiple databases? At the moment everything's jumbled into one database - although I've been considering spreading user data to one, actual content to another and finally core site content (template masters etc.) to another. My reasoning behind this is that sending queries to different databases will ease up the load on them as one database = 3 load sources. Also would this still be effective if they were all on the same server? Caching I have a template system that is used to build the pages and swap out variables. Master templates are stored in the database and each time a template is called it's cached copy (a html document) is called. At the moment I have two types of variable in these templates - a static var and a dynamic var. Static vars are usually things like page names, the name of the site - things that don't change often; dynamic vars are things that change on each page load. My question on this: Say I have comments on different articles. Which is a better solution: store the simple comment template and render comments (from a DB call) each time the page is loaded or store a cached copy of the comments page as a html page - each time a comment is added/edited/deleted the page is recached. Finally Does anyone have any tips/pointers for running a high load site on PHP. I'm pretty sure it's a workable language to use - Facebook and Yahoo! give it great precedence - but are there any experiences I should watch out for? | No two sites are alike. You really need to get a tool like jmeter and benchmark to see where your problem points will be. You can spend a lot of time guessing and improving, but you won't see real results until you measure and compare your changes. For example, for many years, the MySQL query cache was the solution to all of our performance problems. If your site was slow, MySQL experts suggested turning the query cache on. It turns out that if you have a high write load, the cache is actually crippling. If you turned it on without testing, you'd never know. And don't forget that you are never done scaling. A site that handles 10req/s will need changes to support 1000req/s. And if you're lucking enough to need to support 10,000req/s, your architecture will probably look completely different as well. Databases Don't use MySQLi -- PDO is the 'modern' OO database access layer. The most important feature to use is placeholders in your queries. It's smart enough to use server side prepares and other optimizations for you as well. You probably don't want to break your database up at this point. If you do find that one database isn't cutting, there are several techniques to scale up, depending on your app. Replicating to additional servers typically works well if you have more reads than writes. Sharding is a technique to split your data over many machines. Caching You probably don't want to cache in your database. The database is typically your bottleneck, so adding more IO's to it is typically a bad thing. There are several PHP caches out there that accomplish similar things like APC and Zend. Measure your system with caching on and off. I bet your cache is heavier than serving the pages straight. If it takes a long time to build your comments and article data from the db, integrate memcache into your system. You can cache the query results and store them in a memcached instance. It's important to remember that retrieving the data from memcache must be faster than assembling it from the database to see any benefit. If your articles aren't dynamic, or you have simple dynamic changes after it's generated, consider writing out html or php to the disk. You could have an index.php page that looks on disk for the article, if it's there, it streams it to the client. If it isn't, it generates the article, writes it to the disk and sends it to the client. Deleting files from the disk would cause pages to be re-written. If a comment is added to an article, delete the cached copy -- it would be regenerated. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/24675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2025/"
]
} |
24,678 | I'm looking for the best JavaScript editor available as an Eclipse plugin. I've been using Spket which is good. But, is there more better one? | Eclipse HTML Editor Plugin I too have struggled with this totally obvious question. It seemed crazy that this wasn't an extremely easy-to-find feature with all the web development happening in Eclipse these days. I was very turned off by Aptana because of how bloated it is, and the fact that it starts up a local web server (by default on port 8000) everytime you start Eclipse and you can't disable this functionality . Adobe's port of JSEclipse is now a 400Mb plugin, which is equally insane. However, I just found a super-lightweight JavaScript editor called Eclipse HTML Editor Plugin , made by Amateras, which was exactly what I was looking for. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/24678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
]
} |
24,680 | My team is moving from Visual SourceSafe to Subversion soon, while developing/supporting a legacy project in Visual Basic 6.0, so I have a couple of questions: What's the best tool for Subversion IDE integration in Visual Studio 6? (or is it not worth the trouble...) Are there any best practices for using Subversion with Visual Basic 6.0? (file types to ignore, etc.) | I would agree that Tortoise SVN in Windows Explorer would be the best way to use SVN with VB6. The biggest change you will find migrating to SVN is the idea of "Check out" and "Check in" aren't exactly the same as "Update" and "Commit". . . thus, any IDE integration with VB6 is limited because VB6 supports MSSCCI, a check-out/check-in mechanism. I once used TamTam SVN ( http://www.daveswebsite.com/software/tamtamsvn/index.shtml ) with Visual Studio 2003, but stopped since I found it limiting. Merging/branching/blaming, etc. are very powerful features Tortoise SVN provides that weren't in TamTam. Tigris also has http://svnvb6.tigris.org/ , but I have not tried it. Again, while you quite possibly get an IDE to work with VB6, I would not recommend it since the greatest strength of migrating to SVN is to break the Source Safe philosophy of check-in/check-out. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/24680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/217/"
]
} |
24,723 | Jeff actually posted about this in Sanitize HTML . But his example is in C# and I'm actually more interested in a Java version. Does anyone have a better version for Java? Is his example good enough to just convert directly from C# to Java? [Update] I have put a bounty on this question because SO wasn't as popular when I asked the question as it is today (*). As for anything related to security, the more people look into it, the better it is! (*) In fact, I think it was still in closed beta | Don't do this with regular expressions. Remember, you're not protecting just against valid HTML; you're protecting against the DOM that web browsers create. Browsers can be tricked into producing valid DOM from invalid HTML quite easily. For example, see this list of obfuscated XSS attacks . Are you prepared to tailor a regex to prevent this real world attack on Yahoo and Hotmail on IE6/7/8? <HTML><BODY><?xml:namespace prefix="t" ns="urn:schemas-microsoft-com:time"><?import namespace="t" implementation="#default#time2"><t:set attributeName="innerHTML" to="XSS<SCRIPT DEFER>alert("XSS")</SCRIPT>"></BODY></HTML> How about this attack that works on IE6? <TABLE BACKGROUND="javascript:alert('XSS')"> How about attacks that are not listed on this site? The problem with Jeff's approach is that it's not a whitelist, as claimed. As someone on that page adeptly notes: The problem with it, is that the html must be clean. There are cases where you can pass in hacked html, and it won't match it, in which case it'll return the hacked html string as it won't match anything to replace. This isn't strictly whitelisting. I would suggest a purpose built tool like AntiSamy . It works by actually parsing the HTML, and then traversing the DOM and removing anything that's not in the configurable whitelist. The major difference is the ability to gracefully handle malformed HTML. The best part is that it actually unit tests for all the XSS attacks on the above site. Besides, what could be easier than this API call: public String toSafeHtml(String html) throws ScanException, PolicyException { Policy policy = Policy.getInstance(POLICY_FILE); AntiSamy antiSamy = new AntiSamy(); CleanResults cleanResults = antiSamy.scan(html, policy); return cleanResults.getCleanHTML().trim();} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/24723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1406/"
]
} |
24,772 | What are some resources for getting started writing a Firefox Addon? Is there an API guide somewhere? Is there a getting started tutorial somewhere? Is there a developer discussion board somewhere? | We tried to make https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions answer all those questions. The first three links in the documentation section are about getting started (that includes something like Adam's link, before it became stale). The newsgroup and the irc channel in the Community section are the official discussion boards. Mozilla is very complex, so any kind of API guide would be overwhelming and hard to write. So your best bet is to check the code snippets page (also linked from the MDC Extensions page), then search MDC/google, then ask in the forums. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/24772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1490/"
]
} |
24,797 | What is the best way to convert a UTC datetime into local datetime. It isn't as simple as a getutcdate() and getdate() difference because the difference changes depending on what the date is. CLR integration isn't an option for me either. The solution that I had come up with for this problem a few months back was to have a daylight savings time table that stored the beginning and ending daylight savings days for the next 100 or so years, this solution seemed inelegant but conversions were quick (simple table lookup) | Create two tables and then join to them to convert stored GMT dates to local time: TimeZones e.g.--------- ----TimeZoneId 19Name Eastern (GMT -5)Offset -5 Create the daylight savings table and populate it with as much information as you can (local laws change all the time so there's no way to predict what the data will look like years in the future) DaylightSavings---------------TimeZoneId 19BeginDst 3/9/2008 2:00 AMEndDst 11/2/2008 2:00 AM Join them like this: inner join TimeZones tz on x.TimeZoneId=tz.TimeZoneIdleft join DaylightSavings ds on tz.TimeZoneId=ds.LocalTimeZone and x.TheDateToConvert between ds.BeginDst and ds.EndDst Convert dates like this: dateadd(hh, tz.Offset + case when ds.LocalTimeZone is not null then 1 else 0 end, TheDateToConvert) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/24797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1950/"
]
} |
24,816 | Does anyone know of an easy way to escape HTML from strings in jQuery ? I need to be able to pass an arbitrary string and have it properly escaped for display in an HTML page (preventing JavaScript/HTML injection attacks). I'm sure it's possible to extend jQuery to do this, but I don't know enough about the framework at the moment to accomplish this. | Since you're using jQuery , you can just set the element's text property: // before:// <div class="someClass">text</div>var someHtmlString = "<script>alert('hi!');</script>";// set a DIV's text:$("div.someClass").text(someHtmlString);// after: // <div class="someClass"><script>alert('hi!');</script></div>// get the text in a string:var escaped = $("<div>").text(someHtmlString).html();// value: // <script>alert('hi!');</script> | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/24816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2657/"
]
} |
24,849 | Is there any JavaScript method similar to the jQuery delay() or wait() (to delay the execution of a script for a specific amount of time)? | There is the following: setTimeout(function, milliseconds); function which can be passed the time after which the function will be executed. See: Window setTimeout() Method . | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/24849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
]
} |
24,853 | In C, what is the difference between using ++i and i++ , and which should be used in the incrementation block of a for loop? | ++i will increment the value of i , and then return the incremented value. i = 1; j = ++i; (i is 2, j is 2) i++ will increment the value of i , but return the original value that i held before being incremented. i = 1; j = i++; (i is 2, j is 1) For a for loop, either works. ++i seems more common, perhaps because that is what is used in K&R . In any case, follow the guideline "prefer ++i over i++ " and you won't go wrong. There's a couple of comments regarding the efficiency of ++i and i++ . In any non-student-project compiler, there will be no performance difference. You can verify this by looking at the generated code, which will be identical. The efficiency question is interesting... here's my attempt at an answer: Is there a performance difference between i++ and ++i in C? As @OnFreund notes, it's different for a C++ object, since operator++() is a function and the compiler can't know to optimize away the creation of a temporary object to hold the intermediate value. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/24853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128/"
]
} |
24,866 | I am using Java back end for creating an XML string which is passed to the browser. Currently I am using simple string manipulation to produce this XML. Is it essential that I use some XML library in Java to produce the XML string?I find the libraries very difficult to use compared to what I need. | It's not essential, but advisable. However, if string manipulation works for you, then go for it! There are plenty of cases where small or simple XML text can be safely built by hand. Just be aware that creating XML text is harder than it looks. Here's some criteria I would consider: First: how much control do you have on the information that goes into the xml? The less control you have on the source data, the more likely you will have trouble, and the more advantageous the library becomes. For example: (a) Can you guarantee that the element names will never have a character that is illegal in a name? (b) How about quotes in an attribute's content? Can they happen, and are you handling them? (c) Does the data ever contain anything that might need to be encoded as an entity (like the less-than which often needs to be output as < ); are you doing it correctly? Second, maintainability: is the code that builds the XML easy to understand by someone else ? You probably don't want to be stuck with the code for life. I've worked with second-hand C++ code that hand-builds XML and it can be surprisingly obscure. Of course, if this is a personal project of yours, then you don't need to worry about "others": substitute "in a year" for "others" above. I wouldn't worry about performance. If your XML is simple enough that you can hand-write it, any overhead from the library is probably meaningless. Of course, your case might be different, but you should measure to prove it first. Finally, Yes; you can hand build XML text by hand if it's simple enough; but not knowing the libraries available is probably not the right reason. A modern XML library is a quite powerful tool, but it can also be daunting. However, learning the essentials of your XML library is not that hard, and it can be quite handy; among other things, it's almost a requisite in today's job marketplace. Just don't get bogged down by namespaces, schemas and other fancier features until you get the essentials. Good luck. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/24866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
]
} |
24,881 | I'm trying to solve the 3n+1 problem and I have a for loop that looks like this: for(int i = low; i <= high; ++i) { res = runalg(i); if (res > highestres) { highestres = res; } } Unfortunately I'm getting this error when I try to compile with GCC: 3np1.c:15: error: 'for' loop initial declaration used outside C99 mode I don't know what C99 mode is. Any ideas? | I'd try to declare i outside of the loop! Good luck on solving 3n+1 :-) Here's an example: #include <stdio.h>int main() { int i; /* for loop execution */ for (i = 10; i < 20; i++) { printf("i: %d\n", i); } return 0;} Read more on for loops in C here . | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/24881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128/"
]
} |
24,886 | Is there a performance difference between i++ and ++i if the resulting value is not used? | Executive summary: No. i++ could potentially be slower than ++i , since the old value of i might need to be saved for later use, but in practice all moderncompilers will optimize this away. We can demonstrate this by looking at the code for this function,both with ++i and i++ . $ cat i++.cextern void g(int i);void f(){ int i; for (i = 0; i < 100; i++) g(i);} The files are the same, except for ++i and i++ : $ diff i++.c ++i.c6c6< for (i = 0; i < 100; i++)---> for (i = 0; i < 100; ++i) We'll compile them, and also get the generated assembler: $ gcc -c i++.c ++i.c$ gcc -S i++.c ++i.c And we can see that both the generated object and assembler files are the same. $ md5 i++.s ++i.sMD5 (i++.s) = 90f620dda862cd0205cd5db1f2c8c06eMD5 (++i.s) = 90f620dda862cd0205cd5db1f2c8c06e$ md5 *.oMD5 (++i.o) = dd3ef1408d3a9e4287facccec53f7d22MD5 (i++.o) = dd3ef1408d3a9e4287facccec53f7d22 | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/24886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
]
} |
24,891 | I've always heard that in C you have to really watch how you manage memory. And I'm still beginning to learn C, but thus far, I have not had to do any memory managing related activities at all.. I always imagined having to release variables and do all sorts of ugly things. But this doesn't seem to be the case. Can someone show me (with code examples) an example of when you would have to do some "memory management" ? | There are two places where variables can be put in memory. When you create a variable like this: int a;char c;char d[16]; The variables are created in the " stack ". Stack variables are automatically freed when they go out of scope (that is, when the code can't reach them anymore). You might hear them called "automatic" variables, but that has fallen out of fashion. Many beginner examples will use only stack variables. The stack is nice because it's automatic, but it also has two drawbacks: (1) The compiler needs to know in advance how big the variables are, and (2) the stack space is somewhat limited. For example: in Windows, under default settings for the Microsoft linker, the stack is set to 1 MB, and not all of it is available for your variables. If you don't know at compile time how big your array is, or if you need a big array or struct, you need "plan B". Plan B is called the " heap ". You can usually create variables as big as the Operating System will let you, but you have to do it yourself. Earlier postings showed you one way you can do it, although there are other ways: int size;// ...// Set size to some value, based on information available at run-time. Then:// ...char *p = (char *)malloc(size); (Note that variables in the heap are not manipulated directly, but via pointers) Once you create a heap variable, the problem is that the compiler can't tell when you're done with it, so you lose the automatic releasing. That's where the "manual releasing" you were referring to comes in. Your code is now responsible to decide when the variable is not needed anymore, and release it so the memory can be taken for other purposes. For the case above, with: free(p); What makes this second option "nasty business" is that it's not always easy to know when the variable is not needed anymore. Forgetting to release a variable when you don't need it will cause your program to consume more memory that it needs to. This situation is called a "leak". The "leaked" memory cannot be used for anything until your program ends and the OS recovers all of its resources. Even nastier problems are possible if you release a heap variable by mistake before you are actually done with it. In C and C++, you are responsible to clean up your heap variables like shown above. However, there are languages and environments such as Java and .NET languages like C# that use a different approach, where the heap gets cleaned up on its own. This second method, called "garbage collection", is much easier on the developer but you pay a penalty in overhead and performance. It's a balance. (I have glossed over many details to give a simpler, but hopefully more leveled answer) | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/24891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128/"
]
} |
24,901 | We have the question is there a performance difference between i++ and ++i in C ? What's the answer for C++? | [Executive Summary: Use ++i if you don't have a specific reason to use i++ .] For C++, the answer is a bit more complicated. If i is a simple type (not an instance of a C++ class), then the answer given for C ("No there is no performance difference") holds, since the compiler is generating the code. However, if i is an instance of a C++ class, then i++ and ++i are making calls to one of the operator++ functions. Here's a standard pair of these functions: Foo& Foo::operator++() // called for ++i{ this->data += 1; return *this;}Foo Foo::operator++(int ignored_dummy_value) // called for i++{ Foo tmp(*this); // variable "tmp" cannot be optimized away by the compiler ++(*this); return tmp;} Since the compiler isn't generating code, but just calling an operator++ function, there is no way to optimize away the tmp variable and its associated copy constructor. If the copy constructor is expensive, then this can have a significant performance impact. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/24901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
]
} |
24,929 | What is the difference between the EXISTS and IN clause in SQL? When should we use EXISTS , and when should we use IN ? | The exists keyword can be used in that way, but really it's intended as a way to avoid counting: --this statement needs to check the entire tableselect count(*) from [table] where ...--this statement is true as soon as one match is foundexists ( select * from [table] where ... ) This is most useful where you have if conditional statements, as exists can be a lot quicker than count . The in is best used where you have a static list to pass: select * from [table] where [field] in (1, 2, 3) When you have a table in an in statement it makes more sense to use a join , but mostly it shouldn't matter. The query optimiser should return the same plan either way. In some implementations (mostly older, such as Microsoft SQL Server 2000) in queries will always get a nested join plan, while join queries will use nested, merge or hash as appropriate. More modern implementations are smarter and can adjust the plan even when in is used. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/24929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2528/"
]
} |
24,959 | Debugging asp.net websites/web projects in visual studio.net 2005 with Firefox is loads slower than using IE. I've read something somewhere that there is a way of fixing this but i can't for the life of me find it again. Does anyone know what i'm on about and can point me in the right direction please? CheersJohn edit sorry rob i haven't explained myself very well(again). I prefer Firefox for debugging (firebug etc) hitting F5 when debugging with IE the browser launches really quickly and clicking around my web application is almost instant and when a breakpont is hit i get to my code straight away with no delays. hitting F5 when debugging with FireFox the browser launches really slowly (ok i have plugins that slow FF loading) but clicking around my web application is really really slow and when a breakpoint is hit it takes ages to break into code. i swear i've read something somewhere that there is a setting in Firefox (about:config maybe?) that when changed to some magic setting sorts all this out. | bingo. found the article i read before. i just changed my network.dns.ipv4OnlyDomains property in about:config to localhost. restarted firefox and now firefox performs the same as IE when debugging asp.net with visual studio (2005). hope this helps anyone else that has the same problem. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/24959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2041/"
]
} |
24,963 | I am currently learning OLAP & MDX after many years of relational database development. Any tips on getting started in MDX? What are the best books and resources to learn MDX? | A classic, albeit a bit dated, book is Fast Track to MDX . It's a great overview and a quick read, though it doesn't cover the new MDX features of SQL Server 2005. The Spofford book MDX Solutions is more up date and a little deeper, but a bit harder to get through. I also highly recommend the blogs of Mosha Pasumansky , Chris Webb , and Darren Gosbell . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/24963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1073/"
]
} |
24,965 | OK, I know there have already been questions about getting started with TDD .. However, I guess I kind of know the general concensus is to just do it , However, I seem to have the following problems getting my head into the game: When working with collections, do will still test for obvious add/remove/inserts successful, even when based on Generics etc where we kind of "know" its going to work? Some tests seem to take forever to implement.. Such as when working with string output, is there a "better" way to go about this sort of thing? (e.g. test the object model before parsing, break parsing down into small ops and test there) In my mind you should always test the "end result" but that can vary wildly and be tedious to set up. I don't have a testing framework to use (work wont pay for one) so I can "practice" more. Are there any good ones that are free for commercial use? (at the moment I am using good 'ol Debug.Assert :) Probably the biggest.. Sometimes I don't know what to expect NOT to happen.. I mean, you get your green light but I am always concerned that I may be missing a test.. Do you dig deeper to try and break the code, or leave it be and wait for it all fall over later (which will cost more).. So basically what I am looking for here is not a " just do it " but more " I did this, had problems with this, solved them by this ".. The personal experience :) | First, it is alright and normal to feel frustrated when you first start trying to use TDD in your coding style. Just don't get discouraged and quit, you will need to give it some time. It is a major paradigm shift in how we think about solving a problem in code. I like to think of it like when we switched from procedural to object oriented programming. Secondly, I feel that test driven development is first and foremost a design activity that is used to flesh out the design of a component by creating a test that first describes the API it is going to expose and how you are going to consume it's functionality. The test will help shape and mold the System Under Test until you have been able to encapsulate enough functionality to satisfy whatever tasks you happen to be working on. Taking the above paragraph in mind, let's look at your questions: If I am using a collection in my system under test, then I will setup an expectation to make sure that the code was called to insert the item and then assert the count of the collection. I don't necessarily test the Add method on my internal list. I just make sure it was called when the method that adds the item is called. I do this by adding a mocking framework into the mix, with my testing framework. Testing strings as output can be tedious. You cannot account for every outcome. You can only test what you expect based on the functionality of the system under test. You should always break your tests down to the smallest element that it is testing. Which means you will have a lot of tests, but tests that are small and fast and only test what they should, nothing else. There are a lot of open source testing frameworks to choose from. I am not going to argue which is best. Just find one you like and start using it. MbUnit nUnit xUnit All you can do is setup your tests to account for what you want to happen. If a scenario comes up that introduces a bug in your functionality, at least you have a test around the functionality to add that scenario into the test and then change your functionality until the test passes. One way to find where we may have missed a test is to use code coverage . I introduced you to the mocking term in the answer for question one. When you introduce mocking into your arsenal for TDD, it dramatically makes testing easier to abstract away the parts that are not part of the system under test. Here are some resources on the mocking frameworks out there are: Moq : Open Source RhinoMocks : Open Source TypeMock : Commercial Product NSubstitute : Open Source One way to help in using TDD, besides reading about the process, is to watch people do it. I recommend in watching the screen casts by JP Boodhoo on DNRTV . Check these out: Jean Paul Boodhoo on Test Driven Development Part 1 Jean Paul Boodhoo on Test Driven Development Part 2 Jean Paul Boodhoo on Demystifying Design Patterns Part 1 Jean Paul Boodhoo on Demystifying Design Patterns Part 2 Jean Paul Boodhoo on Demystifying Design Patterns Part 3 Jean Paul Boodhoo on Demystifying Design Patterns Part 4 Jean Paul Boodhoo on Demystifying Design Patterns Part 5 OK, these will help you see how the terms I introduced are used. It will also introduce another tool called Resharper and how it can facilitate the TDD process. I couldn't recommend this tool enough when doing TDD. Seems like you are learning the process and you are just finding some of the problems that have already been solved with using other tools. I think I would be doing an injustice to the community, if I didn't update this by adding Kent Beck's new series on Test Driven Development on Pragmatic Programmer . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/24965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
]
} |
24,991 | I have defined a Java function: static <T> List<T> createEmptyList() { return new ArrayList<T>();} One way to call it is like so: List<Integer> myList = createEmptyList(); // Compiles Why can't I call it by explicitly passing the generic type argument? : Object myObject = createEmtpyList<Integer>(); // Doesn't compile. Why? I get the error Illegal start of expression from the compiler. | When the java compiler cannot infer the parameter type by itself for a static method, you can always pass it using the full qualified method name: Class . < Type > method(); Object list = Collections.<String> emptyList(); | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/24991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/755/"
]
} |
25,007 | What's the easiest way to convert a percentage to a color ranging from Green (100%) to Red (0%), with Yellow for 50%? I'm using plain 32bit RGB - so each component is an integer between 0 and 255. I'm doing this in C#, but I guess for a problem like this the language doesn't really matter that much. Based on Marius and Andy's answers I'm using the following solution: double red = (percent < 50) ? 255 : 256 - (percent - 50) * 5.12;double green = (percent > 50) ? 255 : percent * 5.12;var color = Color.FromArgb(255, (byte)red, (byte)green, 0); Works perfectly - Only adjustment I had to make from Marius solution was to use 256, as (255 - (percent - 50) * 5.12 yield -1 when 100%, resulting in Yellow for some reason in Silverlight (-1, 255, 0) -> Yellow ... | I made this function in JavaScript. It returns the color is a css string. It takes the percentage as a variable, with a range from 0 to 100. The algorithm could be made in any language: function setColor(p){ var red = p<50 ? 255 : Math.round(256 - (p-50)*5.12); var green = p>50 ? 255 : Math.round((p)*5.12); return "rgb(" + red + "," + green + ",0)";} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/25007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1199387/"
]
} |
25,041 | Using CSS, I'm trying to specify the height of a span tag in Firefox, but it's just not accepting it (IE does). Firefox accepts the height if I use a div , but the problem with using a div is the annoying line break after it, which I can't have in this particular instance. I tried setting the CSS style attribute of: display: inline for the div , but Firefox seems to revert that to span behavior anyway and ignores the height attribute once again. | <style>#div1 { float:left; height:20px; width:20px; }#div2 { float:left; height:30px; width:30px }</style><div id="div1">FirstDiv</div><div id="div2">SecondDiv</div> As long as the container for whatever is holding div's 1 and 2 is wide enough for them to fit, this should be fine. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/25041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693/"
]
} |
25,046 | I've just started learning Lisp and I can't figure out how to compile and link lisp code to an executable. I'm using clisp and clisp -c produces two files: .fas .lib What do I do next to get an executable? | I was actually trying to do this today, and I found typing this into the CLisp REPL worked: (EXT:SAVEINITMEM "executable.exe" :QUIET t :INIT-FUNCTION 'main :EXECUTABLE t :NORC t) where main is the name of the function you want to call when the program launches, :QUIET t suppresses the startup banner, and :EXECUTABLE t makes a native executable. It can also be useful to call (EXT:EXIT) at the end of your main function in order to stop the user from getting an interactive lisp prompt when the program is done. EDIT: Reading the documentation, you may also want to add :NORC t (read link ). This suppresses loading the RC file (for example, ~/.clisprc.lisp ). | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/25046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2450/"
]
} |
25,063 | Does anyone have any suggestions on how to mentor a junior programmer ? If you have mentored someone did you follow any process or was it quite informal ? If you've been mentored in the past what kind of things did you find most helpful ? | Try to set aside between 30-60 minutes a day to review their code together. If you can't do this, then try to get together to review their code whenever they make a code commit, unless it was very basic. Have them explain why they chose the approach they took in lieu of others. A process like this helps to establish a great relationship, as well as really stimulate the student to think on their own and be able to defend their decisions. Not only does the student end up with someone approachable whom they can trust, but you'll notice an improvement in their quality of code and logic almost immediately. Edit : Also, If you are unable to commit this much time to co-review with your junior, then you probably shouldn't be mentoring them and instead see if anyone else has a schedule that would allow it. The whole point of mentoring is to actively aid in the professional development of the student, and they're not going to learn much if proper attention and guidance is not given to them. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/25063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381/"
]
} |
25,116 | In Python you can use StringIO for a file-like buffer for character data. Memory-mapped file basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is intended for binary data and is memory only, equivalent to Java's ByteArrayOutputStream ? The use-case I have is I want to create a ZIP file in memory, and ZipFile requires a file-like object. | You are probably looking for io.BytesIO class. It works exactly like StringIO except that it supports binary data: from io import BytesIObio = BytesIO(b"some initial binary data: \x00\x01") StringIO will throw TypeError: from io import StringIOsio = StringIO(b"some initial binary data: \x00\x01") | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/25116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2679/"
]
} |
25,128 | Is it possible to create images with PHP (as opposed to simply linking to them via HTML) and if so, where should I go first to learn about such a thing? | I prefer the GD library - check out the Examples , and this example: <?phpheader ("Content-type: image/png");$im = @imagecreatetruecolor(120, 20) or die("Cannot Initialize new GD image stream");$text_color = imagecolorallocate($im, 233, 14, 91);imagestring($im, 1, 5, 5, "A Simple Text String", $text_color);imagepng($im);imagedestroy($im);?> Outputs: (source: php.net ) See imagecreatetruecolor . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/25128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
]
} |
25,192 | I'm looking for a Java library for SWIFT messages. I want to parse SWIFT messages into an object model validate SWIFT messages (including SWIFT network validation rules) build / change SWIFT messages by using an object model Theoretically, I need to support all SWIFT message types. But at the moment I need MT103+, MT199, MT502, MT509, MT515 and MT535. So far I've looked at two libraries AnaSys Message Objects ( link text ) Datamation SWIFT Message Suite ( link text ) Both libraries allow to accomplish the tasks mentioned above but in both cases I'm not really happy. AnaSys uses a internal XML representation for all SWIFT messages which you need to know in order to access the fields of a message. And you need to operate on the DOM of the XML representation, there is no way to say "get the contents of field '50K' of the SWIFT message". And the Datamation library seems to have the nicer API but does not find all errors. So does anyone know other SWIFT libraries to use? | Have you looked at WIFE ? We use that in our application which translates SWIFT messages to an internal XML format and back again. We haven't had any problems with it. Also, it's licensed under the LGPL, so you can hack it up if you need to. Check it out. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/25192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2367/"
]
} |
25,238 | What's the best way to make an element of 100% minimum height across a wide range of browsers ? In particular if you have a layout with a header and footer of fixed height , how do you make the middle content part fill 100% of the space in between with the footer fixed to the bottom ? | I am using the following one: CSS Layout - 100 % height Min-height The #container element of this page has a min-height of 100%. That way, if the content requires more height than the viewport provides, the height of #content forces #container to become longer as well. Possible columns in #content can then be visualised with a background image on #container; divs are not table cells, and you don't need (or want) the physical elements to create such a visual effect. If you're not yet convinced; think wobbly lines and gradients instead of straight lines and simple color schemes. Relative positioning Because #container has a relative position, #footer will always remain at its bottom; since the min-height mentioned above does not prevent #container from scaling, this will work even if (or rather especially when) #content forces #container to become longer. Padding-bottom Since it is no longer in the normal flow, padding-bottom of #content now provides the space for the absolute #footer. This padding is included in the scrolled height by default, so that the footer will never overlap the above content. Scale the text size a bit or resize your browser window to test this layout. html,body { margin:0; padding:0; height:100%; /* needed for container min-height */ background:gray; font-family:arial,sans-serif; font-size:small; color:#666;}h1 { font:1.5em georgia,serif; margin:0.5em 0;}h2 { font:1.25em georgia,serif; margin:0 0 0.5em;} h1, h2, a { color:orange; }p { line-height:1.5; margin:0 0 1em;}div#container { position:relative; /* needed for footer positioning*/ margin:0 auto; /* center, not in IE5 */ width:750px; background:#f0f0f0; height:auto !important; /* real browsers */ height:100%; /* IE6: treaded as min-height*/ min-height:100%; /* real browsers */}div#header { padding:1em; background:#ddd url("../csslayout.gif") 98% 10px no-repeat; border-bottom:6px double gray;} div#header p { font-style:italic; font-size:1.1em; margin:0; }div#content { padding:1em 1em 5em; /* bottom padding for footer */} div#content p { text-align:justify; padding:0 1em; }div#footer { position:absolute; width:100%; bottom:0; /* stick to bottom */ background:#ddd; border-top:6px double gray;}div#footer p { padding:1em; margin:0;} Works fine for me. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/25238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1725/"
]
} |
25,259 | What is a good complete regular expression or some other process that would take the title: How do you change a title to be part of the URL like Stack Overflow? and turn it into how-do-you-change-a-title-to-be-part-of-the-url-like-stack-overflow that is used in the SEO-friendly URLs on Stack Overflow? The development environment I am using is Ruby on Rails , but if there are some other platform-specific solutions (.NET, PHP, Django ), I would love to see those too. I am sure I (or another reader) will come across the same problem on a different platform down the line. I am using custom routes, and I mainly want to know how to alter the string to all special characters are removed, it's all lowercase, and all whitespace is replaced. | Here's how we do it. Note that there are probably more edge conditions than you realize at first glance. This is the second version, unrolled for 5x more performance (and yes, I benchmarked it). I figured I'd optimize it because this function can be called hundreds of times per page. /// <summary>/// Produces optional, URL-friendly version of a title, "like-this-one". /// hand-tuned for speed, reflects performance refactoring contributed/// by John Gietzen (user otac0n) /// </summary>public static string URLFriendly(string title){ if (title == null) return ""; const int maxlen = 80; int len = title.Length; bool prevdash = false; var sb = new StringBuilder(len); char c; for (int i = 0; i < len; i++) { c = title[i]; if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) { sb.Append(c); prevdash = false; } else if (c >= 'A' && c <= 'Z') { // tricky way to convert to lowercase sb.Append((char)(c | 32)); prevdash = false; } else if (c == ' ' || c == ',' || c == '.' || c == '/' || c == '\\' || c == '-' || c == '_' || c == '=') { if (!prevdash && sb.Length > 0) { sb.Append('-'); prevdash = true; } } else if ((int)c >= 128) { int prevlen = sb.Length; sb.Append(RemapInternationalCharToAscii(c)); if (prevlen != sb.Length) prevdash = false; } if (i == maxlen) break; } if (prevdash) return sb.ToString().Substring(0, sb.Length - 1); else return sb.ToString();} To see the previous version of the code this replaced (but is functionally equivalent to, and 5x faster), view revision history of this post (click the date link). Also, the RemapInternationalCharToAscii method source code can be found here . | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/25259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632/"
]
} |
25,297 | I would like to use as and is as members of an enumeration. I know that this is possible in VB.NET to write it like this: Public Enum Test [as] = 1 [is] = 2End Enum How do I write the equivalent statement in C#?The following code does not compile: public enum Test{ as = 1, is = 2} | Prefixing reserved words in C# is done with @. public enum Test{ @as = 1, @is = 2} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/25297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2717/"
]
} |
25,343 | I am familiar with nunit for unit testing of the business layer however I am looking now to automate the test of the win forms gui layer. I have seen watin and the watin recorder for automating tests on web application by accessing the controls and automating them. However I am struggling to find a watin equivalent for windows forms (written in c# or vb.net) preferably that is open source. Does one exist or are all products based on recording mouse and keyboard presses? Update: I have looked at this blog post on white and it seems the sort of thing I am looking for. The blog post raises some issues but as white is only in version 0.6 these may be resolved. Be interested if others have used white or any others for comparison. | Check out http://www.codeplex.com/white and http://nunitforms.sourceforge.net/ . We've used the White project with success. Same Answer to a previous question Edit The White project has moved, and is now located on GitHub as part of TestStack. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/25343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33/"
]
} |
25,349 | I have a string that has some Environment.Newline in it. I'd like to strip those from the string and instead, replace the Newline with something like a comma. What would be, in your opinion, the best way to do this using C#.NET 2.0? | Why not: string s = "foobar\ngork";string v = s.Replace(Environment.NewLine,",");System.Console.WriteLine(v); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/25349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2684/"
]
} |
25,375 | Does .NET come with a class capable of representing extremely large integers, such as 100 factorial? If not, what are some good third party libraries to accomplish this? | .NET 4 has a BigInteger class Represents an arbitrarily large signed integer. The BigInteger type is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds. This type differs from the other integral types in the .NET Framework, which have a range indicated by their MinValue and MaxValue properties. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/25375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1595/"
]
} |
25,376 | I've read that Lambda Expressions are an incredibly powerful addition to C#, yet I find myself mystified by them. How can they improve my life or make my code better? Can anyone point to a good resource for learning such expressions? They seem cool as hell, but how do they relate to my day-to-day life as an asp.net developer? Edit: Thanks for the examples, and thanks for the link to Eric White's articles. I'm still digesting those now. One quick question: are lambda expressions useful for anything other than querying? Every example I've seen has been a query construct. | : are lambda expressions useful for anything other than querying Lamba expressions are nothing much other than a convenient way of writing a function 'in-line'. So they're useful any place you wanted a bit of code which can be called as though it's a separate function but which is actually written inside its caller. (In addition to keeping related code in the same location in a file, this also allows you to play fun games with variable scoping - see 'closures' for a reference.) An example of a non-query-related use of a lamba might be a bit of code which does something asynchronously that you start with ThreadPool.QueueUserWorkItem. The important point is that you could also write this using anonymous delegates (which were a C#2 introduction), or just a plain separate class member function. This http://blogs.msdn.com/jomo_fisher/archive/2005/09/13/464884.aspx is a superb step-by-step introduction into all this stuff, which might help you. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/25376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2757/"
]
} |
25,449 | I want to create a Java program that can be extended with plugins. How can I do that and where should I look for? I have a set of interfaces that the plugin must implement, and it should be in a jar. The program should watch for new jars in a relative (to the program) folder and registered them somehow. Although I do like Eclipse RCP, I think it's too much for my simple needs. Same thing goes for Spring, but since I was going to look at it anyway, I might as well try it. But still, I'd prefer to find a way to create my own plugin "framework" as simple as possible. | I've done this for software I've written in the past, it's very handy. I did it by first creating an Interface that all my 'plugin' classes needed to implement. I then used the Java ClassLoader to load those classes and create instances of them. One way you can go about it is this: File dir = new File("put path to classes you want to load here");URL loadPath = dir.toURI().toURL();URL[] classUrl = new URL[]{loadPath};ClassLoader cl = new URLClassLoader(classUrl);Class loadedClass = cl.loadClass("classname"); // must be in package.class name format That has loaded the class, now you need to create an instance of it, assuming the interface name is MyModule: MyModule modInstance = (MyModule)loadedClass.newInstance(); | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/25449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
]
} |
25,450 | Many frameworks seek to abstract away from HTML (custom tags, JSFs component system) in an effort to make dealing with that particular kettle of fish easier. Is there anything you folks have used that has a similar concept applied to CSS? Something that does a bunch of cross-browser magic for you, supports like variables (why do I have to type #3c5c8d every time I want that colour), supports calculated fields (which are 'compiled' into CSS and JS), etc. Alternatively, am I even thinking about this correctly? Am I trying to push a very square block through a very round hole? | What I found works best is to really learn CSS. I mean really learn CSS. It can be a confusing language to learn, but if you read enough about it and practice, eventually you'll learn the best way to do things. The key is to do it enough that it comes natural. CSS can be very elegant if you know what you want to do before you start and you have enough experience to do it. Granted, it is also a major PITA to do sometimes, but even cross-browser issues aren't so bad if you really practice at it and learn what works and what doesn't, and how to get around problems. All it takes is practice and in time you can become good at it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/25450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
]
} |
25,455 | While plenty of solutions exist for entering dates (such as calendars, drop-down menus, etc.), it doesn't seem like there are too many "standard" ways to ask for a time (or time range). I've personally tried drop-down menus for the hour, minute, and second fields (and sometimes an "AM/PM" field, as well). I've also tried several clock-like input devices, most of which are too hard to use for the typical end-user. I've even tried "pop-out" time selection menus (which allow you to, for example, hover over the hour "10" to receive a sub-menu that contains ":00",":15",":30", and ":45") -- but none of these methods seem natural. So far, the best (and most universal) method I have found is just using simple text fields and forcing a user to manually populate the hour, minute, and second. Alternatively, I've had good experiences creating something similar to Outlook's "Day View" which allows you to drag and drop an event to set the start and end times. Is there a "best way" to ask for this information? Is anybody using some type of time input widget that's really intuitive and easy to use? Or is there at least a way that's more efficient than using plain text boxes? | What I found works best is to really learn CSS. I mean really learn CSS. It can be a confusing language to learn, but if you read enough about it and practice, eventually you'll learn the best way to do things. The key is to do it enough that it comes natural. CSS can be very elegant if you know what you want to do before you start and you have enough experience to do it. Granted, it is also a major PITA to do sometimes, but even cross-browser issues aren't so bad if you really practice at it and learn what works and what doesn't, and how to get around problems. All it takes is practice and in time you can become good at it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/25455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1581/"
]
} |
25,458 | I constantly hear how bad reflection is to use. While I generally avoid reflection and rarely find situations where it is impossible to solve my problem without it, I was wondering... For those who have used reflection in applications, have you measured performance hits and, is it really so bad? | It is. But that depends on what you're trying to do. I use reflection to dynamically load assemblies (plugins) and its performance "penalty" is not a problem, since the operation is something I do during startup of the application. However, if you're reflecting inside a series of nested loops with reflection calls on each, I'd say you should revisit your code :) For "a couple of time" operations, reflection is perfectly acceptable and you won't notice any delay or problem with it. It's a very powerful mechanism and it is even used by .NET, so I don't see why you shouldn't give it a try. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/25458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
]
} |
25,461 | In a project I am interfacing between C++ and a C library that uses stdbool.h defined as such. #ifndef _STDBOOL_H#define _STDBOOL_H/* C99 Boolean types for compilers without C99 support *//* http://www.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html */#if !defined(__cplusplus)#if !defined(__GNUC__)/* _Bool builtin type is included in GCC */typedef enum { _Bool_must_promote_to_int = -1, false = 0, true = 1 } _Bool;#endif#define bool _Bool#define true 1#define false 0#define __bool_true_false_are_defined 1#endif#endif Some structures have bool members. So if I have one of these structures defined as local variables within a C++ function and pass it to a C function the sizes are inconsistent between C++ and C as bool is one bye in C++ and 4 in C. Does anyone have any advice to how to overcome this without resorting to my current solution which is //#define bool _Bool#define bool unsigned char Which is against the C99 standard for stdbool.h | I found the answer to my own question by finding a more compatible implementation of stdbool.h that is compliant with the C99 standard. #ifndef _STDBOOL_H#define _STDBOOL_H#include <stdint.h>/* C99 Boolean types for compilers without C99 support *//* http://www.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html */#if !defined(__cplusplus)#if !defined(__GNUC__)/* _Bool builtin type is included in GCC *//* ISO C Standard: 5.2.5 An object declared as type _Bool is large enough to store the values 0 and 1. *//* We choose 8 bit to match C++ *//* It must also promote to integer */typedef int8_t _Bool;#endif/* ISO C Standard: 7.16 Boolean type */#define bool _Bool#define true 1#define false 0#define __bool_true_false_are_defined 1#endif#endif This is taken from the Ada Class Library project. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/25461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1675/"
]
} |
25,530 | I am looking for the best method to run a Java Application as a *NIX daemon or a Windows Service. I've looked in to the Java Service Wrapper , the Apache Commons project 'jsvc' , and the Apache Commons project 'procrun' . So far, the Java Service Wrapper looks like it's the best option... but, I'm wondering if there are any other "Open Source friendly" licensed products out there. | I've had great success with Java Service Wrapper myself. I haven't looked at the others, but the major strengths of ServiceWrapper are: Great x-platform support - I've used it on Windows and Linux, and found it easy on both Solid Documentation - The docs are clear and to the point, with great examples Deep per-platform support - There are some unique features in the window service management system that are supported perfectly by service wrapper (w/o restarting). And on Windows, you will even see your app name in the process list instead of just "java.exe". Standards Compliant - Unlike many ad-hoc Java init scripts, the scripts for service wrapper tend to be compliant with LSB standards. This can end up being very important if you ever want high availability management from something like Linux Heartbeat/HA. Anyway, just my 2 cents... :) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/25530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/828/"
]
} |
25,552 | I'm currently building a Java app that could end up being run on many different platforms, but primarily variants of Solaris, Linux and Windows. Has anyone been able to successfully extract information such as the current disk space used, CPU utilisation and memory used in the underlying OS? What about just what the Java app itself is consuming? Preferrably I'd like to get this information without using JNI. | You can get some limited memory information from the Runtime class. It really isn't exactly what you are looking for, but I thought I would provide it for the sake of completeness. Here is a small example. Edit: You can also get disk usage information from the java.io.File class. The disk space usage stuff requires Java 1.6 or higher. public class Main { public static void main(String[] args) { /* Total number of processors or cores available to the JVM */ System.out.println("Available processors (cores): " + Runtime.getRuntime().availableProcessors()); /* Total amount of free memory available to the JVM */ System.out.println("Free memory (bytes): " + Runtime.getRuntime().freeMemory()); /* This will return Long.MAX_VALUE if there is no preset limit */ long maxMemory = Runtime.getRuntime().maxMemory(); /* Maximum amount of memory the JVM will attempt to use */ System.out.println("Maximum memory (bytes): " + (maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory)); /* Total memory currently available to the JVM */ System.out.println("Total memory available to JVM (bytes): " + Runtime.getRuntime().totalMemory()); /* Get a list of all filesystem roots on this system */ File[] roots = File.listRoots(); /* For each filesystem root, print some info */ for (File root : roots) { System.out.println("File system root: " + root.getAbsolutePath()); System.out.println("Total space (bytes): " + root.getTotalSpace()); System.out.println("Free space (bytes): " + root.getFreeSpace()); System.out.println("Usable space (bytes): " + root.getUsableSpace()); } }} | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/25552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693/"
]
} |
25,637 | Is there a way to shutdown a computer using a built-in Java method? | Create your own function to execute an OS command through the command line ? For the sake of an example. But know where and why you'd want to use this as others note. public static void main(String arg[]) throws IOException{ Runtime runtime = Runtime.getRuntime(); Process proc = runtime.exec("shutdown -s -t 0"); System.exit(0);} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/25637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598/"
]
} |
25,642 | I want to catch the NavigationService.Navigating event from my Page, to prevent the user from navigating forward. I have an event handler defined thusly: void PreventForwardNavigation(object sender, NavigatingCancelEventArgs e){ if (e.NavigationMode == NavigationMode.Forward) { e.Cancel = true; }} ... and that works fine. However, I am unsure exactly where to place this code: NavigationService.Navigating += PreventForwardNavigation; If I place it in the constructor of the page, or the Initialized event handler, then NavigationService is still null and I get a NullReferenceException. However, if I place it in the Loaded event handler for the Page, then it is called every time the page is navigated to. If I understand right, that means I'm handling the same event multiple times. Am I ok to add the same handler to the event multiple times (as would happen were I to use the page's Loaded event to hook it up)? If not, is there some place in between Initialized and Loaded where I can do this wiring? | Create your own function to execute an OS command through the command line ? For the sake of an example. But know where and why you'd want to use this as others note. public static void main(String arg[]) throws IOException{ Runtime runtime = Runtime.getRuntime(); Process proc = runtime.exec("shutdown -s -t 0"); System.exit(0);} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/25642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615/"
]
} |
25,653 | Is there any way to apply an attribute to a model file in ASP.NET Dynamic Data to hide the column? For instance, I can currently set the display name of a column like this: [DisplayName("Last name")]public object Last_name { get; set; } Is there a similar way to hide a column? Edit : Many thanks to Christian Hagelid for going the extra mile and giving a spot-on answer :-) | Had no idea what ASP.NET Dynamic Data was so you promted me to so some research :) Looks like the property you are looking for is [ScaffoldColumn(false)] There is also a similar property for tables [ScaffoldTable(false)] source | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/25653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
]
} |
25,665 | Is there any python module to convert PDF files into text? I tried one piece of code found in Activestate which uses pypdf but the text generated had no space between and was of no use. | Try PDFMiner . It can extract text from PDF files as HTML, SGML or "Tagged PDF" format. The Tagged PDF format seems to be the cleanest, and stripping out the XML tags leaves just the bare text. A Python 3 version is available under: https://github.com/pdfminer/pdfminer.six | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/25665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448/"
]
} |
25,672 | Been going over my predecessor's code and see usage of the "request" scope frequently. What is the appropriate usage of this scope? | There are several scopes that are available to any portion of your code: Session, Client, Cookie, Application, and Request. Some are inadvisable to use in certain ways (i.e. using Request or Application scope inside your Custom Tags or CFC's; this is coupling , violates encapsulation principles, and is considered a bad practice), and some have special purposes: Cookie is persisted on the client machine as physical cookies, and Session scoped variables are user-specific and expire with the user's session on the website. If a variable is extremely unlikely to change (constant for all intents and purposes) and can simply be initialized on application startup and never written again, generally you should put it into Application scope because this persists it between every user and every session. When properly implemented it is written once and read N times. A proper implementation of Application variables in Application.cfm might look like this: <cfif not structKeyExists(application, "dsn")> <cflock scope="application" type="exclusive" timeout="30"> <cfif not structKeyExists(application, "dsn")> <cfset application.dsn = "MyDSN" /> <cfset foo = "bar" /> <cfset x = 5 /> </cfif> </cflock></cfif> Note that the existence of the variable in the application scope is checked before and after the lock, so that if two users create a race condition at application startup, only one of them will end up setting the application variables. The benefit of this approach is that it won't constantly refresh these stored variables on every request, wasting the user's time and the server's processing cycles. The trade-off is that it is a little verbose and complex. This was greatly simplified with the addition of Application.cfc. Now, you can specify which variables are created on application startup and don't have to worry about locking and checking for existence and all of that fun stuff: <cfcomponent> <cfset this.name = "myApplicationName" /> <cffunction name="onApplicationStart" returnType="boolean" output="false"> <cfset application.dsn = "MyDSN" /> <cfset foo = "bar" /> <cfset x = 5 /> <cfreturn true /> </cffunction></cfcomponent> For more information on Application.cfc including all of the various special functions available and every little detail about what and how to use it, I recommend this post on Raymond Camden's blog . To summarize, request scope is available everywhere in your code, but that doesn't necessarily make it "right" to use it everywhere. Chances are that your predecessor was using it to break encapsulation, and that can be cumbersome to refactor out. You may be best off leaving it as-is, but understanding which scope is the best tool for the job will definitely make your future code better. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/25672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
25,730 | I have a .exe and many plug-in .dll modules that the .exe loads. (I have source for both.) A cross-platform (with source) solution would be ideal, but the platform can be narrowed to WinXP and Visual Studio (7.1/2003 in my case). The built-in VS leak detector only gives the line where new/malloc was called from, but I have a wrapper for allocations, so a full symbolic stack trace would be best. The detector would also be able to detect for a leak in both the .exe and its accompanying plug-in .dll modules. | I personally use Visual Leak Detector , though it can cause large delays when large blocks are leaked (it displays the contents of the entire leaked block). | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/25730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2666/"
]
} |
25,746 | I'm learning objective-C and Cocoa and have come across this statement: The Cocoa frameworks expect that global string constants rather than string literals are used for dictionary keys, notification and exception names, and some method parameters that take strings. I've only worked in higher level languages so have never had to consider the details of strings that much. What's the difference between a string constant and string literal? | In Objective-C, the syntax @"foo" is an immutable , literal instance of NSString . It does not make a constant string from a string literal as Mike assume. Objective-C compilers typically do intern literal strings within compilation units — that is, they coalesce multiple uses of the same literal string — and it's possible for the linker to do additional interning across the compilation units that are directly linked into a single binary. (Since Cocoa distinguishes between mutable and immutable strings, and literal strings are always also immutable, this can be straightforward and safe.) Constant strings on the other hand are typically declared and defined using syntax like this: // MyExample.h - declaration, other code references thisextern NSString * const MyExampleNotification;// MyExample.m - definition, compiled for other code to referenceNSString * const MyExampleNotification = @"MyExampleNotification"; The point of the syntactic exercise here is that you can make uses of the string efficient by ensuring that there's only one instance of that string in use even across multiple frameworks (shared libraries) in the same address space. (The placement of the const keyword matters; it guarantees that the pointer itself is guaranteed to be constant.) While burning memory isn't as big a deal as it may have been in the days of 25MHz 68030 workstations with 8MB of RAM, comparing strings for equality can take time. Ensuring that most of the time strings that are equal will also be pointer-equal helps. Say, for example, you want to subscribe to notifications from an object by name. If you use non-constant strings for the names, the NSNotificationCenter posting the notification could wind up doing a lot of byte-by-byte string comparisons when determining who is interested in it. If most of these comparisons are short-circuited because the strings being compared have the same pointer, that can be a big win. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/25746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2799/"
]
} |
25,749 | I'm learning objective-c and keep bumping into the @ symbol. It is used in different scenarios, for example at the start of a string or to synthesise accessor methods. What's does the @ symbol mean in objective-c? | The @ character isn't used in C or C++ identifiers, so it's used to introduce Objective-C language keywords in a way that won't conflict with the other languages' keywords. This enables the "Objective" part of the language to freely intermix with the C or C++ part. Thus with very few exceptions, any time you see @ in some Objective-C code, you're looking at Objective-C constructs rather than C or C++ constructs. The major exceptions are id , Class , nil , and Nil , which are generally treated as language keywords even though they may also have a typedef or #define behind them. For example, the compiler actually does treat id specially in terms of the pointer type conversion rules it applies to declarations, as well as to the decision of whether to generate GC write barriers. Other exceptions are in , out , inout , oneway , byref , and bycopy ; these are used as storage class annotations on method parameter and return types to make Distributed Objects more efficient. (They become part of the method signature available from the runtime, which DO can look at to determine how to best serialize a transaction.) There are also the attributes within @property declarations, copy , retain , assign , readonly , readwrite , nonatomic , getter , and setter ; those are only valid within the attribute section of a @property declaration. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/25749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2799/"
]
} |
25,752 | In a drop down list, I need to add spaces in front of the options in the list. I am trying <select><option>  Sample</option></select> for adding two spaces but it displays no spaces. How can I add spaces before option texts? | Isn't   the entity for space? <select><option> option 1</option><option> option 2</option></select> Works for me... EDIT: Just checked this out, there may be compatibility issues with this in older browsers, but all seems to work fine for me here. Just thought I should let you know as you may want to replace with | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/25752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
]
} |
25,765 | I'm in the process of weeding out all hardcoded values in a Java library and was wondering what framework would be the best (in terms of zero- or close-to-zero configuration) to handle run-time configuration? I would prefer XML-based configuration files, but it's not essential. Please do only reply if you have practical experience with a framework. I'm not looking for examples, but experience... | If your hardcoded values are just simple key-value pairs, you should look at java.util.Properties . It's a lot simpler than xml, easier to use, and mind-numbingly trivial to implement. If you are working with Java and the data you are storing or retrieving from disk is modeled as a key value pair (which it sounds like it is in your case), then I really can't imagine a better solution. I have used properties files for simple configuration of small packages in a bigger project, and as a more global configuration for a whole project, and I have never had problems with it. Of course this has the huge benefit of not requiring any 3rd party libraries to utilize. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/25765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448983/"
]
} |
25,771 | How can I insert compilation timestamp information into an executable I build with Visual C++ 2005? I want to be able to output something like this when I execute the program: This build XXXX was compiled at dd-mm-yy, hh:mm. where date and time reflect the time when the project was built. They should not change with each successive call of the program, unless it's recompiled. | Though not your exact format, DATE will be of the format Mmm dd yyyy, while TIME will be of the format hh:mm:ss. You can create a string like this and use it in whatever print routine makes sense for you: const char *buildString = "This build XXXX was compiled at " __DATE__ ", " __TIME__ "."; (Note on another answer: TIMESTAMP only spits out the modification date/time of the source file, not the build date/time.) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/25771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
25,785 | Is there a simple way, in a pretty standard UNIX environment with bash, to run a command to delete all but the most recent X files from a directory? To give a bit more of a concrete example, imagine some cron job writing out a file (say, a log file or a tar-ed up backup) to a directory every hour. I'd like a way to have another cron job running which would remove the oldest files in that directory until there are less than, say, 5. And just to be clear, there's only one file present, it should never be deleted. | The problems with the existing answers: inability to handle filenames with embedded spaces or newlines. in the case of solutions that invoke rm directly on an unquoted command substitution ( rm `...` ), there's an added risk of unintended globbing. inability to distinguish between files and directories (i.e., if directories happened to be among the 5 most recently modified filesystem items, you'd effectively retain fewer than 5 files, and applying rm to directories will fail). wnoise's answer addresses these issues, but the solution is GNU -specific (and quite complex). Here's a pragmatic, POSIX-compliant solution that comes with only one caveat : it cannot handle filenames with embedded newlines - but I don't consider that a real-world concern for most people. For the record, here's the explanation for why it's generally not a good idea to parse ls output: http://mywiki.wooledge.org/ParsingLs ls -tp | grep -v '/$' | tail -n +6 | xargs -I {} rm -- {} Note: This command operates in the current directory ; to target a directory explicitly , use a subshell ( (...) ) with cd : (cd /path/to && ls -tp | grep -v '/$' | tail -n +6 | xargs -I {} rm -- {}) The same applies analogously to the commands below . The above is inefficient , because xargs has to invoke rm separately for each filename . However, your platform's specific xargs implementation may allow you to solve this problem: A solution that works with GNU xargs is to use -d '\n' , which makes xargs consider each input line a separate argument, yet passes as many arguments as will fit on a command line at once : ls -tp | grep -v '/$' | tail -n +6 | xargs -d '\n' -r rm -- Note: Option -r ( --no-run-if-empty ) ensures that rm is not invoked if there's no input . A solution that works with both GNU xargs and BSD xargs (including on macOS ) - though technically still not POSIX-compliant - is to use -0 to handle NUL -separated input, after first translating newlines to NUL ( 0x0 ) chars., which also passes (typically) all filenames at once : ls -tp | grep -v '/$' | tail -n +6 | tr '\n' '\0' | xargs -0 rm -- Explanation: ls -tp prints the names of filesystem items sorted by how recently they were modified , in descending order (most recently modified items first) ( -t ), with directories printed with a trailing / to mark them as such ( -p ). Note: It is the fact that ls -tp always outputs file / directory names only, not full paths, that necessitates the subshell approach mentioned above for targeting a directory other than the current one ( (cd /path/to && ls -tp ...) ). grep -v '/$' then weeds out directories from the resulting listing, by omitting ( -v ) lines that have a trailing / ( /$ ). Caveat : Since a symlink that points to a directory is technically not itself a directory, such symlinks will not be excluded. tail -n +6 skips the first 5 entries in the listing, in effect returning all but the 5 most recently modified files, if any. Note that in order to exclude N files, N+1 must be passed to tail -n + . xargs -I {} rm -- {} (and its variations) then invokes on rm on all these files; if there are no matches at all, xargs won't do anything. xargs -I {} rm -- {} defines placeholder {} that represents each input line as a whole , so rm is then invoked once for each input line, but with filenames with embedded spaces handled correctly. -- in all cases ensures that any filenames that happen to start with - aren't mistaken for options by rm . A variation on the original problem, in case the matching files need to be processed individually or collected in a shell array : # One by one, in a shell loop (POSIX-compliant):ls -tp | grep -v '/$' | tail -n +6 | while IFS= read -r f; do echo "$f"; done# One by one, but using a Bash process substitution (<(...), # so that the variables inside the `while` loop remain in scope:while IFS= read -r f; do echo "$f"; done < <(ls -tp | grep -v '/$' | tail -n +6)# Collecting the matches in a Bash *array*:IFS=$'\n' read -d '' -ra files < <(ls -tp | grep -v '/$' | tail -n +6)printf '%s\n' "${files[@]}" # print array elements | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/25785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
]
} |
25,794 | Without local access to the server, is there any way to duplicate/clone a MySQL db (with content and without content) into another without using mysqldump ? I am currently using MySQL 4.0. | I can see you said you didn't want to use mysqldump , but I reached this page while looking for a similar solution and others might find it as well. With that in mind, here is a simple way to duplicate a database from the command line of a windows server: Create the target database using MySQLAdmin or your preferred method. In this example, db2 is the target database, where the source database db1 will be copied. Execute the following statement on a command line: mysqldump -h [server] -u [user] -p[password] db1 | mysql -h [server] -u [user] -p[password] db2 Note: There is NO space between -p and [password] | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/25794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/211/"
]
} |
25,803 | For a given class I would like to have tracing functionality i.e. I would like to log every method call (method signature and actual parameter values) and every method exit (just the method signature). How do I accomplish this assuming that: I don't want to use any 3rd partyAOP libraries for C#, I don't want to add duplicate code to all the methods that I want to trace, I don't want to change the public API of the class - users of the class should be able to call all the methods in exactly the same way. To make the question more concrete let's assume there are 3 classes: public class Caller { public static void Call() { Traced traced = new Traced(); traced.Method1(); traced.Method2(); } } public class Traced { public void Method1(String name, Int32 value) { } public void Method2(Object object) { } } public class Logger { public static void LogStart(MethodInfo method, Object[] parameterValues); public static void LogEnd(MethodInfo method); } How do I invoke Logger.LogStart and Logger.LogEnd for every call to Method1 and Method2 without modifying the Caller.Call method and without adding the calls explicitly to Traced.Method1 and Traced.Method2 ? Edit: What would be the solution if I'm allowed to slightly change the Call method? | C# is not an AOP oriented language. It has some AOP features and you can emulate some others but making AOP with C# is painful. I looked up for ways to do exactly what you wanted to do and I found no easy way to do it. As I understand it, this is what you want to do: [Log()]public void Method1(String name, Int32 value); and in order to do that you have two main options Inherit your class from MarshalByRefObject or ContextBoundObject and define an attribute which inherits from IMessageSink. This article has a good example. You have to consider nontheless that using a MarshalByRefObject the performance will go down like hell, and I mean it, I'm talking about a 10x performance lost so think carefully before trying that. The other option is to inject code directly. In runtime, meaning you'll have to use reflection to "read" every class, get its attributes and inject the appropiate call (and for that matter I think you couldn't use the Reflection.Emit method as I think Reflection.Emit wouldn't allow you to insert new code inside an already existing method). At design time this will mean creating an extension to the CLR compiler which I have honestly no idea on how it's done. The final option is using an IoC framework . Maybe it's not the perfect solution as most IoC frameworks works by defining entry points which allow methods to be hooked but, depending on what you want to achive, that might be a fair aproximation. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/25803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2800/"
]
} |
25,807 | If I have Python code class A(): passclass B(): passclass C(A, B): pass and I have class C , is there a way to iterate through it's super classed ( A and B )? Something like pseudocode: >>> magicGetSuperClasses(C)(<type 'A'>, <type 'B'>) One solution seems to be inspect module and getclasstree function. def magicGetSuperClasses(cls): return [o[0] for o in inspect.getclasstree([cls]) if type(o[0]) == type] but is this a "Pythonian" way to achieve the goal? | C.__bases__ is an array of the super classes, so you could implement your hypothetical function like so: def magicGetSuperClasses(cls): return cls.__bases__ But I imagine it would be easier to just reference cls.__bases__ directly in most cases. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/25807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2679/"
]
} |
25,865 | My good friend, Wikipedia, didn't give me a very good response to that question. So: What are language bindings? How do they work? Specifically accessing functions from code written in language X of a library written in language Y. | Let's say you create a C library to post stuff to stackoverflow. Now you want to be able to use the same library from Python. In this case, you will write Python bindings for your library. Also see SWIG: http://www.swig.org | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/25865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/416/"
]
} |
25,952 | Back when I was at school, I remember tinkering with a Mac game where you programmed little robots in a sort of pseudo-assembler language which could then battle each other. They could move themselves around the arena, look for opponents in different directions, and fire some sort of weapon. Pretty basic stuff, but I remember it quite fondly, even if I can't remember the name. Are there any good modern day equivalents? | I used to have a lot of fun coding my own robot with Robocode in college. It is Java based, the API is detailled and it's pretty easy to get a challenging robot up and running. Here is an example : public class MyFirstRobot extends Robot { public void run() { while (true) { ahead(100); turnGunRight(360); back(100); turnGunRight(360); } } public void onScannedRobot(ScannedRobotEvent e) { fire(1); } } | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/25952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
]
} |
25,969 | I am trying to INSERT INTO a table using the input from another table. Although this is entirely feasible for many database engines, I always seem to struggle to remember the correct syntax for the SQL engine of the day ( MySQL , Oracle , SQL Server , Informix , and DB2 ). Is there a silver-bullet syntax coming from an SQL standard (for example, SQL-92 ) that would allow me to insert the values without worrying about the underlying database? | Try: INSERT INTO table1 ( column1 )SELECT col1FROM table2 This is standard ANSI SQL and should work on any DBMS It definitely works for: Oracle MS SQL Server MySQL Postgres SQLite v3 Teradata DB2 Sybase Vertica HSQLDB H2 AWS RedShift SAP HANA Google Spanner | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/25969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/244/"
]
} |
25,977 | I would like to compare a screenshot of one application (could be a Web page) with a previously taken screenshot to determine whether the application is displaying itself correctly. I don't want an exact match comparison, because the aspect could be slightly different (in the case of a Web app, depending on the browser, some element could be at a slightly different location). It should give a measure of how similar are the screenshots. Is there a library / tool that already does that? How would you implement it? | This depends entirely on how smart you want the algorithm to be. For instance, here are some issues: cropped images vs. an uncropped image images with a text added vs. another without mirrored images The easiest and simplest algorithm I've seen for this is just to do the following steps to each image: scale to something small, like 64x64 or 32x32, disregard aspect ratio, use a combining scaling algorithm instead of nearest pixel scale the color ranges so that the darkest is black and lightest is white rotate and flip the image so that the lighest color is top left, and then top-right is next darker, bottom-left is next darker (as far as possible of course) Edit A combining scaling algorithm is one that when scaling 10 pixels down to one will do it using a function that takes the color of all those 10 pixels and combines them into one. Can be done with algorithms like averaging, mean-value, or more complex ones like bicubic splines. Then calculate the mean distance pixel-by-pixel between the two images. To look up a possible match in a database, store the pixel colors as individual columns in the database, index a bunch of them (but not all, unless you use a very small image), and do a query that uses a range for each pixel value, ie. every image where the pixel in the small image is between -5 and +5 of the image you want to look up. This is easy to implement, and fairly fast to run, but of course won't handle most advanced differences. For that you need much more advanced algorithms. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/25977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2680/"
]
} |
25,999 | I'm playing around with a native (non-web) single-player game I'm writing, and it occured to me that having a daily/weekly/all-time online highscore list (think Xbox Live Leaderboard) would make the game much more interesting, adding some (small) amount of community and competition. However, I'm afraid people would see such a feature as an invitation to hacking, which would discourage regular players due to impossibly high scores. I thought about the obvious ways of preventing such attempts (public/private key encryption, for example), but I've figured out reasonably simple ways hackers could circumvent all of my ideas (extracting the public key from the binary and thus sending fake encrypted scores, for example). Have you ever implemented an online highscore list or leaderboard? Did you find a reasonably hacker-proof way of implementing this? If so, how did you do it? What are your experiences with hacking attempts? | At the end of the day, you are relying on trusting the client. If the client sends replays to the server, it is easy enough to replicable or modify a successful playthrough and send that to the server. Your best bet is to raise the bar for cheating above what a player would deem worth surmounting. To do this, there are a number of proven (but oft-unmentioned) techniques you can use: Leave blacklisted cheaters in a honeypot. They can see their own scores, but no one else can. Unless they verify by logging in with a different account, they think they have successfully hacked your game. When someone is flagged as a cheater, defer any account repercussions from transpiring until a given point in the future. Make this point random, within one to three days. Typically, a cheater will try multiple methods and will eventually succeed. By deferring account status feedback until a later date, they fail to understand what got them caught. Capture all game user commands and send them to the server. Verify them against other scores within a given delta. For instance, if the player used the shoot action 200 times, but obtained a score of 200,000, but the neighboring players in the game shot 5,000 times to obtain a score of 210,000, it may trigger a threshold that flags the person for further or human investigation. Add value and persistence to your user accounts. If your user accounts have unlockables for your game, or if your game requires purchase, the weight of a ban is greater as the user cannot regain his previous account status by simply creating a new account through a web-based proxy. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/25999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/996/"
]
} |
26,002 | I want our team to develop against local instances of an Oracle database. With MS SQL, I can use SQL Express Edition. What are my options? | Oracle has an express edition as well. I believe it is more limited though (IIRC, you can only have one database on an instance) Oracle XE | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/26002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2676/"
]
} |
26,007 | Is there an easy way to iterate over an associative array of this structure in PHP: The array $searches has a numbered index, with between 4 and 5 associative parts. So I not only need to iterate over $searches[0] through $searches[n] , but also $searches[0]["part0"] through $searches[n]["partn"] . The hard part is that different indexes have different numbers of parts (some might be missing one or two). Thoughts on doing this in a way that's nice, neat, and understandable? | Nest two foreach loops : foreach ($array as $i => $values) { print "$i {\n"; foreach ($values as $key => $value) { print " $key => $value\n"; } print "}\n";} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/26007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
]
} |
26,020 | I've done this before in C++ by including sqlite.h but is there a similarly easy way in C#? | Microsoft.Data.Sqlite by Microsoft has over 9000 downloads every day, so I think you are safe using that one. Example usage from the documentation : using (var connection = new SqliteConnection("Data Source=hello.db")){ connection.Open(); var command = connection.CreateCommand(); command.CommandText = @" SELECT name FROM user WHERE id = $id "; command.Parameters.AddWithValue("$id", id); using (var reader = command.ExecuteReader()) { while (reader.Read()) { var name = reader.GetString(0); Console.WriteLine($"Hello, {name}!"); } }} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/26020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2674/"
]
} |
26,025 | I'm about to deploy a mediumsized site powered by Django. I have a dedicated Ubuntu Server. I'm really confused over which serversoftware to use. So i thought to myself: why not ask stackoverflow. What i'm looking for is: Easy to set up Fast and easy on resources Can serve mediafiles Able to serve multiple djangosites on same server I would rather not install PHP or anything else that sucks resources, and for which I have no use for. I have heard of mod_wsgi and mod_python on Apache, nginx and lighty. Which are the pros and cons of these and have i missed someone? @Barry : Somehow i feel like Apache is to bloated for me. What about the alternatives? @BrianLy : Ok I'll check out mod_wsgi some more. But why do i need Apache if i serve static files with lighty? I have also managed to serve the django app itself with lighty. Is that bad in anyway? Sorry for beeing so stupid :-) UPDATE : What about lighty and nginx - which are the uses-cases when these are the perfect choice? | Since I was looking for some more in-depth answers, I decided to research the issue myself in depth. Please let me know if I've misunderstood anything. Some general recommendation are to use a separate webserver for handling media. By separate, I mean a webserver which is not running Django. This server can be for instance: Lighttpd (Lighty) Nginx (EngineX) Or some other light-weight server Then, for Django, you can go down different paths. You can either: Serve Django via Apache and: mod_python This is the stable and recommended/well documented way. Cons: uses a lot of memory. mod_wsgi From what I understand, mod_wsgi is a newer alternative. It appears to be faster and easier on resources. mod_fastcgi When using FastCGI you are delegating the serving of Django to another process. Since mod_python includes a python interpreter in every request it uses a lot of memory. This is a way to bypass that problem. Also there is some security concerns. What you do is that you start your Django FastCGI server in a separate process and then configures apache via rewrites to call this process when needed. Or you can: Serve Django without using Apache but with another server that supports FastCGI natively: (The documentation mentions that you can do this if you don't have any Apache specific needs. I guess the reason must be to save memory.) Lighttpd This is the server that runs Youtube. It seems fast and easy to use, however i've seen reports on memoryleaks. nginx I've seen benchmarks claiming that this server is even faster than lighttpd. It's mostly documented in Russian though. Another thing, due to limitations in Python your server should be running in forked mode, not threaded. So this is my current research, but I want more opinions and experiences. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/26025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2639/"
]
} |
26,123 | I want to use Powershell to write some utilities, leveraging our own .NET components to handle the actual work. This is in place of writing a small console app to tie the calls together. My question is where I would find a good source of documentation or tutorial material to help me fast track this? | If you want to load an assembly into your PowerShell session, you can use reflection and load the assembly. [void][System.Reflection.Assembly]::LoadFrom(PathToYourAssembly) After you load your assembly, you can call static methods and create new instances of a class. A good tutorial can be found here . Both books mentioned by EBGreen are excellent. The PowerShell Cookbook is very task oriented and PowerShell in Action is a great description of the language, its focus and useability. PowerShell in Action is one of my favorite books. :) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/26123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1535/"
]
} |
26,137 | I have a couple of questions regarding VBScript and ASP Classic: What is the preferred way to access an MS SQL Server database in VBScript/ASP? What are best practices in regards to separating model from view from controller? Any other things I should know about either VBScript or ASP? If you haven't noticed, I'm new at VBScript coding. I realize numbers 2 & 3 are kind of giant "black hole" questions that are overly general, so don't think that I'm expecting to learn everything there is to know about those two questions from here. | ADO is an excellent way to access a database in VBScript/Classic ASP. Dim db: Set db = Server.CreateObject("ADODB.Connection")db.Open "yourconnectionstring -> see connectionstrings.com"Dim rs: Set rs = db.Execute("SELECT firstName from Employees")While Not rs.EOF Response.Write rs("firstName") rs.MoveNextWendrs.Close More info here: http://www.technowledgebase.com/2007/06/12/vbscript-how-to-create-an-ado-connection-and-run-a-query/ One caveat is that if you are returning a MEMO field in a recordset, be sure you only select ONE MEMO field at a time, and make sure it is the LAST column in your query. Otherwise you will run into problems.(Reference: http://lists.evolt.org/archive/Week-of-Mon-20040329/157305.html ) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/26137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
]
} |
26,147 | I'd love to know if there is such a thing as a Gecko.NET ;) I mean, just like we can embed a WebView and that is an "instance" of IE7 inside any Windows Forms application (and tell it to navigateto(fancy_url); ). I'd love to use Firefox or WebKit. Anybody tried this? UPDATE : Please bear in mind that although it is possible to embed Gecko using the mentioned controls, it is still impossible to print while using Gecko. UPDATE March 2010 : It’s still not possible to print natively using GeckoFX, however a couple of methods exist that may be enough, depending upon what you’re trying to do. See: http://geckofx.org/viewtopic.php?id=796 for more information. UPDATE October 2013 : I am no longer doing Windows development so I have no interest in this, but seems like the development of Gecko can be found here: https://bitbucket.org/geckofx and it seems to be recently updated. Leaving this here for future Windows devs ;) UPDATE January 2017 : I have gotten an email from a company called TeamDev . They created a Chromium-based .NET browser component called "DotNetBrowser" which can be used to display modern web pages in Windows Forms applications. To quote the email directly: Here are some details about the component, which might be helpful: DotNetBrowser is based on Chromium, thus supporting HTML5, CSS3, JS and the latest web standards. The underlying Chromium version of the library is regularly updated. The component is suitable for WPF as well as Windows Forms desktop applications, and works both for C# and VB.NET. The library is licensed commercially, however free licences are provided for Open Source and academic projects. Disclaimer: I have not used this DotNetBrowser for I no longer do Windows Development but may be worth checking if you're looking for a solution to this. | http://code.google.com/p/geckofx/ This is a nice .NET-wrapped version of Gecko | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/26147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2684/"
]
} |
26,151 | C++ 0x has template aliases (sometimes referred to as template typedefs). See here . Current spec of C++ does not. What do you like to use as work around ? Container objects or Macros ?Do you feel its worth it ? | What do you like to use as work around ? Container objects or Macros ? Do you feel its worth it ? The canonical way is to use a metafunction like thus: template <typename T>struct my_string_map { typedef std::map<std::string, T> type;};// Invoke:my_string_map<int>::type my_str_int_map; This is also used in the STL ( allocator::rebind<U> ) and in many libraries including Boost. We use it extensively in a bioinformatical library . It's bloated, but it's the best alternative 99% of the time. Using macros here is not worth the many downsides. (EDIT: I've amended the code to reflect Boost/STL conventions as pointed out by Daniel in his comment.) | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/26151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2759/"
]
} |
26,158 | How does a stack overflow occur and what are the best ways to make sure it doesn't happen, or ways to prevent one, particularly on web servers, but other examples would be interesting as well? | Stack A stack, in this context, is the last in, first out buffer you place data while your program runs. Last in, first out (LIFO) means that the last thing you put in is always the first thing you get back out - if you push 2 items on the stack, 'A' and then 'B', then the first thing you pop off the stack will be 'B', and the next thing is 'A'. When you call a function in your code, the next instruction after the function call is stored on the stack, and any storage space that might be overwritten by the function call. The function you call might use up more stack for its own local variables. When it's done, it frees up the local variable stack space it used, then returns to the previous function. Stack overflow A stack overflow is when you've used up more memory for the stack than your program was supposed to use. In embedded systems you might only have 256 bytes for the stack, and if each function takes up 32 bytes then you can only have function calls 8 deep - function 1 calls function 2 who calls function 3 who calls function 4 .... who calls function 8 who calls function 9, but function 9 overwrites memory outside the stack. This might overwrite memory, code, etc. Many programmers make this mistake by calling function A that then calls function B, that then calls function C, that then calls function A. It might work most of the time, but just once the wrong input will cause it to go in that circle forever until the computer recognizes that the stack is overblown. Recursive functions are also a cause for this, but if you're writing recursively (ie, your function calls itself) then you need to be aware of this and use static/global variables to prevent infinite recursion. Generally, the OS and the programming language you're using manage the stack, and it's out of your hands. You should look at your call graph (a tree structure that shows from your main what each function calls) to see how deep your function calls go, and to detect cycles and recursion that are not intended. Intentional cycles and recursion need to be artificially checked to error out if they call each other too many times. Beyond good programming practices, static and dynamic testing, there's not much you can do on these high level systems. Embedded systems In the embedded world, especially in high reliability code (automotive, aircraft, space) you do extensive code reviews and checking, but you also do the following: Disallow recursion and cycles - enforced by policy and testing Keep code and stack far apart (code in flash, stack in RAM, and never the twain shall meet) Place guard bands around the stack - empty area of memory that you fill with a magic number (usually a software interrupt instruction, but there are many options here), and hundreds or thousands of times a second you look at the guard bands to make sure they haven't been overwritten. Use memory protection (ie, no execute on the stack, no read or write just outside the stack) Interrupts don't call secondary functions - they set flags, copy data, and let the application take care of processing it (otherwise you might get 8 deep in your function call tree, have an interrupt, and then go out another few functions inside the interrupt, causing the blowout). You have several call trees - one for the main processes, and one for each interrupt. If your interrupts can interrupt each other... well, there be dragons... High-level languages and systems But in high level languages run on operating systems: Reduce your local variable storage (local variables are stored on the stack - although compilers are pretty smart about this and will sometimes put big locals on the heap if your call tree is shallow) Avoid or strictly limit recursion Don't break your programs up too far into smaller and smaller functions - even without counting local variables each function call consumes as much as 64 bytes on the stack (32 bit processor, saving half the CPU registers, flags, etc) Keep your call tree shallow (similar to the above statement) Web servers It depends on the 'sandbox' you have whether you can control or even see the stack. Chances are good you can treat web servers as you would any other high level language and operating system - it's largely out of your hands, but check the language and server stack you're using. It is possible to blow the stack on your SQL server, for instance. -Adam | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/26158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1935/"
]
} |
26,176 | Does your work environment use Harvest SCM? I've used this now at two different locations and find it appalling. In one situation I wrote a conversion script so I could use CVS locally and then daily import changes to the Harvest system while I was sleeping. The corp was fanatic about using Harvest, despite 80% of the programmers crying for something different. It was needlessly complicated, slow and heavy. It is now a job requirement for me that Harvest is not in use where I work. Has anyone else used Harvest before? What's your experience? As bad as mine? Did you employ other, different workarounds? Why is this product still purchased today? | Chances are, your company has some sort of contract with CA - are you using a lot of other CA software in-house? Edit: Guess so! | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/26176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2836/"
]
} |
26,196 | I am looking for a very fast way to filter down a collection in C#. I am currently using generic List<object> collections, but am open to using other structures if they perform better. Currently, I am just creating a new List<object> and looping thru the original list. If the filtering criteria matches, I put a copy into the new list. Is there a better way to do this? Is there a way to filter in place so there is no temporary list required? | If you're using C# 3.0 you can use linq, which is way better and way more elegant: List<int> myList = GetListOfIntsFromSomewhere();// This will filter ints that are not > 7 out of the list; Where returns an// IEnumerable<T>, so call ToList to convert back to a List<T>.List<int> filteredList = myList.Where(x => x > 7).ToList(); If you can't find the .Where , that means you need to import using System.Linq; at the top of your file. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/26196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2470/"
]
} |
26,233 | Given a URL, what would be the most efficient code to download the contents of that web page? I am only considering the HTML, not associated images, JS and CSS. | public static void DownloadFile(string remoteFilename, string localFilename){ WebClient client = new WebClient(); client.DownloadFile(remoteFilename, localFilename);} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/26233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2141/"
]
} |
26,255 | What JavaScript keywords (function names, variables, etc) are reserved? | Here is my poem, which includes all of the reserved keywords in JavaScript, and is dedicated to those who remain honest in the moment, and not just try to score: Let this long package float, Goto private class if short.While protected with debugger case, Continue volatile interface.Instanceof super synchronized throw, Extends final export throws. Try import double enum? - False, boolean, abstract function, Implements typeof transient break!Void static, default do, Switch int native new. Else, delete null public var In return for const, true, char…Finally catch byte. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/26255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/399/"
]
} |
26,260 | The first time I load the website in the production web server, it start very slow, subsequent pages load very quickly (included the home page). I precompiled the site, but nothing changes. I don't have any code at Application start.I don't have cached items. Any ideas? How can I find out what is happening? | It's just your app domain loading up and loading any binaries into memory. Also, it's initializing static variables, so if you have a static variable that loads up a lot of data from the db, it might take a bit. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/26260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2385/"
]
} |
26,301 | What algorithm taught you the most about programming or a specific language feature? We have all had those moments where all of a sudden we know, just know, we have learned an important lesson for the future based on finally understanding an algorithm written by a programmer a couple of steps up the evolutionary ladder. Whose ideas and code had the magic touch on you? | "To iterate is human, to recurse divine" - quoted in 1989 at college. P.S. Posted by Woodgnome while waiting for invite to join | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/26301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/269/"
]
} |
26,305 | I want to be able to play sound files in my program. Where should I look? | I wrote the following code that works fine. But I think it only works with .wav format. public static synchronized void playSound(final String url) { new Thread(new Runnable() { // The wrapper thread is unnecessary, unless it blocks on the // Clip finishing; see comments. public void run() { try { Clip clip = AudioSystem.getClip(); AudioInputStream inputStream = AudioSystem.getAudioInputStream( Main.class.getResourceAsStream("/path/to/sounds/" + url)); clip.open(inputStream); clip.start(); } catch (Exception e) { System.err.println(e.getMessage()); } } }).start();} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/26305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
]
} |
26,362 | Has anyone managed to use ItemizedOverlays in Android Beta 0.9? I can't get it to work, but I'm not sure if I've done something wrong or if this functionality isn't yet available. I've been trying to use the ItemizedOverlay and OverlayItem classes. Their intended purpose is to simulate map markers (as seen in Google Maps Mashups) but I've had problems getting them to appear on the map. I can add my own custom overlays using a similar technique, it's just the ItemizedOverlays that don't work. Once I've implemented my own ItemizedOverlay (and overridden createItem ), creating a new instance of my class seems to work (I can extract OverlayItems from it) but adding it to a map's Overlay list doesn't make it appear as it should. This is the code I use to add the ItemizedOverlay class as an Overlay on to my MapView . // Add the ItemizedOverlay to the Mapprivate void addItemizedOverlay() { Resources r = getResources(); MapView mapView = (MapView)findViewById(R.id.mymapview); List<Overlay> overlays = mapView.getOverlays(); MyItemizedOverlay markers = new MyItemizedOverlay(r.getDrawable(R.drawable.icon)); overlays.add(markers); OverlayItem oi = markers.getItem(0); markers.setFocus(oi); mapView.postInvalidate();} Where MyItemizedOverlay is defined as: public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> { public MyItemizedOverlay(Drawable defaultMarker) { super(defaultMarker); populate(); } @Override protected OverlayItem createItem(int index) { Double lat = (index+37.422006)*1E6; Double lng = -122.084095*1E6; GeoPoint point = new GeoPoint(lat.intValue(), lng.intValue()); OverlayItem oi = new OverlayItem(point, "Marker", "Marker Text"); return oi; } @Override public int size() { return 5; } } | For the sake of completeness I'll repeat the discussion on Reto's post over at the Android Groups here . It seems that if you set the bounds on your drawable it does the trick: Drawable defaultMarker = r.getDrawable(R.drawable.icon);// You HAVE to specify the bounds! It seems like the markers are drawn// through Drawable.draw(Canvas) and therefore must have its bounds set// before drawing.defaultMarker.setBounds(0, 0, defaultMarker.getIntrinsicWidth(), defaultMarker.getIntrinsicHeight());MyItemizedOverlay markers = new MyItemizedOverlay(defaultMarker);overlays.add(markers); By the way, the above is shamelessly ripped from the demo at MarcelP.info . Also, here is a good howto . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/26362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/822/"
]
} |
26,366 | For the past 10 years or so there have been a smattering of articles and papers referencing Christopher Alexander's newer work "The Nature of Order" and how it can be applied to software. Unfortunately, the only works I can find are from James Coplien and Richard Gabriel; there is nothing beyond that, at least from my attempts to find such things through google. Is this kind of discussion happening anywhere? MSN @Georgia My question isn't about design patterns or pattern languages; it's about trying to see if more of Christopher Alexander's work can be applied to software (which it probably can, since it has even less physical constraints than architecture and building). Design patterns and pattern languages seem to have embraced the structure of Alexander's design patterns, but not many capture the essence. The essence being something beyond solving a problem in a particular context. It's difficult to explain without using some of Alexander's later works as a reference point. Edit: No, I take that back. For example, there's an architectural design pattern that is called Alcoves. The pattern has a context that isn't just rooted in the circumstances of the situation but also rooted in fundamentals about the purpose of buildings: that they are structures to be lived in and must promote living in them. In the case of the Alcove pattern, the context is that you want an area that allows for multiple people to be in the same area doing different things, because it is important for family members to be physically together as well as to be able to do things that tend to distract other family members. Most software design patterns describe a problem in a context, but they make no deeper statement about why the problem is important, or why the problem is something that is fundamental to software. It makes it very easy to apply design patterns inappropriately or blithely, which is the exact opposite of the intent of design patterns to began with. MSN | For the sake of completeness I'll repeat the discussion on Reto's post over at the Android Groups here . It seems that if you set the bounds on your drawable it does the trick: Drawable defaultMarker = r.getDrawable(R.drawable.icon);// You HAVE to specify the bounds! It seems like the markers are drawn// through Drawable.draw(Canvas) and therefore must have its bounds set// before drawing.defaultMarker.setBounds(0, 0, defaultMarker.getIntrinsicWidth(), defaultMarker.getIntrinsicHeight());MyItemizedOverlay markers = new MyItemizedOverlay(defaultMarker);overlays.add(markers); By the way, the above is shamelessly ripped from the demo at MarcelP.info . Also, here is a good howto . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/26366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1799/"
]
} |
26,369 | I have a .NET 2.0 Windows Forms application. Where is the best place the store user settings (considering Windows guidelines)? Some people pointed to Application.LocalUserAppDataPath . However, that creates a folder structure like: C:\Documents and Settings\user_name\Local Settings\Application Data\company_name\product_name\product_version\ If I release version 1 of my application and store an XML file there, then release version 2, that would change to a different folder, right? I'd prefer to have a single folder, per user, to store settings, regardless of the application version. | I love using the built-in Application Settings . Then you have built in support for using the settings designer if you want at design-time, or at runtime to use: // read settingstring setting1 = (string)Settings.Default["MySetting1"];// save settingSettings.Default["MySetting2"] = "My Setting Value";// you can force a save withProperties.Settings.Default.Save(); It does store the settings in a similar folder structure as you describe (with the version in the path). However, with a simple call to: Properties.Settings.Default.Upgrade(); The app will pull all previous versions settings in to save in. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/26369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2868/"
]
} |
26,393 | I've seen news of John Resig's fast new selector engine named Sizzle pop up in quite a few places, but I don't know what a selector engine is, nor have any of the articles given an explanation of what it is. I know Resig is the creator of jQuery, and that Sizzle is something in Javascript, but beyond that I don't know what it is. So, what is a selector engine? Thanks! | A selector engine is used to query a page's DOM for particular elements, based on some sort of query (usually CSS syntax or similar). For example, this jQuery: $('div') Would search for and return all of the <div> elements on the page. It uses jQuery's selector engine to do that. Optimizing the selector engine is a big deal because almost every operation you perform with these frameworks is based on some sort of DOM query. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/26393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1266/"
]
} |
26,433 | Say I have three files (template_*.txt): template_x.txt template_y.txt template_z.txt I want to copy them to three new files (foo_*.txt). foo_x.txt foo_y.txt foo_z.txt Is there some simple way to do that with one command, e.g. cp --enableAwesomeness template_*.txt foo_*.txt | for f in template_*.txt; do cp $f foo_${f#template_}; done | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/26433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/437/"
]
} |
26,455 | Do you use Design by Contract professionally? Is it something you have to do from the beginning of a project, or can you change gears and start to incorporate it into your software development lifecycle? What have you found to be the pros/cons of the design approach? I came across the Design by Contract approach in a grad school course. In the academic setting, it seemed to be a pretty useful technique. But I don't currently use Design by Contract professionally, and I don't know any other developers that are using it. It would be good to hear about its actual usage from the SO crowd. | I can't recommend it highly enough. It's particularly nice if you have a suite that takes inline documentation contract specifications, like so: // @returns null iff x = 0public foo(int x) { ...} and turns them into generated unit tests, like so: public test_foo_returns_null_iff_x_equals_0() { assertNull foo(0);} That way, you can actually see the tests you're running, but they're auto-generated. Generated tests shouldn't be checked into source control, by the way. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/26455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
26,458 | Is there any IDE that simplifies creating Swing applications (ideally something along the lines of Visual Studio) | Like others have mentioned, NetBeans' visual editor is pretty good, but it's based pretty heavily on the Swing Application Framework , so you'd need to get an understanding of how it works to properly use it (although you don't need to dig in to just test things). Other than that there are also: the IntelliJ IDEA visual editor ( flash demo of the features ) and Eclipse's Visual Editor Personally I've used NetBeans' and IDEA's visual editors. Both are nice, but I thought NetBeans had a leg up, because it doesn't use any proprietary way of saving the GUI structure and instead does something similar to what Visual Studio does - auto-generating the code that you can then add to. IDEA stores the information in a separate file which means you have to use IDEA to edit the layout visually later. I have not used Eclipse's Visual Editor. My vote is for NetBeans' visual editor. I think it satisfies what most people are looking for in a visual editor and leaves it flexible enough to plug the holes manually through code without affecting the visual editor (so you can switch back and forth between code and design views without breaking either). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/26458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2875/"
]
} |
26,551 | I need to pass an ID and a password to a batch file at the time of running rather than hardcoding them into the file. Here's what the command line looks like: test.cmd admin P@55w0rd > test-log.txt | Another useful tip is to use %* to mean "all". For example: echo offset arg1=%1set arg2=%2shiftshiftfake-command /u %arg1% /p %arg2% %* When you run: test-command admin password foo bar The above batch file will run: fake-command /u admin /p password admin password foo bar I may have the syntax slightly wrong, but this is the general idea. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/26551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
]
} |
26,552 | What are the advantages and disadvantages of turning NOCOUNT off in SQL server queries? | From SQL BOL: SET NOCOUNT ON prevents the sending of DONE_IN_PROC messages to the client for each statement in a stored procedure. For stored procedures that contain several statements that do not return much actual data, setting SET NOCOUNT to ON can provide a significant performance boost , because network traffic is greatly reduced. See http://msdn.microsoft.com/en-us/library/ms189837.aspx for more details. Also, this article on SQLServerCentral is great on this subject: Performance Effects of NOCOUNT | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/26552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2141/"
]
} |
26,559 | I know there are a lot of positive things mod-rewrite accomplishes. But are there any negative? Obviously if you have poorly written rules your going to have problems. But what if you have a high volume site and your constantly using mod-rewrite, is it going to have a significant impact on performance? I did a quick search for some benchmarks on Google and didn't find much. | I've used mod_rewrite on sites that get millions/hits/month without any significant performance issues. You do have to know which rewrites get applied first depending on your rules. Using mod_rewrite is most likely faster than parsing the URL with your current language. If you are really worried about performance, don't use .htaccess files, those are slow. Put all your rewrite rules in your Apache config, which is only read once on startup. .htaccess files get re-parsed on every request, along with every .htaccess file in parent folders. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/26559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2687/"
]
} |
26,567 | I have a report with many fields that I'm trying to get down to 1 page horizontally (I don't care whether it's 2 or 200 pages vertically... just don't want to have to deal with 2 pages wide by x pages long train-wreck). That said, it deals with contact information. My idea was to do: Name: Address: City: State: ...Jon Doe Addr1 ThisTown XX ... Addr2 Addr3-----------------------------------------------Jane Doe Addr1 ThisTown XX ... Addr2 Addr3----------------------------------------------- Is there some way to set a textbox to be multi-line (or the SQL result)? Have I missed something bloody obvious? The CanGrow Property is on by default, and I've double checked that this is true. My problem is that I don't know how to force a line-break. I get the 3 address fields that just fills a line, then wraps to another. I've tried /n , \n (since I can never remember which is the correct slash to put), <br> , <br /> (since the report will be viewed in a ReportViewer control in an ASP.NET website). I can't think of any other ways to wrap the text. Is there some way to get the results from the database as 3 lines of text/characters? | Alter the report's text box to: = Fields!Addr1.Value + VbCrLf + Fields!Addr2.Value + VbCrLf + Fields!Addr3.Value | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/26567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2156/"
]
} |
26,595 | Is there any difference between: if foo is None: pass and if foo == None: pass The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might? | is always returns True if it compares the same object instance Whereas == is ultimately determined by the __eq__() method i.e. >>> class Foo(object): def __eq__(self, other): return True>>> f = Foo()>>> f == NoneTrue>>> f is NoneFalse | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/26595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/156/"
]
} |
26,620 | In my web app, I submit some form fields with jQuery's $.getJSON() method. I am having some problems with the encoding. The character-set of my app is charset=ISO-8859-1 , but I think these fields are submitted with UTF-8 . How I can set encoding used in $.getJSON calls? | I think that you'll probably have to use $.ajax() if you want to change the encoding, see the contentType param below (the success and error callbacks assume you have <div id="success"></div> and <div id="error"></div> in the html): $.ajax({ type: "POST", url: "SomePage.aspx/GetSomeObjects", contentType: "application/json; charset=utf-8", dataType: "json", data: "{id: '" + someId + "'}", success: function(json) { $("#success").html("json.length=" + json.length); itemAddCallback(json); }, error: function (xhr, textStatus, errorThrown) { $("#error").html(xhr.responseText); }}); I actually just had to do this about an hour ago, what a coincidence! | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/26620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
]
} |
26,638 | I want to parse some HTML in order to find the values of some attributes/tags etc. What HTML parsers do you recommend? Any pros and cons? | NekoHTML , TagSoup , and JTidy will allow you to parse HTML and then process with XML tools, like XPath. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/26638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
]
} |
26,652 | Is there a way to make a TSQL variable constant? | No, but you can create a function and hardcode it in there and use that. Here is an example: CREATE FUNCTION fnConstant()RETURNS INTASBEGIN RETURN 2ENDGOSELECT dbo.fnConstant() | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/26652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1874/"
]
} |
26,663 | So far, I've only used Rational Quantify. I've heard great things about Intel's VTune, but have never tried it! Edit: I'm mostly looking for software that will instrument the code, as I guess that's about the only way to get very fine results. See also: What are some good profilers for native C++ on Windows? | For linux development (although some of these tools might work on other platforms). These are the two big names I know of, there's plenty of other smaller ones that haven't seen active development in a while. Valgrind TAU - Tuning and Analysis Utilities | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/26663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2638/"
]
} |
26,685 | I found What are mvp and mvc and what is the difference but it didn't really answer this question. I've recently started using MVC because it's part of the framework that myself and my work-partner are going to use. We chose it because it looked easy and separated process from display, are there advantages besides this that we don't know about and could be missing out on? Pros Display and Processing are seperated Cons None so far | MVC is the separation of m odel, v iew and c ontroller — nothing more, nothing less. It's simply a paradigm; an ideal that you should have in the back of your mind when designing classes. Avoid mixing code from the three categories into one class. For example, while a table grid view should obviously present data once shown, it should not have code on where to retrieve the data from, or what its native structure (the model ) is like. Likewise, while it may have a function to sum up a column, the actual summing is supposed to happen in the controller . A 'save file' dialog ( view ) ultimately passes the path, once picked by the user, on to the controller , which then asks the model for the data, and does the actual saving. This separation of responsibilities allows flexibility down the road. For example, because the view doesn't care about the underlying model, supporting multiple file formats is easier: just add a model subclass for each. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/26685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
]
} |
26,715 | How does the new Microsoft asp.net mvc implementation handle partitioning your application - for example: --index.aspx--about.aspx--contact.aspx--/feature1--/feature1/subfeature/action--/feature2/subfeature/action I guess what I am trying to say is that it seems everything has to go into the root of the views/controllers folders which could get unwieldy when working on a project that if built with web forms might have lots and lots of folders and sub-folders to partition the application. I think I get the MVC model and I like the look of it compared to web forms but still getting my head round how you would build a large project in practice. | There isn't any issues with organizing your controllers. You just need to setup the routes to take the organization into consideration. The problem you will run into is finding the view for the controller, since you changed the convention. There isn't any built in functionality for it yet, but it is easy to create a work around yourself with a ActionFilterAttribute and a custom view locator that inherits off ViewLocator. Then when creating your controller, you just specify what ViewLocator to use, so the controller knows how to find the view. I can post some code if needed. This method kind of goes along with some advice I gave another person for separating their views out for a portal using ASP.NET MVC. Here is the link to the question as a reference. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/26715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2041/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.