source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
109,580 | I'm looking to grab cookie values for the same domain within a Flash movie. Is this possible? Let's see I let a user set a variable foo and I store it using any web programming language. I can access it easily via that language, but I would like to access it via the Flash movie without passing it in via printing it within the HTML page. | If you just want to store and retrieve data, you probably want to use the SharedObject class. See Adobe's SharedObject reference for more details of that. If you want to access the HTTP cookies, you'll need to use ExternalInterface to talk to javascript. The way we do that here is to have a helper class called HTTPCookies. HTTPCookies.as: import flash.external.ExternalInterface;public class HTTPCookies{ public static function getCookie(key:String):* { return ExternalInterface.call("getCookie", key); } public static function setCookie(key:String, val:*):void { ExternalInterface.call("setCookie", key, val); }} You need to make sure you enable javascript using the 'allowScriptAccess' parameter in your flash object. Then you need to create a pair of javascript functions, getCookie and setCookie, as follows (with thanks to quirksmode.org ) HTTPCookies.js: function getCookie(key){ var cookieValue = null; if (key) { var cookieSearch = key + "="; if (document.cookie) { var cookieArray = document.cookie.split(";"); for (var i = 0; i < cookieArray.length; i++) { var cookieString = cookieArray[i]; // skip past leading spaces while (cookieString.charAt(0) == ' ') { cookieString = cookieString.substr(1); } // extract the actual value if (cookieString.indexOf(cookieSearch) == 0) { cookieValue = cookieString.substr(cookieSearch.length); } } } } return cookieValue;}function setCookie(key, val){ if (key) { var date = new Date(); if (val != null) { // expires in one year date.setTime(date.getTime() + (365*24*60*60*1000)); document.cookie = key + "=" + val + "; expires=" + date.toGMTString(); } else { // expires yesterday date.setTime(date.getTime() - (24*60*60*1000)); document.cookie = key + "=; expires=" + date.toGMTString(); } }} Once you have HTTPCookies.as in your flash project, and HTTPCookies.js loaded from your web page, you should be able to call getCookie and setCookie from within your flash movie to get or set HTTP cookies. This will only work for very simple values - strings or numbers - but for anything more complicated you really should be using SharedObject. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/109580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/497/"
]
} |
109,620 | I've been developing Winforms applications in C# for a few years now and have been interested in moving future development toward WPF, mainly because of the positive things I've been hearing about it. But, I'm wondering what sort of hurdles others have had to overcome as they migrated to WPF. Was there a significant hit to your productivity or any particular issues which you found challenging? | I'm not sure I can give you just one hurdle, because it is a complete departure from WinForms. My suggestion is get Adam Nathan's WPF Unleashed, forget everything you know about building UI's with any previous technology (Winforms, MFC, Java) and begin again at square one. If you try and do it any other way it will cause utter frustration. ETA: the reason I say to just start from scratch is because sometimes it's easier to learn new concepts if you go in with a clean slate. In the past, I've discovered that I can be my own worst enemy when it comes to learning something new if I try to carry knowledge from technology to technology (e.g. thinking that doing asmx web services for years precludes me from reading the first couple chapters of a WCF book). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/109620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7862/"
]
} |
109,710 | I've been digging through some parts of the Linux kernel, and found calls like this: if (unlikely(fd < 0)){ /* Do something */} or if (likely(!err)){ /* Do something */} I've found the definition of them: #define likely(x) __builtin_expect((x),1)#define unlikely(x) __builtin_expect((x),0) I know that they are for optimization, but how do they work? And how much performance/size decrease can be expected from using them? And is it worth the hassle (and losing the portability probably) at least in bottleneck code (in userspace, of course). | They are hint to the compiler to emit instructions that will cause branch prediction to favour the "likely" side of a jump instruction. This can be a big win, if the prediction is correct it means that the jump instruction is basically free and will take zero cycles. On the other hand if the prediction is wrong, then it means the processor pipeline needs to be flushed and it can cost several cycles. So long as the prediction is correct most of the time, this will tend to be good for performance. Like all such performance optimisations you should only do it after extensive profiling to ensure the code really is in a bottleneck, and probably given the micro nature, that it is being run in a tight loop. Generally the Linux developers are pretty experienced so I would imagine they would have done that. They don't really care too much about portability as they only target gcc, and they have a very close idea of the assembly they want it to generate. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/109710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9232/"
]
} |
109,717 | In C#, if you have multiple constructors, you can do something like this: public MyClass(Guid inputId, string inputName){ // do something}public MyClass(Guid inputId): this(inputId, "foo") {} The idea is of course code reuse. However, what is the best approach when there is a bit of complex logic needed? Say I want this constructor: public MyClass(MyOtherClass inputObject){ Guid inputId = inputObject.ID; MyThirdClass mc = inputObject.CreateHelper(); string inputText = mc.Text; mc.Dispose(); // Need to call the main Constructor now with inputId and inputText } The caveat here is that I need to create an object that has to be disposed after use. (Clarification: Not immediately, but I have to call Dispose() rather than waiting for Garbage Collection) However, I did not see a way to just call the base constructor again if I add some code inside my overloaded constructor. Is there a way to call the base constructor from within an overloaded one? Or is it possible to use public MyClass(MyOtherClass inputObject): this(inputObject.ID, inputObject.CreateHelper().Text) {} Would this automatically Dispose the generated Object from CreateHelper()? Edit: Thanks so far. Two problems: I do not control MyOtherClass and I do not have Extension Methods (only .NET 3.0...). I do control my own class though, and since I've just started writing it, I have no problem refactoring the constructors if there is a good approach. | The most common pattern used to solve this problem is to have an Initialize() method that your constructors call, but in the example you just gave, adding a static method that you called like the code below, would do the trick. public MyClass(MyOtherClass inputObject): this(inputObject.ID, GetHelperText(inputObject) {}private static string GetHelperText(MyOtherClass o){ using (var helper = o.CreateHelper()) return helper.Text;} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/109717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
]
} |
109,781 | What's the most elegant way to select out objects in an array that are unique with respect to one or more attributes? These objects are stored in ActiveRecord so using AR's methods would be fine too. | Use Array#uniq with a block: @photos = @photos.uniq { |p| p.album_id } | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/109781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1227001/"
]
} |
109,854 | I like jQuery and I was wondering if anyone have used a good plugin or (non-jQuery) JavaScript library that allows for auto-formatting of structured fields like phone numbers or dates. I know of the jquery-ui-datapicker plugin, and not what I am looking for here. You may type in a phone number as 123 which then becomes (123), additional numbers will be formatted as (123) 456 7890 Ext. 123456. If you press delete the auto-formatting stuff disappears automatically, and repositioning of the cursor, say, after (123) and pressing delete will remove the 3 and make the rest (124) 567 8901 Ext. 23456. The ones that I have played with appears unreliable. | Does the Masked Input plugin do what you need or that one you have already found to be unreliable? | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/109854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9706/"
]
} |
109,855 | Where can I find a complete reference of the ncurses C API? | I found this question a while back, but none of the answers so far answer the original question. The complete freely available API reference is available through the . . . NCURSES MAN PAGES | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/109855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19470/"
]
} |
109,859 | I am reading a .NET book, and in one of the code examples there is a class definition with this field: private DateTime? startdate What does DateTime? mean? | Since DateTime is a struct , not a class , you get a DateTime object , not a reference , when you declare a field or variable of that type. And, in the same way as an int cannot be null , so this DateTime object can never be null , because it's not a reference. Adding the question mark turns it into a nullable type , which means that either it is a DateTime object, or it is null . DateTime? is syntactic sugar for Nullable<DateTime> , where Nullable is itself a struct . | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/109859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7148/"
]
} |
109,880 | Has anybody found a good solution for lazily-evaluated lists in Perl? I've tried a number of ways to turn something like for my $item ( map { ... } @list ) { } into a lazy evaluation--by tie-ing @list, for example. I'm trying to avoid breaking down and writing a source filter to do it, because they mess with your ability to debug the code. Has anybody had any success. Or do you just have to break down and use a while loop? Note: I guess that I should mention that I'm kind of hooked on sometimes long grep-map chains for functionally transforming lists. So it's not so much the foreach loop or the while loop. It's that map expressions tend to pack more functionality into the same vertical space. | As mentioned previously, for(each) is an eager loop, so it wants to evaluate the entire list before starting. For simplicity, I would recommend using an iterator object or closure rather than trying to have a lazily evaluated array. While you can use a tie to have a lazily evaluated infinite list, you can run into troubles if you ever ask (directly or indirectly, as in the foreach above) for the entire list (or even the size of the entire list). Without writing a full class or using any modules, you can make a simple iterator factory just by using closures: sub make_iterator { my ($value, $max, $step) = @_; return sub { return if $value > $max; # Return undef when we overflow max. my $current = $value; $value += $step; # Increment value for next call. return $current; # Return current iterator value. };} And then to use it: # All the even numbers between 0 - 100.my $evens = make_iterator(0, 100, 2);while (defined( my $x = $evens->() ) ) { print "$x\n";} There's also the Tie::Array::Lazy module on the CPAN, which provides a much richer and fuller interface to lazy arrays. I've not used the module myself, so your mileage may vary. All the best, Paul | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/109880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11289/"
]
} |
109,976 | I am setting up a rails app and I just finished making some unit tests and my friend said that apparently fixtures are no longer cool and people are now using RSpec or shoulda. I was wondering what the actual benefits are to use these other toolkits. Any information at all is appreciated. -fREW | RSpec and similar frameworks are tooling designed to aid in Behavior Driven Development. They're not just a prettier way to write tests, though they do help with that. There is plenty of information on BDD here: http://behaviour-driven.org/ And wikipedia: http://en.wikipedia.org/wiki/Behavior_Driven_Development There are too many benefits to list here, so I'd recommend browsing that site a little. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/109976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448/"
]
} |
109,997 | I am curious about how do you protect your software against cracking, hacking etc. Do you employ some kind of serial number check? Hardware keys? Do you use any third-party solutions? How do you go about solving licensing issues? (e.g. managing floating licenses) EDIT: I'm not talking any open source, but strictly commercial software distribution... | There are many, many, many protections available. The key is: Assessing your target audience, and what they're willing to put up with Understanding your audience's desire to play with no pay Assessing the amount someone is willing to put forth to break your protection Applying just enough protection to prevent most people from avoiding payment, while not annoying those that use your software. Nothing is unbreakable, so it's more important to gauge these things and pick a good protection than to simply slap on the best (worst) protection you are able to afford. Simple registration codes (verified online once). Simple registration with revokable keys, verified online frequently. Encrypted key holds portion of program algorithm (can't just skip over the check - it has to be run for the program to work) Hardware key (public/private key cryptography) Hardware key (includes portion of program algorithm that runs on the key) Web service runs critical code (hackers never get to see it) And variations of the above. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/109997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15497/"
]
} |
110,018 | Anyone know? Want to be able to on the fly stamp an image with another image as a watermark, also to do large batches. Any type of existing library or a technique you know of would be great. | This will answer your question: http://www.codeproject.com/KB/GDI-plus/watermark.aspx Good luck! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/110018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18309/"
]
} |
110,031 | Several questions about functional programming languages have got me thinking about whether XSLT is a functional programming language. If not, what features are missing? Has XSLT 2.0 shortened or closed the gap? | XSLT is declarative as opposed to stateful. Although XSLT is based on functional programming ideas, it is not a full functional programming language, it lacks the ability to treat functions as a first class data type. It has elements like lazy evaluation to reduce unneeded evaluation and also the absence of explicit loops. Like a functional language though, I would think that it can be nicely parallelized with automatic safe multi threading across several processors. From Wikipedia on XSLT : As a language, XSLT is influenced by functional languages, and by text-based pattern matching languages like SNOBOL and awk. Its most direct predecessor was DSSSL, a language that performed the same function for SGML that XSLT performs for XML. XSLT can also be considered as a template processor. Here is a great site on using XSLT as a functional language with the help of FXSL. FXSL is a library that implements support for higher-order functions. Because of FXSL I don't think that XSLT has a need to be fully functional itself. Perhaps FXSL will be included as a W3C standard in the future, but I have no evidence of this. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/110031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13342/"
]
} |
110,032 | Is a Star-Schema design essential to a data warehouse? Or can you do data warehousing with another design pattern? | Using star schemas for a data warehouse system gets you several benefits and in most cases it is appropriate to use them for the top layer. You may also have an operational data store (ODS) - a normalised structure that holds 'current state' and facilitates operations such as data conformation. However there are reasonable situations where this is not desirable. I've had occasion to build systems with and without ODS layers, and had specific reasons for the choice of architecture in each case. Without going into the subtlties of data warehouse architecture or starting a Kimball vs. Inmon flame war the main benefits of a star schema are: Most database management systemshave facilities in the query optimiserto do 'Star Transformations' thatuse Bitmap Index structures or Index Intersection for fastpredicate resolution. This means that selection from a star schema can be done without hitting the fact table (which is usually much bigger than the indexes) until the selection is resolved. Partitioning a star schema is relatively straightforward as only the fact table needs to be partitioned (unless you have some biblically large dimensions). Partition elimination means that the query optimiser can ignore patitions that could not possibly participate in the query results, which saves on I/O. Slowly changing dimensions are much easier to implement on a star schema than a snowflake. The schema is easier to understand and tends to involve less joins than a snowflake or E-R schema. Your reporting team will love you for this Star schemas are much easier to use and (more importantly) make perform well with ad-hoc query tools such as Business Objects or Report Builder . As a developer you have very little control over the SQL generated by these tools so you need to give the query optimiser as much help as possible. Star schemas give the query optimiser relatively little opportunity to get it wrong. Typically your reporting layer would use star schemas unless you have a specific reason not to. If you have multiple source systems you may want to implement an Operational Data Store with a normalised or snowflake schema to accumulate the data. This is easier because an ODS typically does not do history. Historical state is tracked in star schemas where this is much easier to do than with normalised structures. A normalised or snowflaked Operational Data Store reflects 'current' state and does not hold a historical view over and above any that is inherent in the data. ODS load processes are concerned with data scrubbing and conforming, which is easier to do with a normalised structure. Once you have clean data in an ODS, dimension and fact loads can track history (changes over time) with generic or relatively simple mechanisms relatively simply; this is much easier to do with a star schema, Many ETL tools (for example) provide built-in facilities for slowly changing dimensions and implementing a generic mechanism is relatively straightforward. Layering the system in this way providies a separation of responsibilities - business and data cleansing logic is dealt with in the ODS and the star schema loads deal with historical state. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/110032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10661/"
]
} |
110,083 | String s = "";for(i=0;i<....){ s = some Assignment;} or for(i=0;i<..){ String s = some Assignment;} I don't need to use 's' outside the loop ever again. The first option is perhaps better since a new String is not initialized each time. The second however would result in the scope of the variable being limited to the loop itself. EDIT: In response to Milhous's answer. It'd be pointless to assign the String to a constant within a loop wouldn't it? No, here 'some Assignment' means a changing value got from the list being iterated through. Also, the question isn't because I'm worried about memory management. Just want to know which is better. | Limited Scope is Best Use your second option: for ( ... ) { String s = ...;} Scope Doesn't Affect Performance If you disassemble code the compiled from each (with the JDK's javap tool), you will see that the loop compiles to the exact same JVM instructions in both cases. Note also that Brian R. Bondy's "Option #3" is identical to Option #1. Nothing extra is added or removed from the stack when using the tighter scope, and same data are used on the stack in both cases. Avoid Premature Initialization The only difference between the two cases is that, in the first example, the variable s is unnecessarily initialized. This is a separate issue from the location of the variable declaration. This adds two wasted instructions (to load a string constant and store it in a stack frame slot). A good static analysis tool will warn you that you are never reading the value you assign to s , and a good JIT compiler will probably elide it at runtime. You could fix this simply by using an empty declaration (i.e., String s; ), but this is considered bad practice and has another side-effect discussed below. Often a bogus value like null is assigned to a variable simply to hush a compiler error that a variable is read without being initialized. This error can be taken as a hint that the variable scope is too large, and that it is being declared before it is needed to receive a valid value. Empty declarations force you to consider every code path; don't ignore this valuable warning by assigning a bogus value. Conserve Stack Slots As mentioned, while the JVM instructions are the same in both cases, there is a subtle side-effect that makes it best, at a JVM level, to use the most limited scope possible. This is visible in the "local variable table" for the method. Consider what happens if you have multiple loops, with the variables declared in unnecessarily large scope: void x(String[] strings, Integer[] integers) { String s; for (int i = 0; i < strings.length; ++i) { s = strings[0]; ... } Integer n; for (int i = 0; i < integers.length; ++i) { n = integers[i]; ... }} The variables s and n could be declared inside their respective loops, but since they are not, the compiler uses two "slots" in the stack frame. If they were declared inside the loop, the compiler can reuse the same slot, making the stack frame smaller. What Really Matters However, most of these issues are immaterial. A good JIT compiler will see that it is not possible to read the initial value you are wastefully assigning, and optimize the assignment away. Saving a slot here or there isn't going to make or break your application. The important thing is to make your code readable and easy to maintain, and in that respect, using a limited scope is clearly better. The smaller scope a variable has, the easier it is to comprehend how it is used and what impact any changes to the code will have. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/110083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16485/"
]
} |
110,157 | This is one of the possible ways I come out: struct RetrieveKey{ template <typename T> typename T::first_type operator()(T keyValuePair) const { return keyValuePair.first; }};map<int, int> m;vector<int> keys;// Retrieve all keystransform(m.begin(), m.end(), back_inserter(keys), RetrieveKey());// Dump all keyscopy(keys.begin(), keys.end(), ostream_iterator<int>(cout, "\n")); Of course, we can also retrieve all values from the map by defining another functor RetrieveValues . Is there any other way to achieve this easily? (I'm always wondering why std::map does not include a member function for us to do so.) | While your solution should work, it can be difficult to read depending on the skill level of your fellow programmers. Additionally, it moves functionality away from the call site. Which can make maintenance a little more difficult. I'm not sure if your goal is to get the keys into a vector or print them to cout so I'm doing both. You may try something like this: std::map<int, int> m;std::vector<int> key, value;for(std::map<int,int>::iterator it = m.begin(); it != m.end(); ++it) { key.push_back(it->first); value.push_back(it->second); std::cout << "Key: " << it->first << std::endl(); std::cout << "Value: " << it->second << std::endl();} Or even simpler, if you are using Boost: map<int,int> m;pair<int,int> me; // what a map<int, int> is made ofvector<int> v;BOOST_FOREACH(me, m) { v.push_back(me.first); cout << me.first << "\n";} Personally, I like the BOOST_FOREACH version because there is less typing and it is very explicit about what it is doing. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/110157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18638/"
]
} |
110,163 | I have a rails model that looks something like this: class Recipe < ActiveRecord::Base has_many :ingredients attr_accessor :ingredients_string attr_accessible :title, :directions, :ingredients, :ingredients_string before_save :set_ingredients def ingredients_string ingredients.join("\n") end private def set_ingredients self.ingredients.each { |x| x.destroy } self.ingredients_string ||= false if self.ingredients_string self.ingredients_string.split("\n").each do |x| ingredient = Ingredient.create(:ingredient_string => x) self.ingredients << ingredient end end endend The idea is that when I create the ingredient from the webpage, I pass in the ingredients_string and let the model sort it all out. Of course, if I am editing an ingredient I need to re-create that string. The bug is basically this: how do I inform the view of the ingredient_string (elegantly) and still check to see if the ingredient_string is defined in the set_ingredients method? | While your solution should work, it can be difficult to read depending on the skill level of your fellow programmers. Additionally, it moves functionality away from the call site. Which can make maintenance a little more difficult. I'm not sure if your goal is to get the keys into a vector or print them to cout so I'm doing both. You may try something like this: std::map<int, int> m;std::vector<int> key, value;for(std::map<int,int>::iterator it = m.begin(); it != m.end(); ++it) { key.push_back(it->first); value.push_back(it->second); std::cout << "Key: " << it->first << std::endl(); std::cout << "Value: " << it->second << std::endl();} Or even simpler, if you are using Boost: map<int,int> m;pair<int,int> me; // what a map<int, int> is made ofvector<int> v;BOOST_FOREACH(me, m) { v.push_back(me.first); cout << me.first << "\n";} Personally, I like the BOOST_FOREACH version because there is less typing and it is very explicit about what it is doing. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/110163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448/"
]
} |
110,175 | How can you automatically import the latest build/revision number in subversion? The goal would be to have that number visible on your webpage footer like SO does. | svn info <Repository-URL> or svn info --xml <Repository-URL> Then look at the result. For xml, parse /info/entry/@revision for the revision of the repository (151 in this example) or /info/entry/commit/@revision for the revision of the last commit against this path (133, useful when working with tags): <?xml version="1.0"?><info><entry kind="dir" path="cmdtools" revision="151"><url>http://myserver/svn/stumde/cmdtools</url><repository><root>http://myserver/svn/stumde</root><uuid>a148ce7d-da11-c240-b47f-6810ff02934c</uuid></repository><commit revision="133"><author>mstum</author><date>2008-07-12T17:09:08.315246Z</date></commit></entry></info> I wrote a tool ( cmdnetsvnrev , source code included) for myself which replaces the Revision in my AssemblyInfo.cs files. It's limited to that purpose though, but generally svn info and then processing is the way to go. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/110175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
]
} |
110,186 | Looking to do a very small, quick 'n dirty side project. I like the fact that the Google App Engine is running on Python with Django built right in - gives me an excuse to try that platform... but my question is this: Has anyone made use of the app engine for anything other than a toy problem? I see some good example apps out there, so I would assume this is good enough for the real deal, but wanted to get some feedback. Any other success/failure notes would be great. | I have tried app engine for my small quake watch application http://quakewatch.appspot.com/ My purpose was to see the capabilities of app engine, so here are the main points: it doesn't come by default with Django, it has its own web framework which is pythonic has URL dispatcher like Django and it uses Django templatesSo if you have Django exp. you will find it easy to use But you can use any pure python framework and Django can be easily added see http://code.google.com/appengine/articles/django.html google-app-engine-django ( http://code.google.com/p/google-app-engine-django/ ) project is excellent and works almost like working on a Django project You can not execute any long running process on server, what you do is reply to request and which should be quick otherwise appengine will kill itSo if your app needs lots of backend processing appengine is not the best wayotherwise you will have to do processing on a server of your own My quakewatch app has a subscription feature, it means I had to email latest quakes as they happend, but I can not run a background process in app engine to monitor new quakessolution here is to use a third part service like pingablity.com which can connect to one of your page and which executes the subscription emailerbut here also you will have to take care that you don't spend much time hereor break task into several pieces It provides Django like modeling capabilities but backend is totally different but for a new project it should not matter. But overall I think it is excellent for creating apps which do not need lot of background processing. Edit:Now task queues can be used for running batch processing or scheduled tasks Edit:after working/creating a real application on GAE for a year, now my opnion is that unless you are making a application which needs to scale to million and million of users, don't use GAE. Maintaining and doing trivial tasks in GAE is a headache due to distributed nature, to avoid deadline exceeded errors, count entities or do complex queries requires complex code, so small complex application should stick to LAMP. Edit:Models should be specially designed considering all the transactions you wish to have in future, because entities only in same entity group can be used in a transaction and it makes the process of updating two different groups a nightmare e.g. transfer money from user1 to user2 in transaction is impossible unless they are in same entity group, but making them same entity group may not be best for frequent update purposes....read this http://blog.notdot.net/2009/9/Distributed-Transactions-on-App-Engine | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/110186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18402/"
]
} |
110,205 | I want to download this open source application, and they are using Git. What do I need to download the code base? Update How do I change the working directory when I am using Git Bash? (I want to download the repo at a certain directory, using pwd tells me I will be downloading the repo where I don't want it. | Download Git on Msys . Then: git clone git://project.url.here | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/110205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
]
} |
110,229 | What is the behind-the-scenes difference between 'int?' and 'int'? Is 'int?' a somehow a reference type? | ? wraps the value type (T) in a Nullable<T> struct: http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/110229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16872/"
]
} |
110,259 | I want to know the memory usage of my Python application and specifically want to know what code blocks/portions or objects are consuming most memory.Google search shows a commercial one is Python Memory Validator (Windows only). And open source ones are PySizer and Heapy . I haven't tried anyone, so I wanted to know which one is the best considering: Gives most details. I have to do least or no changes to my code. | guppy3 is quite simple to use. At some point in your code, you have to write the following: from guppy import hpyh = hpy()print(h.heap()) This gives you some output like this: Partition of a set of 132527 objects. Total size = 8301532 bytes.Index Count % Size % Cumulative % Kind (class / dict of class)0 35144 27 2140412 26 2140412 26 str1 38397 29 1309020 16 3449432 42 tuple2 530 0 739856 9 4189288 50 dict (no owner) You can also find out from where objects are referenced and get statistics about that, but somehow the docs on that are a bit sparse. There is a graphical browser as well, written in Tk. For Python 2.x, use Heapy . | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/110259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6946/"
]
} |
110,263 | I am trying to add a project reference or swc to papervision in FlashDevelop but intellisense isn't picking it up. I've done it before but i forgot how. Thanks. | Add your swc to the lib folder of your project. Then right-click it and mark "Add To Library". | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/110263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1748529/"
]
} |
110,305 | I'm working on a page has an ol with nested p's, div's, and li's. Internet Explorer 6 and 7 both render the numbers for the ol tag after the p element at the end (at the very, very bottom of the li tag) rather than at the top of the outermost li as expected. I'm working on a PowerPC Mac and can't do any testing. Is there some simple CSS hack to make this render the same as it does in Firefox? You can view the live page here . I know, I'm working on positioning the sidebar. Ignore that for now. Markup is as follows: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="css/global.css" /> <link rel="stylesheet" type="text/css" href="css/whats_included.css" /> <script type="text/javascript" src="script/compliant_target_blank.js"></script> <!--[if lte IE 5]> <script type="text/javascript" src="script/ie_5_unsupported_warning.js"></script> <![endif]--> <!--[if gt IE 5]> <link rel="stylesheet" type="text/css" href="css/ie_hacks/global.css" /> <![endif]--> <title> The Daily Plan-It, LLC - Home of the Tax MiniMiser </title> </head> <body> <?php include("includes/nav_bar.php") ?> <div id="content"> <img src="images/title.png" alt="Tax MiniMiser Financial Tracking System" /> <div id="bordered_wrapper"> <h1>Here's What You Get With The Tax MiniMiser!</h1> <h2>24 Envelopes, 7-hole punched to fit one-at-a-time in your binder</h2> <ol> <li class="main_item"> Business Income & Expense Record <div class="preview_image"> <a href="previews/large/bier/front.html" rel="external"> <img src="images/small_previews/large/bier_preview.jpg" alt="" /><br/> Click to Preview! </a> </div> <div class="details"> <ul> <li>12 receipt envelopes with all the income & expense columns you need to transform your planner or binder into a daily tax journal!</li> <li>Store daily receipts in the convenient pocket envelopes.</li> </ul> </div> <p>To get a free copy of the "20 Column Heading Guidelines", <a href="files/downloads/20_column_heading_guidelines.pdf">click here</a> or call our Fax-on-Demand line at 888-829-8237.</p> </li> <li class="main_item"> Vehicle Mileage & Expense Record <div class="preview_image"> <a href="previews/large/vme/front.html" rel="external"> <img src="images/small_previews/large/mileage_preview.jpg" alt=""/><br/> Click to Preview! </a> </div> <div class="details"> <ul> <li>12 receipt envelopes to track your daily mileage and vehicle expenses. Keep one envelope in each vehicle used for your business(es).</li> <li>Store daily receipts in the convenient pocket envelopes.</li> </ul> </div> <p>To get a free copy of the "Instructions for Vehicle Mileage & Expense Record", <a href="files/downloads/vehicle_record_instructions.pdf">click here</a> or call our Fax-on-Demand line at 888-829-8237.</p> </li> <li class="main_item"> Annual Business Summary of Income and Expense <div class="preview_image"> <a href="previews/large/cover/inside.html" rel="external"> <img src="images/small_previews/large/cover_inside_preview.jpg" alt="" /><br/> Click to Preview! </a> </div> <div class="details"> <ul> <li>Enter the subtotals from all the envelopes throughout the year. Then you and your tax pro can figure out profitability and taxes to maximize your deductions and legally minimize your taxes.</li> </ul> </div> </li> </ol> <p class="end">To see previews of the small (6" x 8½") Tax MiniMisers, visit their respective pages <a href="products.php">here.</a></p> </div> </div> <?php include("includes/footer.php") ?> </body></html> And the CSS: #content { background-color: white;}#bordered_wrapper { margin-left: 26px; background: top left no-repeat url(../images/borders/yellow-box-top.gif);}#bordered_wrapper h1, #bordered_wrapper h2 { margin-left: 20px;}#bordered_wrapper h1 { padding-top: 15px; margin-bottom: 0;}#bordered_wrapper h2 { margin-top: 0; font-size: 1.3em;}ol { font-size: 1.1em;}ul { list-style-type: disc;}li.main_item { width: 700px; clear: right;}li p { clear: both; margin-bottom: 20px;}.preview_image { width: 200px; float: right; text-align: center; margin-bottom: 10px;}.preview_image a { text-decoration: none;}.preview_image img { border-style: none;}.end { clear: right; padding-bottom: 25px; padding-left: 20px; background: bottom left no-repeat url(../images/borders/yellow-box-bottom.gif);} | Congratulations, you are the victim of IE's hasLayout property. Short version: You've got it easy this time. Changes these rules: ...ol { font-size: 1.1em;}...li.main_item { width: 700px; clear: right;}... To this: ...ol { font-size: 1.1em; width: 700px;}...li.main_item { clear: right;}... And it's all good. Longer version: When you apply certain CSS rules to certain elements, IE 5.5+ gives those elements a property called "hasLayout" that changes how that element is rendered. Since hasLayout was a read-only property with no apparent purpose, it took quite a while before web designers caught on to the issue. Older sites (even Quirksmode.org!) still has pages that suggest twiddling padding, margins, or even using Javascript to fix these issues. If you can at all help it, don't do these things. Instead, see if you can find out what element is incorrectly being given hasLayout, and change the offending CSS so that the element no longer gets hasLayout. If that totally borks your page, use conditional comments to fix it just for IE. Here are some CSS rules that add "hasLayout" to an element that doesn't already have it: position: absolute float: left|right display: inline-block height: any value other than 'auto' zoom: any value other than 'normal' (MS proprietary) writing-mode: tb-rl (MS proprietary) As of IE7, overflow became a trigger for hasLayout. overflow: hidden|scroll|auto Longest version: read the following articles. Here's all the neat things Microsoft would like you do by triggering "hasLayout" . Here's the clean-language version of what web designers thought about hasLayout when they found out what was going on. Some of the same content, but includes CSS hacks and stuff. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/110305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10140/"
]
} |
110,313 | If our organisation were to switch from a central-server VCS like subversion to a distributed VCS like git, how do I make sure that all my code is safe from hardware failure? With a central-server VCS I just need to backup the repository every day. If we were using a DVCS then there'd be loads of code branches on all the developer machines, and if that hardware were to fail (or a dev were to lose his laptop or have it stolen) then we wouldn't have any backups. Note that I don't consider it a good option to "make the developers push branches to a server" -- that's tedious and the developers will end up not doing it. Is there a common way around this problem? Some clarification: With a natively-central-server VCS then everything has to be on the central server except the developer's most recent changes. So, for example, if a developer decides to branch to do a bugfix, that branch is on the central server and available for backup immediately. If we're using a DVCS then the developer can do a local branch (and in fact many local branches). None of those branches are on the central server and available for backup until the developer thinks, "oh yeah, I should push that to the central server". So the difference I'm seeing (correct me if I'm wrong!): Half-implemented features and bugfixes will probably not available for backup on the central server if we're using a DVCS, but are with a normal VCS. How do I keep that code safe? | I think that you will find that in practice developers will prefer to use a central repository than pushing and pulling between each other's local repositories. Once you've cloned a central repository, while working on any tracking branches, fetching and pushing are trivial commands. Adding half a dozen remotes to all your colleagues' local repositories is a pain and these repositories may not always be accessible (switched off, on a laptop taken home, etc.). At some point, if you are all working on the same project, all the work needs to be integrated. This means that you need an integration branch where all the changes come together. This naturally needs to be somewhere accessible by all the developers, it doesn't belong, for example, on the lead developer's laptop. Once you've set up a central repository you can use a cvs/svn style workflow to check in and update. cvs update becomes git fetch and rebase if you have local changes or just git pull if you don't. cvs commit becomes git commit and git push. With this setup you are in a similar position with your fully centralized VCS system. Once developers submit their changes (git push), which they need to do to be visible to the rest of the team, they are on the central server and will be backed up. What takes discipline in both cases is preventing developers keeping long running changes out of the central repository. Most of us have probably worked in a situation where one developer is working on feature 'x' which needs a fundamental change in some core code. The change will cause everyone else to need to completely rebuild but the feature isn't ready for the main stream yet so he just keeps it checked out until a suitable point in time. The situation is very similar in both situations although there are some practical differences. Using git, because you get to perform local commits and can manage local history, the need to push to the central repository may not be felt as much by the individual developer as with something like cvs. On the other hand, the use of local commits can be used as an advantage. Pushing all local commits to a safe place on the central repository should not be very difficult. Local branches can be stored in a developer specific tag namespace. For example, for Joe Bloggs, An alias could be made in his local repository to perform something like the following in response to (e.g.) git mybackup . git push origin +refs/heads/*:refs/jbloggs/* This is a single command that can be used at any point (such as the end of the day) to make sure that all his local changes are safely backed up. This helps with all sorts of disasters. Joe's machine blows up and he can use another machine and fetch is saved commits and carry on from where he left off. Joe's ill? Fred can fetch Joe's branches to grab that 'must have' fix that he made yesterday but didn't have a chance to test against master. To go back to the original question. Does there need to be a difference between dVCS and centralized VCS? You say that half-implemented features and bugfixes will not end up on the central repository in the dVCS case but I would contend that there need be no difference. I have seen many cases where a half-implemented feature stays on one developers working box when using centralized VCS. It either takes a policy that allows half written features to be checked in to the main stream or a decision has to be made to create a central branch. In the dVCS the same thing can happen, but the same decision should be made. If there is important but incomplete work, it needs to be saved centrally. The advantage of git is that creating this central branch is almost trivial. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/110313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6408/"
]
} |
110,314 | So, I am using the Linq entity framework. I have 2 entities: Content and Tag . They are in a many-to-many relationship with one another. Content can have many Tags and Tag can have many Contents . So I am trying to write a query to select all contents where any tags names are equal to blah The entities both have a collection of the other entity as a property(but no IDs). This is where I am struggling. I do have a custom expression for Contains (so, whoever may help me, you can assume that I can do a "contains" for a collection). I got this expression from: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2670710&SiteID=1 Edit 1 I ended up finding my own answer. | After reading about the PredicateBuilder , reading all of the wonderful posts that people sent to me, posting on other sites, and then reading more on Combining Predicates and Canonical Function Mapping .. oh and I picked up a bit from Calling functions in LINQ queries (some of these classes were taken from these pages). I FINALLY have a solution!!! Though there is a piece that is a bit hacked... Let's get the hacked piece over with :( I had to use reflector and copy the ExpressionVisitor class that is marked as internal. I then had to make some minor changes to it, to get it to work. I had to create two exceptions (because it was newing internal exceptions. I also had to change the ReadOnlyCollection() method's return from: return sequence.ToReadOnlyCollection<Expression>(); To: return sequence.AsReadOnly(); I would post the class, but it is quite large and I don't want to clutter this post any more than it's already going to be. I hope that in the future that class can be removed from my library and that Microsoft will make it public. Moving on... I added a ParameterRebinder class: public class ParameterRebinder : ExpressionVisitor { private readonly Dictionary<ParameterExpression, ParameterExpression> map; public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map) { this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>(); } public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp) { return new ParameterRebinder(map).Visit(exp); } internal override Expression VisitParameter(ParameterExpression p) { ParameterExpression replacement; if (map.TryGetValue(p, out replacement)) { p = replacement; } return base.VisitParameter(p); } } Then I added a ExpressionExtensions class: public static class ExpressionExtensions { public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge) { // build parameter map (from parameters of second to parameters of first) var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f); // replace parameters in the second lambda expression with parameters from the first var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body); // apply composition of lambda expression bodies to parameters from the first expression return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters); } public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second) { return first.Compose(second, Expression.And); } public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second) { return first.Compose(second, Expression.Or); } } And the last class I added was PredicateBuilder: public static class PredicateBuilder { public static Expression<Func<T, bool>> True<T>() { return f => true; } public static Expression<Func<T, bool>> False<T>() { return f => false; }} This is my result... I was able to execute this code and get back the resulting "content" entities that have matching "tag" entities from the tags that I was searching for! public static IList<Content> GetAllContentByTags(IList<Tag> tags) { IQueryable<Content> contentQuery = ... Expression<Func<Content, bool>> predicate = PredicateBuilder.False<Content>(); foreach (Tag individualTag in tags) { Tag tagParameter = individualTag; predicate = predicate.Or(p => p.Tags.Any(tag => tag.Name.Equals(tagParameter.Name))); } IQueryable<Content> resultExpressions = contentQuery.Where(predicate); return resultExpressions.ToList(); } Please let me know if anyone needs help with this same thing, if you would like me to send you files for this, or just need more info. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/110314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19854/"
]
} |
110,328 | One mentor I respect suggests that a simple bean is a waste of time - that value objects 'MUST' contain some business logic to be useful. Another says such code is difficult to maintain and that all business logic must be externalized. I realize this question is subjective. Asking anyway - want to know answers from more perspectives. | The idea of putting data and business logic together is to promote encapsulation, and to expose as little internal state as possible to other objects. That way, clients can rely on an interface rather than on an implementation. See the "Tell, Don't Ask" principle and the Law of Demeter . Encapsulation makes it easier to understand the states data can be in, easier to read code, easier to decouple classes and generally easier to unit test. Externalising business logic (generally into "Service" or "Manager" classes) makes questions like "where is this data used?" and "What states can it be in?" a lot more difficult to answer. It's also a procedural way of thinking, wrapped up in an object. This can lead to an anemic domain model . Externalising behaviour isn't always bad. For example, a service layer might orchestrate domain objects, but without taking over their state-manipulating responsibilities. Or, when you are mostly doing reads/writes to a DB that map nicely to input forms, maybe you don't need a domain model - or the painful object/relational mapping overhead it entails - at all. Transfer Objects often serve to decouple architectural layers from each other (or from an external system) by providing the minimum state information the calling layer needs, without exposing any business logic. This can be useful, for example when preparing information for the view: just give the view the information it needs, and nothing else, so that it can concentrate on how to display the information, rather than what information to display. For example, the TO might be an aggregation of several sources of data. One advantage is that your views and your domain objects are decoupled. Using your domain objects in JSPs can make your domain harder to refactor and promotes the indiscriminate use of getters and setters (hence breaking encapsulation). However, there's also an overhead associated with having a lot of Transfer Objects and often a lot of duplication, too. Some projects I've been on end up with TO's that basically mirror other domain objects (which I consider an anti-pattern). | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/110328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16485/"
]
} |
110,332 | I have an NSArray and I'd like to create a new NSArray with objects from the original array that meet certain criteria. The criteria is decided by a function that returns a BOOL . I can create an NSMutableArray , iterate through the source array and copy over the objects that the filter function accepts and then create an immutable version of it. Is there a better way? | NSArray and NSMutableArray provide methods to filter array contents. NSArray provides filteredArrayUsingPredicate: which returns a new array containing objects in the receiver that match the specified predicate. NSMutableArray adds filterUsingPredicate: which evaluates the receiver’s content against the specified predicate and leaves only objects that match. These methods are illustrated in the following example. NSMutableArray *array = [NSMutableArray arrayWithObjects:@"Bill", @"Ben", @"Chris", @"Melissa", nil];NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] 'b'"];NSArray *beginWithB = [array filteredArrayUsingPredicate:bPredicate];// beginWithB contains { @"Bill", @"Ben" }.NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 's'"];[array filteredArrayUsingPredicate:sPredicate];// array now contains { @"Chris", @"Melissa" } | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/110332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3740/"
]
} |
110,344 | What would be the most optimal algorithm (performance-wise) to calculate the number of divisors of a given number? It'll be great if you could provide pseudocode or a link to some example. EDIT: All the answers have been very helpful, thank you. I'm implementing the Sieve of Atkin and then I'm going to use something similar to what Jonathan Leffler indicated. The link posted by Justin Bozonier has further information on what I wanted. | Dmitriy is right that you'll want the Sieve of Atkin to generate the prime list but I don't believe that takes care of the whole issue. Now that you have a list of primes you'll need to see how many of those primes act as a divisor (and how often). Here's some python for the algo Look here and search for "Subject: math - need divisors algorithm". Just count the number of items in the list instead of returning them however. Here's a Dr. Math that explains what exactly it is you need to do mathematically. Essentially it boils down to if your number n is: n = a^x * b^y * c^z (where a, b, and c are n's prime divisors and x, y, and z are the number of times that divisor is repeated)then the total count for all of the divisors is: (x + 1) * (y + 1) * (z + 1) . Edit: BTW, to find a,b,c,etc you'll want to do what amounts to a greedy algo if I'm understanding this correctly. Start with your largest prime divisor and multiply it by itself until a further multiplication would exceed the number n. Then move to the next lowest factor and times the previous prime ^ number of times it was multiplied by the current prime and keep multiplying by the prime until the next will exceed n... etc. Keep track of the number of times you multiply the divisors together and apply those numbers into the formula above. Not 100% sure about my algo description but if that isn't it it's something similar . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/110344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9776/"
]
} |
110,354 | I want to do this: e.className = t; Where t is the name of a style I have defined in a stylesheet. | If e is a reference to a DOM element and you have a class like this: .t {color:green;} then you want reference the class name as a string: e.className = 't'; | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/110354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15059/"
]
} |
110,362 | As the title says, how can I find the current operating system in python? | I usually use sys.platform to get the platform. sys.platform will distinguish between linux, other unixes, and OS X, while os.name is " posix " for all of them. For much more detailed information, use the platform module . This has cross-platform functions that will give you information on the machine architecture, OS and OS version, version of Python, etc. Also it has os-specific functions to get things like the particular linux distribution. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/110362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
]
} |
110,378 | How can I change the width of a textarea form element if I used ModelForm to create it? Here is my product class: class ProductForm(ModelForm): long_desc = forms.CharField(widget=forms.Textarea) short_desc = forms.CharField(widget=forms.Textarea) class Meta: model = Product And the template code... {% for f in form %} {{ f.name }}:{{ f }}{% endfor %} f is the actual form element... | The easiest way for your use case is to use CSS . It's a language meant for defining presentation. Look at the code generated by form, take note of the ids for fields that interest you, and change appearance of these fields through CSS. Example for long_desc field in your ProductForm (when your form does not have a custom prefix): #id_long_desc { width: 300px; height: 200px;} Second approach is to pass the attrs keyword to your widget constructor. class ProductForm(ModelForm): long_desc = forms.CharField(widget=forms.Textarea(attrs={'cols': 10, 'rows': 20})) short_desc = forms.CharField(widget=forms.Textarea) class Meta: model = Product It's described in Django documentation . Third approach is to leave the nice declarative interface of newforms for a while and set your widget attributes in custom constructor. class ProductForm(ModelForm): long_desc = forms.CharField(widget=forms.Textarea) short_desc = forms.CharField(widget=forms.Textarea) class Meta: model = Product # Edit by bryan def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor self.fields['long_desc'].widget.attrs['cols'] = 10 self.fields['long_desc'].widget.attrs['rows'] = 20 This approach has the following advantages: You can define widget attributes for fields that are generated automatically from your model without redefining whole fields. It doesn't depend on the prefix of your form. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/110378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592/"
]
} |
110,393 | I'm attempting to use TinyXML to read and save from memory, instead of only reading and saving files to disk. It seems that the documnent's parse function can load a char *. But then I need to save the document to a char * when I'm done with it. Does anyone know about this? Edit: The printing & streaming functions aren't what I'm looking for. They output in a viewable format, I need the actual xml content. Edit: Printing is cool. | Here's some sample code I am using, adapted from the TiXMLPrinter documentation: TiXmlDocument doc;// populate document here ...TiXmlPrinter printer;printer.SetIndent( " " );doc.Accept( &printer );std::string xmltext = printer.CStr(); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/110393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14278/"
]
} |
110,430 | Do you write one test per function/method, with multiple checks in the test, or a test for each check? | One test per check and super descriptive names, per instance: @Testpublic void userCannotVoteDownWhenScoreIsLessThanOneHundred() { ...} Both only one assertion and using good names gives me a better report when a test fails. They scream to me: "You broke THAT rule!". | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/110430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19863/"
]
} |
110,433 | Are there any Common Lisp implementations for .Net? | I haven't looked at it recently, but at least in the past there were some problems with fully implementing common lisp on the CLR, and I'd be a little surprised if this has changed. The issues come up with things like the handling of floats where .net/clr has a way to do it that is a) subtly incorrect b) disagrees with the ANSI standard for common lisp but c) doesn't allow any way around this. There are other similar problems. This stuff is fiddly and perhaps not too important, but means you are unlikely to see an ANSI CL on the CLR. There are bigger issues, for example common lisp has a more powerful object system, so you can't map it 1:1 to object in the runtime (no MI, for one). This is ok, but leaves you with an inside/outside sort of approach which is what a common runtime tries to avoid... Whether or not you'll see a common lisp-ish variant running on it is a different story, but I don't know of any at the moment (not that I've looked hard) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/110433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18658/"
]
} |
110,451 | I am working through the book Learning WCF by Michele Bustamante, and trying to do it using Visual Studio C# Express 2008. The instructions say to use WCF project and item templates, which are not included with VS C# Express. There are templates for these types included with Visual Studio Web Developer Express, and I've tried to copy them over into the right directories for VS C# Express to find, but the IDE doesn't find them. Is there some registration process? Or config file somewhere? | If you have both Visual Web Developer (VWD) 2008 and Visual C# (VC#) 2008 installed you can copy templates between them. The VWD template files live in (by default): C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VWDExpress The VC# templates live in: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VCSExpress Simply copy the templates between the two directories, they might not match exactly but they should be close enough to make sense, for instance I copied the project templates from VC# into VWD by copying files from: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VCSExpress\ProjectTemplates\1033 into: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VWDExpress\ProjectTemplates\CSharp\Windows\1033 The templates won't appear straight away in the template browser. For VWD you need to run: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VWDExpress.exe /installvstemplates For VC# you run: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VCSExpress.exe /installvstemplates | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/110451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14607/"
]
} |
110,477 | vi is for cool kids. | After @joe's answer, Jared Parsons created the great VsVim . It's been featured on Visual Studio Gallery . It's a ready extension package. I downloaded it, ran the file and it worked out of the box. It's free, too. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/110477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10088/"
]
} |
110,498 | Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple. | Here is the Requests way: import requestsr = requests.get('http://github.com', allow_redirects=False)print(r.status_code, r.headers['Location']) | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/110498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2168/"
]
} |
110,575 | Earlier today a question was asked regarding input validation strategies in web apps . The top answer, at time of writing, suggests in PHP just using htmlspecialchars and mysql_real_escape_string . My question is: Is this always enough? Is there more we should know? Where do these functions break down? | When it comes to database queries, always try and use prepared parameterised queries. The mysqli and PDO libraries support this. This is infinitely safer than using escaping functions such as mysql_real_escape_string . Yes, mysql_real_escape_string is effectively just a string escaping function. It is not a magic bullet. All it will do is escape dangerous characters in order that they can be safe to use in a single query string. However, if you do not sanitise your inputs beforehand, then you will be vulnerable to certain attack vectors. Imagine the following SQL: $result = "SELECT fields FROM table WHERE id = ".mysql_real_escape_string($_POST['id']); You should be able to see that this is vulnerable to exploit. Imagine the id parameter contained the common attack vector: 1 OR 1=1 There's no risky chars in there to encode, so it will pass straight through the escaping filter. Leaving us: SELECT fields FROM table WHERE id= 1 OR 1=1 Which is a lovely SQL injection vector and would allow the attacker to return all the rows.Or 1 or is_admin=1 order by id limit 1 which produces SELECT fields FROM table WHERE id=1 or is_admin=1 order by id limit 1 Which allows the attacker to return the first administrator's details in this completely fictional example. Whilst these functions are useful, they must be used with care. You need to ensure that all web inputs are validated to some degree. In this case, we see that we can be exploited because we didn't check that a variable we were using as a number, was actually numeric. In PHP you should widely use a set of functions to check that inputs are integers, floats, alphanumeric etc. But when it comes to SQL, heed most the value of the prepared statement. The above code would have been secure if it was a prepared statement as the database functions would have known that 1 OR 1=1 is not a valid literal. As for htmlspecialchars() . That's a minefield of its own. There's a real problem in PHP in that it has a whole selection of different html-related escaping functions, and no clear guidance on exactly which functions do what. Firstly, if you are inside an HTML tag, you are in real trouble. Look at echo '<img src= "' . htmlspecialchars($_GET['imagesrc']) . '" />'; We're already inside an HTML tag, so we don't need < or > to do anything dangerous. Our attack vector could just be javascript:alert(document.cookie) Now resultant HTML looks like <img src= "javascript:alert(document.cookie)" /> The attack gets straight through. It gets worse. Why? because htmlspecialchars (when called this way) only encodes double quotes and not single. So if we had echo "<img src= '" . htmlspecialchars($_GET['imagesrc']) . ". />"; Our evil attacker can now inject whole new parameters pic.png' onclick='location.href=xxx' onmouseover='... gives us <img src='pic.png' onclick='location.href=xxx' onmouseover='...' /> In these cases, there is no magic bullet, you just have to santise the input yourself. If you try and filter out bad characters you will surely fail. Take a whitelist approach and only let through the chars which are good. Look at the XSS cheat sheet for examples on how diverse vectors can be Even if you use htmlspecialchars($string) outside of HTML tags, you are still vulnerable to multi-byte charset attack vectors. The most effective you can be is to use the a combination of mb_convert_encoding and htmlentities as follows. $str = mb_convert_encoding($str, 'UTF-8', 'UTF-8');$str = htmlentities($str, ENT_QUOTES, 'UTF-8'); Even this leaves IE6 vulnerable, because of the way it handles UTF. However, you could fall back to a more limited encoding, such as ISO-8859-1, until IE6 usage drops off. For a more in-depth study to the multibyte problems, see https://stackoverflow.com/a/12118602/1820 | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/110575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1820/"
]
} |
110,674 | I'm developing a performance critical application for Intel Atom processor. What are the best gcc optimization flags for this CPU? | GCC 4.5 will contain the -march=atom and -mtune=atom options. Source: http://gcc.gnu.org/gcc-4.5/changes.html | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/110674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7305/"
]
} |
110,684 | Some years ago I was on a panel that was interviewing candidates for a relatively senior embedded C programmer position. One of the standard questions that I asked was about optimisation techniques. I was quite surprised that some of the candidates didn't have answers. So, in the interests of putting together a list for posterity - what techniques and constructs do you normally use when optimising C programs? Answers to optimisation for speed and size both accepted. | First things first - don't optimise too early. It's not uncommon to spend time carefully optimising a chunk of code only to find that it wasn't the bottleneck that you thought it was going to be. Or, to put it another way "Before you make it fast, make it work" Investigate whether there's any option for optimising the algorithm before optimising the code. It'll be easier to find an improvement in performance by optimising a poor algorithm than it is to optimise the code, only then to throw it away when you change the algorithm anyway. And work out why you need to optimise in the first place. What are you trying to achieve? If you're trying, say, to improve the response time to some event work out if there is an opportunity to change the order of execution to minimise the time critical areas. For example when trying to improve the response to some external interrupt can you do any preparation in the dead time between events? Once you've decided that you need to optimise the code, which bit do you optimise? Use a profiler. Focus your attention (first) on the areas that are used most often. So what can you do about those areas? minimise condition checking. Checking conditions (eg. terminating conditions for loops) is time that isn't being spent on actual processing. Condition checking can be minimised with techniques like loop-unrolling. In some circumstances condition checking can also be eliminated by using function pointers. For example if you are implementing a state machine you may find that implementing the handlers for individual states as small functions (with a uniform prototype) and storing the "next state" by storing the function pointer of the next handler is more efficient than using a large switch statement with the handler code implemented in the individual case statements. YMMV. minimise function calls. Function calls usually carry a burden of context saving (eg. writing local variables contained in registers to the stack, saving the stack pointer), so if you don't have to make a call this is time saved. One option (if you're optimising for speed and not space) is to make use of inline functions. If function calls are unavoidable minimise the data that is being passed to the functions. For example passing pointers is likely to be more efficient than passing structures. When optimising for speed choose datatypes that are the native size for your platform. For example on a 32bit processor it is likely to be more efficient to manipulate 32bit values than 8 or 16 bit values. (side note - it is worth checking that the compiler is doing what you think it is. I've had situations where I've discovered that my compiler insisted on doing 16 bit arithmetic on 8 bit values with all of the to and from conversions to go with them) Find data that can be precalculated, and either calculate during initialisation or (better yet) at compile time. For example when implementing a CRC you can either calculate your CRC values on the fly (using the polynomial directly) which is great for size (but dreadful for performance), or you can generate a table of all of the interim values - which is a much faster implementation, to the detriment of the size. Localise your data. If you're manipulating a blob of data often your processor may be able to speed things up by storing it all in cache. And your compiler may be able to use shorter instructions that are suited to more localised data (eg. instructions that use 8 bit offsets instead of 32 bit) In the same vein, localise your functions. For the same reasons. Work out the assumptions that you can make about the operations that you're performing and find ways of exploiting them. For example, on an 8 bit platform if the only operation that at you're doing on a 32 bit value is an increment you may find that you can do better than the compiler by inlining (or creating a macro) specifically for this purpose, rather than using a normal arithmetic operation. Avoid expensive instructions - division is a prime example. The "register" keyword can be your friend (although hopefully your compiler has a pretty good idea about your register usage). If you're going to use "register" it's likely that you'll have to declare the local variables that you want "register"ed first. Be consistent with your data types. If you are doing arithmetic on a mixture of data types (eg. shorts and ints, doubles and floats) then the compiler is adding implicit type conversions for each mismatch. This is wasted cpu cycles that may not be necessary. Most of the options listed above can be used as part of normal practice without any ill effects. However if you're really trying to eke out the best performance: - Investigate where you can (safely) disable error checking. It's not recommended, but it will save you some space and cycles. - Hand craft portions of your code in assembler. This of course means that your code is no longer portable but where that's not an issue you may find savings here. Be aware though that there is potentially time lost moving data into and out of the registers that you have at your disposal (ie. to satisfy the register usage of your compiler). Also be aware that your compiler should be doing a pretty good job on its own. (of course there are exceptions) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/110684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11694/"
]
} |
110,712 | I've worked with Cruise Control as the CI framework in my last project.Any recommendations on some other tools? (Not that i found CruiseControl lacking, just wanted to know if someone did some comparisons) | We have had great success with Hudson . It is easy to install and configure, has a great range of plugins and a good web user interface. The checkstyle and cobertura code coverage plugins are two that we use. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/110712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15100/"
]
} |
110,803 | In my app i need to save changed values (old and new) when model gets saved. Any examples or working code? I need this for premoderation of content. For example, if user changes something in model, then administrator can see all changes in separate table and then decide to apply them or not. | You haven't said very much about your specific use case or needs. In particular, it would be helpful to know what you need to do with the change information (how long do you need to store it?). If you only need to store it for transient purposes, @S.Lott's session solution may be best. If you want a full audit trail of all changes to your objects stored in the DB, try this AuditTrail solution . UPDATE : The AuditTrail code I linked to above is the closest I've seen to a full solution that would work for your case, though it has some limitations (doesn't work at all for ManyToMany fields). It will store all previous versions of your objects in the DB, so the admin could roll back to any previous version. You'd have to work with it a bit if you want the change to not take effect until approved. You could also build a custom solution based on something like @Armin Ronacher's DiffingMixin. You'd store the diff dictionary (maybe pickled?) in a table for the admin to review later and apply if desired (you'd need to write the code to take the diff dictionary and apply it to an instance). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/110803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7437/"
]
} |
110,858 | I am searching for a tutorial (optimally with Zend Framework) on how to use PHPUnit . I have found a couple on google but have not quiet understood it yet. | What your are looking for is the Pocket Guide . It explaines how to work with PHPUnit from A to Z in several languages. You can read it online or offline, for free, and it's regularly updated. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/110858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19929/"
]
} |
110,894 | I've got C# code that accesses MySQL through ODBC. It creates a transaction, does a few thousand insert commands, and then commits.Now my question is how many "round trips", so to speak, happen against the DB server? I mean, does it simply transmit every insert command to the DB server, or does it cache/buffer them and send them in batches? And is this configurable in any way? | MySQL has an extended SQL style that can be used, where mass inserts are put in several at a time: INSERT INTO `table` (`id`, `event`) VALUES (1, 94263), (2, 75015), (3, 75015); I will usually collect a few hundred insert-parts into a string before running the SQL query itself. This will reduce the overhead of parsing and communication by batching them yourself. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/110894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11208/"
]
} |
110,923 | How do I end a Tkinter program? Let's say I have this code: from Tkinter import *def quit(): # code to exitroot = Tk()Button(root, text="Quit", command=quit).pack()root.mainloop() How should I define the quit function to exit my application? | You should use destroy() to close a Tkinter window. from Tkinter import * #use tkinter instead of Tkinter (small, not capital T) if it doesn't work#as it was changed to tkinter in newer Python versionsroot = Tk()Button(root, text="Quit", command=root.destroy).pack() #button to close the windowroot.mainloop() Explanation: root.quit() The above line just bypasses the root.mainloop() , i.e., root.mainloop() will still be running in the background if quit() command is executed. root.destroy() While destroy() command vanishes out root.mainloop() , i.e., root.mainloop() stops. <window>.destroy() completely destroys and closes the window. So, if you want to exit and close the program completely, you should use root.destroy() , as it stops the mainloop() and destroys the window and all its widgets. But if you want to run some infinite loop and don't want to destroy your Tkinter window and want to execute some code after the root.mainloop() line, you should use root.quit() . Example: from Tkinter import *def quit(): global root root.quit()root = Tk()while True: Button(root, text="Quit", command=quit).pack() root.mainloop() #do something See What is the difference between root.destroy() and root.quit()? . | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/110923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10577/"
]
} |
110,928 | Seriously. On a 22" monitor, it only covers maybe a quarter of the screen. I need some ammo to axe down this rule. I'm not saying that there shouldn't be a limit; I'm just saying, 80 characters is very small. | I think the practice of keeping code to 80 (or 79) columns was originally created to support people editing code on 80-column dumb terminals or on 80-column printouts. Those requirement have mostly gone away now, but there are still valid reasons to keep the 80 column rule: To avoid wrapping when copying code into email, web pages, and books. To view multiple source windows side-by-side or using a side-by-side diff viewer. To improve readability. Narrow code can be read quickly without having to scan your eyes from side to side. I think the last point is the most important. Though displays have grown in size and resolution in the last few years, eyes haven't . | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/110928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18658/"
]
} |
110,933 | I wish to know all the pros and cons about using these two methods. In particular the implications on web security. Thanks. | To choose between them I use this simple rule: GET for reads. (reading data and displaying it) POST for anything that writes (i.e updating a database table, deleting an entry, etc.) The other consideration is that GET is subjected to the maximum URI length and of course can't handle file uploads. This page has a good summary . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/110933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19689/"
]
} |
111,031 | What are the benefits and drawbacks with using Centralized versus Distributed Version Control Systems (DVCS)? Have you run into any problems in DVCS and how did you safeguard against these problems? Keep the discussion tool agnostic and flaming to minimum. For those wondering what DVCS tools are available, here is a list of the best known free/open source DVCSs: Git , (written in C) used by the Linux Kernel and Ruby on Rails . Mercurial , (written in Python) used by Mozilla and OpenJDK . Bazaar , (written in Python) used by Ubuntu developers . Darcs , (written in Haskell). | From my answer to a different question : Distributed version control systems (DVCSs) solve different problems than Centralized VCSs. Comparing them is like comparing hammers and screwdrivers. Centralized VCS systems are designed with the intent that there is One True Source that is Blessed, and therefore Good. All developers work (checkout) from that source, and then add (commit) their changes, which then become similarly Blessed. The only real difference between CVS, Subversion, ClearCase, Perforce, VisualSourceSafe and all the other CVCSes is in the workflow, performance, and integration that each product offers. Distributed VCS systems are designed with the intent that one repository is as good as any other, and that merges from one repository to another are just another form of communication. Any semantic value as to which repository should be trusted is imposed from the outside by process, not by the software itself. The real choice between using one type or the other is organizational -- if your project or organization wants centralized control, then a DVCS is a non-starter. If your developers are expected to work all over the country/world, without secure broadband connections to a central repository, then DVCS is probably your salvation. If you need both, you're fsck'd. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/111031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3713/"
]
} |
111,071 | We have a large ASP (classic ASP) application and we would like to convert it to .NET in order to work on further releases. It makes no sense continuing to use ASP as it is obsolete, and we don't want to rewrite it from scratch (Joel Spolsky tells you why ). Is there a way to convert it from ASP to ASP.NET automatically? | Well,I used to work for the company where all web apps were classic ASP.When decision was made to move to .NET we had to find a way to transform 168(!) web apps into this new framework.I tried all the tools available at the time to do this and all failed. Best way is to build a new web server and start there from scratch, this way you can be sure that upgrade will happen fast and will work without any hick-ups because of old-new integration. You will be able to choose what functionality and visual appearances to keep and which one to change.Do not waste your time on automatic tools to upgrade your old ASP files/sites into NET platform. None so far have ever worked properly. And on top of that if you have database on back end, you will run into problem with connection to it from web apps. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/111071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7028/"
]
} |
111,102 | How would you explain JavaScript closures to someone with a knowledge of the concepts they consist of (for example functions, variables and the like), but does not understand closures themselves? I have seen the Scheme example given on Wikipedia, but unfortunately it did not help. | A closure is a pairing of: A function and A reference to that function's outer scope (lexical environment) A lexical environment is part of every execution context (stack frame) and is a map between identifiers (i.e. local variable names) and values. Every function in JavaScript maintains a reference to its outer lexical environment. This reference is used to configure the execution context created when a function is invoked. This reference enables code inside the function to "see" variables declared outside the function, regardless of when and where the function is called. If a function was called by a function, which in turn was called by another function, then a chain of references to outer lexical environments is created. This chain is called the scope chain. In the following code, inner forms a closure with the lexical environment of the execution context created when foo is invoked, closing over variable secret : function foo() { const secret = Math.trunc(Math.random() * 100) return function inner() { console.log(`The secret number is ${secret}.`) }}const f = foo() // `secret` is not directly accessible from outside `foo`f() // The only way to retrieve `secret`, is to invoke `f` In other words: in JavaScript, functions carry a reference to a private "box of state", to which only they (and any other functions declared within the same lexical environment) have access. This box of the state is invisible to the caller of the function, delivering an excellent mechanism for data-hiding and encapsulation. And remember: functions in JavaScript can be passed around like variables (first-class functions), meaning these pairings of functionality and state can be passed around your program: similar to how you might pass an instance of a class around in C++. If JavaScript did not have closures, then more states would have to be passed between functions explicitly , making parameter lists longer and code noisier. So, if you want a function to always have access to a private piece of state, you can use a closure. ...and frequently we do want to associate the state with a function. For example, in Java or C++, when you add a private instance variable and a method to a class, you are associating the state with functionality. In C and most other common languages, after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed. In JavaScript, if you declare a function within another function, then the local variables of the outer function can remain accessible after returning from it. In this way, in the code above, secret remains available to the function object inner , after it has been returned from foo . Uses of Closures Closures are useful whenever you need a private state associated with a function. This is a very common scenario - and remember: JavaScript did not have a class syntax until 2015, and it still does not have a private field syntax. Closures meet this need. Private Instance Variables In the following code, the function toString closes over the details of the car. function Car(manufacturer, model, year, color) { return { toString() { return `${manufacturer} ${model} (${year}, ${color})` } }}const car = new Car('Aston Martin', 'V8 Vantage', '2012', 'Quantum Silver')console.log(car.toString()) Functional Programming In the following code, the function inner closes over both fn and args . function curry(fn) { const args = [] return function inner(arg) { if(args.length === fn.length) return fn(...args) args.push(arg) return inner }}function add(a, b) { return a + b}const curriedAdd = curry(add)console.log(curriedAdd(2)(3)()) // 5 Event-Oriented Programming In the following code, function onClick closes over variable BACKGROUND_COLOR . const $ = document.querySelector.bind(document)const BACKGROUND_COLOR = 'rgba(200, 200, 242, 1)'function onClick() { $('body').style.background = BACKGROUND_COLOR}$('button').addEventListener('click', onClick) <button>Set background color</button> Modularization In the following example, all the implementation details are hidden inside an immediately executed function expression. The functions tick and toString close over the private state and functions they need to complete their work. Closures have enabled us to modularize and encapsulate our code. let namespace = {};(function foo(n) { let numbers = [] function format(n) { return Math.trunc(n) } function tick() { numbers.push(Math.random() * 100) } function toString() { return numbers.map(format) } n.counter = { tick, toString }}(namespace))const counter = namespace.countercounter.tick()counter.tick()console.log(counter.toString()) Examples Example 1 This example shows that the local variables are not copied in the closure: the closure maintains a reference to the original variables themselves . It is as though the stack-frame stays alive in memory even after the outer function exits. function foo() { let x = 42 let inner = () => console.log(x) x = x + 1 return inner}foo()() // logs 43 Example 2 In the following code, three methods log , increment , and update all close over the same lexical environment. And every time createObject is called, a new execution context (stack frame) is created and a completely new variable x , and a new set of functions ( log etc.) are created, that close over this new variable. function createObject() { let x = 42; return { log() { console.log(x) }, increment() { x++ }, update(value) { x = value } }}const o = createObject()o.increment()o.log() // 43o.update(5)o.log() // 5const p = createObject()p.log() // 42 Example 3 If you are using variables declared using var , be careful you understand which variable you are closing over. Variables declared using var are hoisted. This is much less of a problem in modern JavaScript due to the introduction of let and const . In the following code, each time around the loop, a new function inner is created, which closes over i . But because var i is hoisted outside the loop, all of these inner functions close over the same variable, meaning that the final value of i (3) is printed, three times. function foo() { var result = [] for (var i = 0; i < 3; i++) { result.push(function inner() { console.log(i) } ) } return result}const result = foo()// The following will print `3`, three times...for (var i = 0; i < 3; i++) { result[i]() } Final points: Whenever a function is declared in JavaScript closure is created. Returning a function from inside another function is the classic example of closure, because the state inside the outer function is implicitly available to the returned inner function, even after the outer function has completed execution. Whenever you use eval() inside a function, a closure is used. The text you eval can reference local variables of the function, and in the non-strict mode, you can even create new local variables by using eval('var foo = …') . When you use new Function(…) (the Function constructor ) inside a function, it does not close over its lexical environment: it closes over the global context instead. The new function cannot reference the local variables of the outer function. A closure in JavaScript is like keeping a reference ( NOT a copy) to the scope at the point of function declaration, which in turn keeps a reference to its outer scope, and so on, all the way to the global object at the top of the scope chain. A closure is created when a function is declared; this closure is used to configure the execution context when the function is invoked. A new set of local variables is created every time a function is called. Links Douglas Crockford's simulated private attributes and private methods for an object, using closures. A great explanation of how closures can cause memory leaks in IE if you are not careful. MDN documentation on JavaScript Closures . | {
"score": 14,
"source": [
"https://Stackoverflow.com/questions/111102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951/"
]
} |
111,133 | Just wondering | I made them work as I wanted once ! That was cool! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/111133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19970/"
]
} |
111,155 | How do I handle the window close event (user clicking the 'X' button) in a Python Tkinter program? | Tkinter supports a mechanism called protocol handlers . Here, the term protocol refers to the interaction between the application and the window manager. The most commonly used protocol is called WM_DELETE_WINDOW , and is used to define what happens when the user explicitly closes a window using the window manager. You can use the protocol method to install a handler for this protocol (the widget must be a Tk or Toplevel widget): Here you have a concrete example: import tkinter as tkfrom tkinter import messageboxroot = tk.Tk()def on_closing(): if messagebox.askokcancel("Quit", "Do you want to quit?"): root.destroy()root.protocol("WM_DELETE_WINDOW", on_closing)root.mainloop() | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/111155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10577/"
]
} |
111,181 | I'd like to be able to hook into a 3rd party application to see what SQL Statements are being executed. Specifically, it is a VB6 application running on SQL Server 2005. For example, when the application fills out a grid, I'd like to be able to see exactly what query produced that data. | If you have the appropriate rights (sysadmin or ALTER TRACE permission) on the DB you could watch using SQL Profiler. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/111181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
]
} |
111,234 | Now that it's clear what a metaclass is , there is an associated concept that I use all the time without knowing what it really means. I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using __init__ and __new__ lead to wonder what this bloody __call__ can be used for. Could you give me some explanations, including examples with the magic method ? | A callable is anything that can be called. The built-in callable (PyCallable_Check in objects.c) checks if the argument is either: an instance of a class with a __call__ method or is of a type that has a non null tp_call (c struct) member which indicates callability otherwise (such as in functions, methods etc.) The method named __call__ is ( according to the documentation ) Called when the instance is ''called'' as a function Example class Foo: def __call__(self): print 'called'foo_instance = Foo()foo_instance() #this is calling the __call__ method | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/111234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951/"
]
} |
111,302 | I have a webservice that when called without specifying a callback will return a JSON string using application/json as the content type. When a callback is specified it will wrap the JSON string in a callback function, so it's not really valid JSON anymore. My question is, should I serve it as application/javascript in this case or still use application/json ? | Use application/javascript. In that way, clients can rely on the content-type without having to manually check whether a response has padding or not. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/111302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9128/"
]
} |
111,307 | The question of whether P=NP is perhaps the most famous in all of Computer Science. What does it mean? And why is it so interesting? Oh, and for extra credit, please post a proof of the statement's truth or falsehood. :) | P stands for polynomial time. NP stands for non-deterministic polynomial time. Definitions: Polynomial time means that the complexity of the algorithm is O(n^k), where n is the size of your data (e. g. number of elements in a list to be sorted), and k is a constant. Complexity is time measured in the number of operations it would take, as a function of the number of data items. Operation is whatever makes sense as a basic operation for a particular task. For sorting, the basic operation is a comparison. For matrix multiplication, the basic operation is multiplication of two numbers. Now the question is, what does deterministic vs. non-deterministic mean? There is an abstract computational model, an imaginary computer called a Turing machine (TM). This machine has a finite number of states, and an infinite tape, which has discrete cells into which a finite set of symbols can be written and read. At any given time, the TM is in one of its states, and it is looking at a particular cell on the tape. Depending on what it reads from that cell, it can write a new symbol into that cell, move the tape one cell forward or backward, and go into a different state. This is called a state transition. Amazingly enough, by carefully constructing states and transitions, you can design a TM, which is equivalent to any computer program that can be written. This is why it is used as a theoretical model for proving things about what computers can and cannot do. There are two kinds of TM's that concern us here: deterministic and non-deterministic. A deterministic TM only has one transition from each state for each symbol that it is reading off the tape. A non-deterministic TM may have several such transition, i. e. it is able to check several possibilities simultaneously. This is sort of like spawning multiple threads. The difference is that a non-deterministic TM can spawn as many such "threads" as it wants, while on a real computer only a specific number of threads can be executed at a time (equal to the number of CPUs). In reality, computers are basically deterministic TMs with finite tapes. On the other hand, a non-deterministic TM cannot be physically realized, except maybe with a quantum computer. It has been proven that any problem that can be solved by a non-deterministic TM can be solved by a deterministic TM. However, it is not clear how much time it will take. The statement P=NP means that if a problem takes polynomial time on a non-deterministic TM, then one can build a deterministic TM which would solve the same problem also in polynomial time. So far nobody has been able to show that it can be done, but nobody has been able to prove that it cannot be done, either. NP-complete problem means an NP problem X, such that any NP problem Y can be reduced to X by a polynomial reduction. That implies that if anyone ever comes up with a polynomial-time solution to an NP-complete problem, that will also give a polynomial-time solution to any NP problem. Thus that would prove that P=NP. Conversely, if anyone were to prove that P!=NP, then we would be certain that there is no way to solve an NP problem in polynomial time on a conventional computer. An example of an NP-complete problem is the problem of finding a truth assignment that would make a boolean expression containing n variables true. For the moment in practice any problem that takes polynomial time on the non-deterministic TM can only be done in exponential time on a deterministic TM or on a conventional computer. For example, the only way to solve the truth assignment problem is to try 2^n possibilities. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/111307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
]
} |
111,341 | I've got two tables: TableA------ID,NameTableB------ID,SomeColumn,TableA_ID (FK for TableA) The relationship is one row of TableA - many of TableB . Now, I want to see a result like this: ID Name SomeColumn1. ABC X, Y, Z (these are three different rows)2. MNO R, S This won't work (multiple results in a subquery): SELECT ID, Name, (SELECT SomeColumn FROM TableB WHERE F_ID=TableA.ID)FROM TableA This is a trivial problem if I do the processing on the client side. But this will mean I will have to run X queries on every page, where X is the number of results of TableA . Note that I can't simply do a GROUP BY or something similar, as it will return multiple results for rows of TableA . I'm not sure if a UDF, utilizing COALESCE or something similar might work? | 1. Create the UDF: CREATE FUNCTION CombineValues( @FK_ID INT -- The foreign key from TableA which is used -- to fetch corresponding records)RETURNS VARCHAR(8000)ASBEGINDECLARE @SomeColumnList VARCHAR(8000);SELECT @SomeColumnList = COALESCE(@SomeColumnList + ', ', '') + CAST(SomeColumn AS varchar(20)) FROM TableB CWHERE C.FK_ID = @FK_ID;RETURN ( SELECT @SomeColumnList)END 2. Use in subquery: SELECT ID, Name, dbo.CombineValues(FK_ID) FROM TableA 3. If you are using stored procedure you can do like this: CREATE PROCEDURE GetCombinedValues @FK_ID intAsBEGINDECLARE @SomeColumnList VARCHAR(800)SELECT @SomeColumnList = COALESCE(@SomeColumnList + ', ', '') + CAST(SomeColumn AS varchar(20)) FROM TableBWHERE FK_ID = @FK_ID Select *, @SomeColumnList as SelectedIds FROM TableA WHERE FK_ID = @FK_ID END | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/111341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6939/"
]
} |
111,345 | Is there a cheap way to get the dimensions of an image (jpg, png, ...)? Preferably, I would like to achieve this using only the standard class library (because of hosting restrictions). I know that it should be relatively easy to read the image header and parse it myself, but it seems that something like this should be already there. Also, I’ve verified that the following piece of code reads the entire image (which I don’t want): using System;using System.Drawing;namespace Test{ class Program { static void Main(string[] args) { Image img = new Bitmap("test.png"); System.Console.WriteLine(img.Width + " x " + img.Height); } }} | Your best bet as always is to find a well tested library. However, you said that is difficult, so here is some dodgy largely untested code that should work for a fair number of cases: using System;using System.Collections.Generic;using System.Drawing;using System.IO;using System.Linq;namespace ImageDimensions{ public static class ImageHelper { const string errorMessage = "Could not recognize image format."; private static Dictionary<byte[], Func<BinaryReader, Size>> imageFormatDecoders = new Dictionary<byte[], Func<BinaryReader, Size>>() { { new byte[]{ 0x42, 0x4D }, DecodeBitmap}, { new byte[]{ 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }, DecodeGif }, { new byte[]{ 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 }, DecodeGif }, { new byte[]{ 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, DecodePng }, { new byte[]{ 0xff, 0xd8 }, DecodeJfif }, }; /// <summary> /// Gets the dimensions of an image. /// </summary> /// <param name="path">The path of the image to get the dimensions of.</param> /// <returns>The dimensions of the specified image.</returns> /// <exception cref="ArgumentException">The image was of an unrecognized format.</exception> public static Size GetDimensions(string path) { using (BinaryReader binaryReader = new BinaryReader(File.OpenRead(path))) { try { return GetDimensions(binaryReader); } catch (ArgumentException e) { if (e.Message.StartsWith(errorMessage)) { throw new ArgumentException(errorMessage, "path", e); } else { throw e; } } } } /// <summary> /// Gets the dimensions of an image. /// </summary> /// <param name="path">The path of the image to get the dimensions of.</param> /// <returns>The dimensions of the specified image.</returns> /// <exception cref="ArgumentException">The image was of an unrecognized format.</exception> public static Size GetDimensions(BinaryReader binaryReader) { int maxMagicBytesLength = imageFormatDecoders.Keys.OrderByDescending(x => x.Length).First().Length; byte[] magicBytes = new byte[maxMagicBytesLength]; for (int i = 0; i < maxMagicBytesLength; i += 1) { magicBytes[i] = binaryReader.ReadByte(); foreach(var kvPair in imageFormatDecoders) { if (magicBytes.StartsWith(kvPair.Key)) { return kvPair.Value(binaryReader); } } } throw new ArgumentException(errorMessage, "binaryReader"); } private static bool StartsWith(this byte[] thisBytes, byte[] thatBytes) { for(int i = 0; i < thatBytes.Length; i+= 1) { if (thisBytes[i] != thatBytes[i]) { return false; } } return true; } private static short ReadLittleEndianInt16(this BinaryReader binaryReader) { byte[] bytes = new byte[sizeof(short)]; for (int i = 0; i < sizeof(short); i += 1) { bytes[sizeof(short) - 1 - i] = binaryReader.ReadByte(); } return BitConverter.ToInt16(bytes, 0); } private static int ReadLittleEndianInt32(this BinaryReader binaryReader) { byte[] bytes = new byte[sizeof(int)]; for (int i = 0; i < sizeof(int); i += 1) { bytes[sizeof(int) - 1 - i] = binaryReader.ReadByte(); } return BitConverter.ToInt32(bytes, 0); } private static Size DecodeBitmap(BinaryReader binaryReader) { binaryReader.ReadBytes(16); int width = binaryReader.ReadInt32(); int height = binaryReader.ReadInt32(); return new Size(width, height); } private static Size DecodeGif(BinaryReader binaryReader) { int width = binaryReader.ReadInt16(); int height = binaryReader.ReadInt16(); return new Size(width, height); } private static Size DecodePng(BinaryReader binaryReader) { binaryReader.ReadBytes(8); int width = binaryReader.ReadLittleEndianInt32(); int height = binaryReader.ReadLittleEndianInt32(); return new Size(width, height); } private static Size DecodeJfif(BinaryReader binaryReader) { while (binaryReader.ReadByte() == 0xff) { byte marker = binaryReader.ReadByte(); short chunkLength = binaryReader.ReadLittleEndianInt16(); if (marker == 0xc0) { binaryReader.ReadByte(); int height = binaryReader.ReadLittleEndianInt16(); int width = binaryReader.ReadLittleEndianInt16(); return new Size(width, height); } binaryReader.ReadBytes(chunkLength - 2); } throw new ArgumentException(errorMessage); } }} Hopefully the code is fairly obvious. To add a new file format you add it to imageFormatDecoders with the key being an array of the "magic bits" which appear at the beginning of every file of the given format and the value being a function which extracts the size from the stream. Most formats are simple enough, the only real stinker is jpeg. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/111345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15716/"
]
} |
111,368 | CPU Cycles, Memory Usage, Execution Time, etc.? Added: Is there a quantitative way of testing performance in JavaScript besides just perception of how fast the code runs? | Profilers are definitely a good way to get numbers, but in my experience, perceived performance is all that matters to the user/client. For example, we had a project with an Ext accordion that expanded to show some data and then a few nested Ext grids. Everything was actually rendering pretty fast, no single operation took a long time, there was just a lot of information being rendered all at once, so it felt slow to the user. We 'fixed' this, not by switching to a faster component, or optimizing some method, but by rendering the data first, then rendering the grids with a setTimeout. So, the information appeared first, then the grids would pop into place a second later. Overall, it took slightly more processing time to do it that way, but to the user, the perceived performance was improved. These days, the Chrome profiler and other tools are universally available and easy to use, as are console.time() ( mozilla-docs , chrome-docs ) console.profile() ( mozilla-docs , chrome-docs ) performance.now() ( mozilla-docs ) Chrome also gives you a timeline view which can show you what is killing your frame rate, where the user might be waiting, etc. Finding documentation for all these tools is really easy, you don't need an SO answer for that. 7 years later, I'll still repeat the advice of my original answer and point out that you can have slow code run forever where a user won't notice it, and pretty fast code running where they do, and they will complain about the pretty fast code not being fast enough. Or that your request to your server API took 220ms. Or something else like that. The point remains that if you take a profiler out and go looking for work to do, you will find it, but it may not be the work your users need. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/111368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10352/"
]
} |
111,386 | I am trying to understand what's the actual difference between SSL and Kerberos authentications, and why sometimes I have both SSL traffic and Kerberos. Or does Kerberos use SSL in any way? Anyone could help?Thank you! | While Kerberos and SSL are both protocols, Kerberos is an authentication protocol, but SSL is an encryption protocol. Kerberos usually uses UDP , SSL uses (most of the time) TCP . SSL authentication is usually done by checking the server's and the client's RSA or ECDSA keys embedded in something called X.509 certificates . You're authenticated by your certificate and the corresponding key. With Kerberos, you can be authenticated by your password, or some other way. Windows uses Kerberos for example, when used in domain. Keep in mind: Recent versions of SSL are called TLS for Transport Layer Security. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/111386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19159/"
]
} |
111,388 | I need some sort of interactive chart control for my .NET-based web app. I have some wide XY charts, and the user should be able to interactively scroll and zoom into a specific window on the x axis. Something that acts similar to the google finance control would be nice, but without the need for the date labels or the news event annotations. Also, I'd prefer to avoid Flash, if that's even possible. Can someone please give some recommendations of something that might come close? EDIT: the "real" google timeline visualization is for date-based data. I just have numeric data. I tried to use that control for non-date data, but it seems to always want to show a date and demands that the first data column actually be a date. | How about using the "real" google finance tool from the Google visualizations project? http://code.google.com/apis/visualization/documentation/gallery/annotatedtimeline.html | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/111388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404/"
]
} |
111,389 | I have a Rails project which I neglected to build tests for (for shame!) and the code base has gotten pretty large. A friend of mine said that RSpec was a pain to use unless you use it from the beginning. Is this true? What would make him say that? So, considering the available tests suites and the fact that the code base is already there, what would be my best course of action for getting this thing testable? Is it really that much different than doing it from the beginning? | This question came up recently on the RSpec mailing list, and the advice we generally gave was: Don't bother trying to retro-fit specs to existing, working, code unless you're going to change it - it's exhausting and, unless the code needs to be changed, rather pointless. Start writing specs for any changes you make from now on. Bug fixes are an especially good opportunity for this. Try to train yourself into the discipline that before you touch the code, first of all write a failing example (=spec) to drive out the change. You may find that the design of code which wasn't driven out by code examples or unit tests makes it awkward to write tests or specs for. This is perhaps what your friend was alluding to. You will almost certainly need to learn a few key refactoring techniques to break up dependencies so that you can exercise each class in isolation from your specs. Michael Feathers' excellent book, Working Effectively With Legacy Code has some great material to help you learn this delicate skill. I'd also encourage you to use the built-in spec:rcov rake task to generate code coverage stats. It's extremely rewarding to watch these numbers go up as you start to get your codebase under test. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/111389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9128/"
]
} |
111,390 | Should simple JavaBeans that have only simple getters and setters be unit tested?? What about Beans with some logic in getters and setters? | You should not write tests which: Test the language or the IDE (i.e. automatically generated getters and setters) Add no value to your test harness and kill your enthusiasm for Unit Testing The same applies for .NET objects which only have properties (sometimes called 'Info' objects). In an ideal world you would have 100% test coverage, but in practice this is not going to happen. So spend the client's money where it will add the most benefit i.e. writing tests for classes with complex state and behaviour. If your JavaBean becomes more interesting you can of course add a test case later. One of the common problems associated with Unit Testing / TDD is the mistaken belief that everything has to be perfect first time. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/111390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19888/"
]
} |
111,407 | I have a simple unordered list that I want to show and hide on click using the jQuery slideUp and slideDown effect. Everything seems to work fine, however in IE6 the list will slide up, flicker for a split second, and then disappear. Does anyone know of a fix for this? Thanks! | Apologies for the extra comment (I can't upvote or comment on Pavel's answer), but adding a DOCTYPE fixed this issue for me, and the slideUp/Down/Toggle effects now work correctly in IE7. See A List Apart for more information on DOCTYPES, or you can try specifying the fairly lenient 4/Transitional: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"> | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/111407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1396/"
]
} |
111,426 | I'm taking a course in computational complexity and have so far had an impression that it won't be of much help to a developer. I might be wrong but if you have gone down this path before, could you please provide an example of how the complexity theory helped you in your work? Tons of thanks. | O(1): Plain code without loops. Just flows through. Lookups in a lookup table are O(1), too. O(log(n)): efficiently optimized algorithms. Example: binary tree algorithms and binary search. Usually doesn't hurt. You're lucky if you have such an algorithm at hand. O(n): a single loop over data. Hurts for very large n. O(n*log(n)): an algorithm that does some sort of divide and conquer strategy. Hurts for large n. Typical example: merge sort O(n*n): a nested loop of some sort. Hurts even with small n. Common with naive matrix calculations. You want to avoid this sort of algorithm if you can. O(n^x for x>2): a wicked construction with multiple nested loops. Hurts for very small n. O(x^n, n! and worse): freaky (and often recursive) algorithms you don't want to have in production code except in very controlled cases, for very small n and if there really is no better alternative. Computation time may explode with n=n+1. Moving your algorithm down from a higher complexity class can make your algorithm fly. Think of Fourier transformation which has an O(n*n) algorithm that was unusable with 1960s hardware except in rare cases. Then Cooley and Tukey made some clever complexity reductions by re-using already calculated values. That led to the widespread introduction of FFT into signal processing. And in the end it's also why Steve Jobs made a fortune with the iPod. Simple example: Naive C programmers write this sort of loop: for (int cnt=0; cnt < strlen(s) ; cnt++) { /* some code */} That's an O(n*n) algorithm because of the implementation of strlen(). Nesting loops leads to multiplication of complexities inside the big-O. O(n) inside O(n) gives O(n*n). O(n^3) inside O(n) gives O(n^4). In the example, precalculating the string length will immediately turn the loop into O(n). Joel has also written about this. Yet the complexity class is not everything. You have to keep an eye on the size of n. Reworking an O(n*log(n)) algorithm to O(n) won't help if the number of (now linear) instructions grows massively due to the reworking. And if n is small anyway, optimizing won't give much bang, too. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/111426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8203/"
]
} |
111,436 | I want to have my PHP application labeled with the revision number which it uses, but I don't want to use CruiseControl or update a file and upload it every time. How should I do it? | SVN keywords is not a good solution. As others pointed out adding $Revision$ in a file only affects the specific file , which may not change for a long time. Remembering to "edit" a file (by adding or removing a blank line) before every commit is pointless. You could as well just type the revision by hand. One good way to do it (that I know of) is to have an automated deployment process (which is always a good thing) and using the command svnversion. Here is what I do: Wherever I need the revision I do an include: <?php include 'version.php'; ?> . This "version.php" file only has the revision number. Moreover it is not part of the repository (it set to be ignored). Here is how I create it: 1) On projects where SVN is installed on the server, I also use it for deployment. Getting the latest version to the server I have a script that among other things does the following (it runs on the server): cd /var/www/projectsvn updaterm version.phpsvnversion > version.php 2) On projects where SVN is not installed my deployment script is more complex: it creates the version.php file locally, zips the code, uploads and extracts it | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/111436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19929/"
]
} |
111,460 | I'm working on serial port, transmitting and receiving data to some hardware at 8bit data. I would like to store it as string to facilitate comparison, and preset data are stored as string or hex format in xml file. I found out that only when using Encoding.Default which is ANSI encoding then the 8bit data is converted properly and easily reversible. ASCII encoding will only works for 7bit data, and UTF8 or UTF7 doesn't works well too, since I'm using some character from 1-255. Encoding.Default would be just fine, but I read on MSDN that it's dependent on OS codepage setting, which means it might behave differently on different codepage configured. I use GetBytes() and GetString extensively using the Encoding, but would like a failsafe and portable method that works all the time at any configuration. Any idea or better suggestion for this? | Latin-1 aka ISO-8859-1 aka codepage 28591 is a useful codepage for this scenario, as it maps values in the range 128-255 unchanged. The following are interchangeable: Encoding.GetEncoding(28591)Encoding.GetEncoding("Latin1")Encoding.GetEncoding("iso-8859-1") The following code illustrates the fact that for Latin1, unlike Encoding.Default, all characters in the range 0-255 are mapped unchanged: static void Main(string[] args){ Console.WriteLine("Test Default Encoding returned {0}", TestEncoding(Encoding.Default)); Console.WriteLine("Test Latin1 Encoding returned {0}", TestEncoding(Encoding.GetEncoding("Latin1"))); Console.ReadLine(); return;}private static bool CompareBytes(char[] chars, byte[] bytes){ bool result = true; if (chars.Length != bytes.Length) { Console.WriteLine("Length mismatch {0} bytes and {1} chars" + bytes.Length, chars.Length); return false; } for (int i = 0; i < chars.Length; i++) { int charValue = (int)chars[i]; if (charValue != (int)bytes[i]) { Console.WriteLine("Byte at index {0} value {1:X4} does not match char {2:X4}", i, (int) bytes[i], charValue); result = false; } } return result;}private static bool TestEncoding(Encoding encoding){ byte[] inputBytes = new byte[256]; for (int i = 0; i < 256; i++) { inputBytes[i] = (byte) i; } char[] outputChars = encoding.GetChars(inputBytes); Console.WriteLine("Comparing input bytes and output chars"); if (!CompareBytes(outputChars, inputBytes)) return false; byte[] outputBytes = encoding.GetBytes(outputChars); Console.WriteLine("Comparing output bytes and output chars"); if (!CompareBytes(outputChars, outputBytes)) return false; return true;} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/111460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20007/"
]
} |
111,461 | I see a lot of example code for C# classes that does this: public class Point { public int x { get; set; } public int y { get; set; }} Or, in older code, the same with an explicit private backing value and without the new auto-implemented properties: public class Point { private int _x; private int _y; public int x { get { return _x; } set { _x = value; } } public int y { get { return _y; } set { _y = value; } }} My question is why. Is there any functional difference between doing the above and just making these members public fields, like below? public class Point { public int x; public int y;} To be clear, I understand the value of getters and setters when you need to do some translation of the underlying data. But in cases where you're just passing the values through, it seems needlessly verbose. | I tend to agree (that it seems needlessly verbose), although this has been an issue our team hasn't yet resolved and so our coding standards still insist on verbose properties for all classes. Jeff Atwood dealt with this a few years ago. The most important point he retrospectively noted is that changing from a field to a property is a breaking change in your code; anything that consumes it must be recompiled to work with the new class interface, so if anything outside of your control is consuming your class you might have problems. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/111461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19688/"
]
} |
111,478 | Why is it wrong to use std::auto_ptr<> with standard containers? | The C++ Standard says that an STL element must be "copy-constructible" and "assignable." In other words, an element must be able to be assigned or copied and the two elements are logically independent. std::auto_ptr does not fulfill this requirement. Take for example this code: class X{};std::vector<std::auto_ptr<X> > vecX;vecX.push_back(new X);std::auto_ptr<X> pX = vecX[0]; // vecX[0] is assigned NULL. To overcome this limitation, you should use the std::unique_ptr , std::shared_ptr or std::weak_ptr smart pointers or the boost equivalents if you don't have C++11. Here is the boost library documentation for these smart pointers. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/111478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19129/"
]
} |
111,529 | Is there any way to create the query parameters for doing a GET request in JavaScript? Just like in Python you have urllib.urlencode() , which takes in a dictionary (or list of two tuples) and creates a string like 'var1=value1&var2=value2' . | Here you go: function encodeQueryData(data) { const ret = []; for (let d in data) ret.push(encodeURIComponent(d) + '=' + encodeURIComponent(data[d])); return ret.join('&');} Usage: const data = { 'first name': 'George', 'last name': 'Jetson', 'age': 110 };const querystring = encodeQueryData(data); | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/111529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448/"
]
} |
111,543 | I'm trying to setup a new computer to synchronize with my SVN repository that's hosted with cvsdude.com. I get this error: ![SVN Error][1] - removed image shack image that had been replaced by an advert Here's what I did (these have worked in the past): Downloaded and installed TortoiseSVN Created a new folder C:\aspwebsite Right-clicked, chose SVN Checkout... Entered the following information, clicked OK: URL of repository: https://<reponame>-svn.cvsdude.com/aspwebsite Checkout directory: C:\aspwebsite Checkout depth: Fully recursive Omit externals: Unchecked Revision: HEAD revision Got TortoiseSVN error: OPTIONS of ' https://<reponame>-svn.cvsdude.com/aspwebsite ': could not connect to server ( https://<reponame>-svn.cvsdude.com ) Rather than getting the error, TortoiseSVN should have asked for my username and password and then downloaded about 90MB. Why can't I checkout from my Subversion repository? Kent Fredric wrote: Either their security certificate has expired, or their hosting is broken/down. Contact CVSDude and ask them whats up. It could also be a timeout, because for me their site is exhaustively slow.. It errors after only a couple seconds. I don't think it's a timeout. Matt wrote: Try visiting https://[redacted]-svn.cvsdude.com/aspwebsite and see what happens. If you can visit it in your browser, you ought to be able to get the files in your SVN client and we can work from there. If it fails, then there's your answer. I can access the site in a web browser. | Check you proxy settings in TortoiseSVN->Settings->Network . Maybe they are configured differently than in your web browser. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/111543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
]
} |
111,576 | What are some popular spam prevention methods besides CAPTCHA? | I have tried doing 'honeypots' where you put a field and then hide it with CSS (marking it as 'leave blank' for anyone with stylesheets disabled) but I have found that a lot of bots are able to get past it very quickly. There are also techniques like setting fields to a certain value and changing them with JS, calculating times between load time and submit time, checking the referer URL, and a million other things. They all have their pitfalls and pretty much all you can hope for is to filter as much as you can with them while not alienating who you're here for: the users. At the end of the day, though, if you really, really, don't want bots to be sending things through your form you're going to want to put a CAPTCHA on it - best one I've seen that takes care of mostly everything is reCAPTCHA - but thanks to India's CAPTCHA solving market and the ingenuity of spammers everywhere that's not even successful all of the time. I would beware using something that is 'ingenious' but kind of 'out there' as it would be more of a 'wtf' for users that are at least somewhat used to your usual CAPTCHAs. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/111576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17162/"
]
} |
111,578 | Also, where would I find them? | Tortoise HG . All the tortoise goodness, now for Mercurial. UPDATE july 2020: The original official website linked above is abandoned. The project moved to: https://foss.heptapod.net/mercurial/tortoisehg/thg | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/111578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16398/"
]
} |
111,597 | Basically I’ve heard that certain conditions will cause .NET to blow past the finally block. Does anyone know what those conditions are? | Two possibilities: StackOverflowException ExecutionEngineException The finally block will not be executed when there's a StackOverflowException since there's no room on the stack to even execute any more code. It will also not be called when there's an ExecutionEngineException , which may arise from a call to Environment.FailFast() . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/111597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2424/"
]
} |
111,605 | No doubt, it's essential for understanding code to give member variables a prefix so that they can easily be distinguished from "normal" variables. But what kind of prefix do you use? I have been working on projects where we used m_ as prefix, on other projects we used an underscore only (which I personally don't like, because an underscore only is not demonstrative enough). On another project we used a long prefix form, that also included the variable type. mul_ for example is the prefix of a m ember variable of type u nsigned l ong. Now let me know what kind of prefix you use (and please give a reason for it). EDIT: Most of you seem to code without special prefixes for member variables! Does this depend on the language? From my experience, C++ code tends to use an underscore or m_ as a prefix for member variables. What about other languages? | No doubt, it's essential for understanding code to give member variables a prefix so that they can easily be distinguished from "normal" variables. I dispute this claim. It's not the least bit necessary if you have half-decent syntax highlighting. A good IDE can let you write your code in readable English, and can show you the type and scope of a symbol other ways. Eclipse does a good job by highlighting declarations and uses of a symbol when the insertion point is on one of them. Edit, thanks slim: A good syntax highlighter like Eclipse will also let you use bold or italic text, or change fonts altogether. For instance, I like italics for static things. Another edit: Think of it this way; the type and scope of a variable are secondary information. It should be available and easy to find out, but not shouted at you. If you use prefixes like m_ or types like LPCSTR , that becomes noise, when you just want to read the primary information – the intent of the code. Third edit: This applies regardless of language. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/111605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2012356/"
]
} |
111,631 | I am working with a Visual Studio 2005 C++ solution that includes multiple projects (about 30). Based upon my experience, it often becomes annoying to maintain all the properties of the projects (i.e include path, lib path, linked libs, code generation options, ...), as you often have to click each and every project in order to modify them.The situation becomes even worse when you have multiple configurations (Debug, Release, Release 64 bits, ...). Real life examples: Assume you want to use a new library, and you need to add the include path to this library to all projects. How will you avoid to have to edit the properties of each an every project? Assume you want to test drive a new version of library (say version 2.1beta) so that you need to quickly change the include paths / library path / linked library for a set of projects? Notes: I am aware that it is possible to select multiple projects at a time, then make a right click and select "properties". However this method only works for properties that were already exactly identical for the different projects : you can not use it in order to add an include path to a set of project that were using different include path. I also know that it is possible to modify globally the environment options (Tools/Options/Project And solutions/Directories), however it is not that satisfying since it can not be integrated into a SCM I also know that one can add "Configurations" to a solutions. It does not helps since it makes another set of project properties to maintain I know that codegear C++ Builder 2009 offers a viable answer to this need through so called "Option sets" which can be inherited by several projects (I use both Visual Studio and C++ Builder, and I still thinks C++ Builder rocks on certain aspects as compared to Visual Studio) I expect that someone will suggest an "autconf" such as CMake, however is it possible to import vcproj files into such a tool? | I think you need to investigate properties files, i.e. *.vsprops (older) or *.props (latest) You do need to add the properties file manually to each project, but once that's done, you have multiple projects, but one .[vs]props file. If you change the properties, all projects inherit the new settings. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/111631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19816/"
]
} |
111,676 | Does anyone have any advice for a consistent way to unit test a multithreaded application? I have done one application where our mock "worker threads" had a thread.sleep with a time that was specified by a public member variable. We would use this so we could set how long a particular thread would take to complete its work, then we could do our assertions. Any ideas of a better way to do this? Any good mock frameworks for .Net that can handle this? | My advice would be not to rely on unit tests to detect concurrency issues for several reasons: Lack of reproducibility: the tests will fail only once in a while, and won't be really helpful to pinpoint the problems. Erratic failing build will annoy everybody in the team - because the last commit will always be wrongly suspected for being the cause of the failing build. Deadlocks when encountered are likely to freeze the build until the execution timeout is encountered which can significantly slow down the build. The build environment is likely to be a single CPU environment (think build being run in a VM) where concurrency issues may never happen - no matter how much sleeping time is set. It defeats somehow the idea of having simple, isolated units of validating code. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/111676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19840/"
]
} |
111,700 | It's the weekend, so I relax from spending all week programming by writing a hobby project. I wrote the framework of a MOS 6502 CPU emulator yesterday, the registers, stack, memory and all the opcodes are implemented. (Link to source below) I can manually run a series of operations in the debugger I wrote, but I'd like to load a NES rom and just point the program counter at its instructions, I figured that this would be the fastest way to find flawed opcodes. I wrote a quick NES rom loader and loaded the ROM banks into the CPU memory. The problem is that I don't know how the opcodes are encoded. I know that the opcodes themselves follow a pattern of one byte per opcode that uniquely identifies the opcode, 0 - BRK1 - ORA (D,X)2 - COP b etc However I'm not sure where I'm supposed to find the opcode argument. Is it the the byte directly following? In absolute memory, I suppose it might not be a byte but a short. Is anyone familiar with this CPU's memory model? EDIT: I realize that this is probably shot in the dark, but I was hoping there were some oldschool Apple and Commodore hackers lurking here. EDIT: Thanks for your help everyone. After I implemented the proper changes to align each operation the CPU can load and run Mario Brothers. It doesn't do anything but loop waiting for Start, but its a good sign :) I uploaded the source: https://archive.codeplex.com/?p=cpu6502 If anyone has ever wondered how an emulator works, its pretty easy to follow. Not optimized in the least, but then again, I'm emulating a CPU that runs at 2mhz on a 2.4ghz machine :) | The opcode takes one byte, and the operands are in the following bytes. Check out the byte size column here , for instance. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/111700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
]
} |
111,707 | I am encountering very infrequent yet annoying SQL deadlocks on a .NET 2.0 webapp running on top of MS SQL Server 2005. In the past, we have been dealing with the SQL deadlocks in the very empirical way - basically tweaking the queries until it work. Yet, I found this approach very unsatisfactory: time consuming and unreliable. I would highly prefer to follow deterministic query patterns that would ensure by design that no SQL deadlock will be encountered - ever. For example, in C# multithreaded programming, a simple design rule such as the locks must be taken following their lexicographical order ensures that no deadlock will ever happen. Are there any SQL coding patterns guaranteed to be deadlock-proof? | Writing deadlock-proof code is really hard. Even when you access the tables in the same order you may still get deadlocks [1]. I wrote a post on my blog that elaborates through some approaches that will help you avoid and resolve deadlock situations. If you want to ensure two statements/transactions will never deadlock you may be able to achieve it by observing which locks each statement consumes using the sp_lock system stored procedure. To do this you have to either be very fast or use an open transaction with a holdlock hint. Notes: Any SELECT statement that needs more than one lock at once can deadlock against an intelligently designed transaction which grabs the locks in reverse order. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/111707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18858/"
]
} |
111,817 | I work on a large C# application (approximately 450,000 lines of code), we constantly have problems with desktop heap and GDI handle leaks. WPF solves these issues, but I don't know what is the best way to upgrade (I expect this is going to take a long time). The application has only a few forms but these can contain many different sets of user-controls which are determined programatically. This is an internal company app so our release cycles are very short (typically 3 week release cycle). Is there some gradual upgrade path or do we have to take the hit in one massive effort? | You can start by creating a WPF host. Then you can use the <WindowsFormHost/> control to host your current application. Then, I suggest creating a library of your new controls in WPF. One at a time, you can create the controls (I suggest making them custom controls, not usercontrols). Within the style for each control, you can start with using the <ElementHost/> control to include the "old" windows forms control. Then you can take your time to refactor and recreate each control as complete WPF. I think it will still take an initial effort to create your control wrappers and design a WPF host for the application. I am not sure the size of the application and or the complexity of the user controls, so I'm not sure how much effort that would be for you. Relatively speaking, it is significantly less effort and much faster to get you application up and running in WPF this way. I wouldn't just do that and forget about it though, as you may run into issues with controls overlaying each other (Windows forms does not play well with WPF, especially with transparencies and other visuals) Please update us on the status of this project, or provide more technical information if you would like more specific guidance. Thanks :) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/111817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19290/"
]
} |
111,866 | In Cocoa, if I want to loop through an NSMutableArray and remove multiple objects that fit a certain criteria, what's the best way to do this without restarting the loop each time I remove an object? Thanks, Edit: Just to clarify - I was looking for the best way, e.g. something more elegant than manually updating the index I'm at. For example in C++ I can do; iterator it = someList.begin();while (it != someList.end()){ if (shouldRemove(it)) it = someList.erase(it);} | For clarity I like to make an initial loop where I collect the items to delete. Then I delete them. Here's a sample using Objective-C 2.0 syntax: NSMutableArray *discardedItems = [NSMutableArray array];for (SomeObjectClass *item in originalArrayOfItems) { if ([item shouldBeDiscarded]) [discardedItems addObject:item];}[originalArrayOfItems removeObjectsInArray:discardedItems]; Then there is no question about whether indices are being updated correctly, or other little bookkeeping details. Edited to add: It's been noted in other answers that the inverse formulation should be faster. i.e. If you iterate through the array and compose a new array of objects to keep, instead of objects to discard. That may be true (although what about the memory and processing cost of allocating a new array, and discarding the old one?) but even if it's faster it may not be as big a deal as it would be for a naive implementation, because NSArrays do not behave like "normal" arrays. They talk the talk but they walk a different walk. See a good analysis here: The inverse formulation may be faster, but I've never needed to care whether it is, because the above formulation has always been fast enough for my needs. For me the take-home message is to use whatever formulation is clearest to you. Optimize only if necessary. I personally find the above formulation clearest, which is why I use it. But if the inverse formulation is clearer to you, go for it. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/111866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1043/"
]
} |
111,927 | I use a System.Timers.Timer in my Asp.Net application and I need to use the HttpServerUtility.MapPath method which seems to be only available via HttpContext.Current.Server.MapPath .The problem is that HttpContext.Current is null when the Timer.Elapsed event fires. Is there another way to get a reference to a HttpServerUtility object ? I could inject it in my class' constructor. Is it safe ? How can I be sure it won't be Garbage Collected at the end of the current request? Thanks! | It's possible to use HostingEnvironment.MapPath() instead of HttpContext.Current.Server.MapPath() I haven't tried it yet in a thread or timer event though. Some (non viable) solutions I considered; The only method I care about on HttpServerUtility is MapPath . So as an alternative I could use AppDomain.CurrentDomain.BaseDirectory and build my paths from this. But this will fail if your app uses virtual directories (Mine does). Another approach: Add all the paths I need to the the Global class. Resolve these paths in Application_Start . | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/111927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1130/"
]
} |
111,928 | I can print with printf as a hex or octal number. Is there a format tag to print as binary, or arbitrary base? I am running gcc. printf("%d %x %o\n", 10, 10, 10); //prints "10 A 12\n"print("%b\n", 10); // prints "%b\n" | Hacky but works for me: #define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c"#define BYTE_TO_BINARY(byte) \ (byte & 0x80 ? '1' : '0'), \ (byte & 0x40 ? '1' : '0'), \ (byte & 0x20 ? '1' : '0'), \ (byte & 0x10 ? '1' : '0'), \ (byte & 0x08 ? '1' : '0'), \ (byte & 0x04 ? '1' : '0'), \ (byte & 0x02 ? '1' : '0'), \ (byte & 0x01 ? '1' : '0') printf("Leading text "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(byte)); For multi-byte types printf("m: "BYTE_TO_BINARY_PATTERN" "BYTE_TO_BINARY_PATTERN"\n", BYTE_TO_BINARY(m>>8), BYTE_TO_BINARY(m)); You need all the extra quotes unfortunately. This approach has the efficiency risks of macros (don't pass a function as the argument to BYTE_TO_BINARY ) but avoids the memory issues and multiple invocations of strcat in some of the other proposals here. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/111928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8959/"
]
} |
111,933 | I know what Hungarian refers to - giving information about a variable, parameter, or type as a prefix to its name. Everyone seems to be rabidly against it, even though in some cases it seems to be a good idea. If I feel that useful information is being imparted, why shouldn't I put it right there where it's available? See also: Do people use the Hungarian naming conventions in the real world? | Most people use Hungarian notation in a wrong way and are getting wrong results. Read this excellent article by Joel Spolsky: Making Wrong Code Look Wrong . In short, Hungarian Notation where you prefix your variable names with their type (string) (Systems Hungarian) is bad because it's useless. Hungarian Notation as it was intended by its author where you prefix the variable name with its kind (using Joel's example: safe string or unsafe string), so called Apps Hungarian has its uses and is still valuable. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/111933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16398/"
]
} |
111,934 | I want to create some text in a canvas: myText = self.canvas.create_text(5, 5, anchor=NW, text="TEST") Now how do I find the width and height of myText ? | bounds = self.canvas.bbox(myText) # returns a tuple like (x1, y1, x2, y2)width = bounds[2] - bounds[0]height = bounds[3] - bounds[1] See the TkInter reference . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/111934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10577/"
]
} |
111,945 | I need to upload some data to a server using HTTP PUT in python. From my brief reading of the urllib2 docs, it only does HTTP POST . Is there any way to do an HTTP PUT in python? | I've used a variety of python HTTP libs in the past, and I've settled on requests as my favourite. Existing libs had pretty useable interfaces, but code can end up being a few lines too long for simple operations. A basic PUT in requests looks like: payload = {'username': 'bob', 'email': '[email protected]'}>>> r = requests.put("http://somedomain.org/endpoint", data=payload) You can then check the response status code with: r.status_code or the response with: r.content Requests has a lot synactic sugar and shortcuts that'll make your life easier. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/111945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/161922/"
]
} |
111,954 | You can use ftplib for full FTP support in Python. However the preferred way of getting a directory listing is: # File: ftplib-example-1.pyimport ftplibftp = ftplib.FTP("www.python.org")ftp.login("anonymous", "ftplib-example-1")data = []ftp.dir(data.append)ftp.quit()for line in data: print "-", line Which yields: $ python ftplib-example-1.py- total 34- drwxrwxr-x 11 root 4127 512 Sep 14 14:18 .- drwxrwxr-x 11 root 4127 512 Sep 14 14:18 ..- drwxrwxr-x 2 root 4127 512 Sep 13 15:18 RCS- lrwxrwxrwx 1 root bin 11 Jun 29 14:34 README -> welcome.msg- drwxr-xr-x 3 root wheel 512 May 19 1998 bin- drwxr-sr-x 3 root 1400 512 Jun 9 1997 dev- drwxrwxr-- 2 root 4127 512 Feb 8 1998 dup- drwxr-xr-x 3 root wheel 512 May 19 1998 etc... I guess the idea is to parse the results to get the directory listing. However this listing is directly dependent on the FTP server's way of formatting the list. It would be very messy to write code for this having to anticipate all the different ways FTP servers might format this list. Is there a portable way to get an array filled with the directory listing? (The array should only have the folder names.) | Try using ftp.nlst(dir) . However, note that if the folder is empty, it might throw an error: files = []try: files = ftp.nlst()except ftplib.error_perm as resp: if str(resp) == "550 No files found": print "No files in this directory" else: raisefor f in files: print f | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/111954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
]
} |
111,983 | If you are creating a 1d array in Python, is there any benefit to using the NumPy package? | It all depends on what you plan to do with the array. If all you're doing is creating arrays of simple data types and doing I/O, the array module will do just fine. If, on the other hand, you want to do any kind of numerical calculations, the array module doesn't provide any help with that. NumPy (and SciPy ) give you a wide variety of operations between arrays and special functions that are useful not only for scientific work but for things like advanced image manipulation or in general anything where you need to perform efficient calculations with large amounts of data. Numpy is also much more flexible, e.g. it supports arrays of any type of Python objects, and is also able to interact "natively" with your own objects if they conform to the array interface . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/111983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16584/"
]
} |
111,995 | Is there a way to separate a C# class into a header that contains the class definition and then an actual .cs file that contains the implementation? I suppose one can do this by creating an interface, but that doesn't seem right. I just want a file where I can just see the class design, and not all the detail. It's easy enough to do in C++, but I haven't seen it done with C#. Thanks in advance. | That's a wrong approach. C# isn't C++. Forget about header files . If you want the class summary, just open the Object Browser in Visual Studio. It will give you the signature of all the methods within your classes. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/111995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20062/"
]
} |
112,046 | Some members of the team are having problems programming together. Different gender, different culture, different age. How to deal with those problems? - Do not pair them together, or - Pair them together and let them come to a "golden middle" | Pair programming is based on the idea that the interaction of two programmers adds value. If this is not true, change the pairs... let them choose. Programming should be fun! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/112046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19268/"
]
} |
112,055 | I'm looking at a batch file which defines the following variables: set _SCRIPT_DRIVE=%~d0set _SCRIPT_PATH=%~p0 What do %~d0 or %~p0 actually mean? Is there a set of well-known values for things like current directory, drive, parameters to a script? Are there any other similar shortcuts I could use? | The magic variables % n contains the arguments used to invoke the file: %0 is the path to the bat-file itself, %1 is the first argument after, %2 is the second and so on. Since the arguments are often file paths, there is some additional syntax to extract parts of the path. ~d is drive, ~p is the path (without drive), ~n is the file name. They can be combined so ~dp is drive+path. %~dp0 is therefore pretty useful in a bat: it is the folder in which the executing bat file resides. You can also get other kinds of meta info about the file: ~t is the timestamp, ~z is the size. Look here for a reference for all command line commands. The tilde-magic codes are described under for . | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/112055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/322/"
]
} |
112,064 | The word seems to get used in a number of contexts. The best I can figure is that they mean a variable that can't change. Isn't that what constants/finals (darn you Java!) are for? | An invariant is more "conceptual" than a variable. In general, it's a property of the program state that is always true. A function or method that ensures that the invariant holds is said to maintain the invariant. For instance, a binary search tree might have the invariant that for every node, the key of the node's left child is less than the node's own key. A correctly written insertion function for this tree will maintain that invariant. As you can tell, that's not the sort of thing you can store in a variable: it's more a statement about the program. By figuring out what sort of invariants your program should maintain, then reviewing your code to make sure that it actually maintains those invariants, you can avoid logical errors in your code. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/112064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16398/"
]
} |
112,085 | Instead of having to remember to initialize a simple 'C' structure, I might derive from it and zero it in the constructor like this: struct MY_STRUCT{ int n1; int n2;};class CMyStruct : public MY_STRUCT{public: CMyStruct() { memset(this, 0, sizeof(MY_STRUCT)); }}; This trick is often used to initialize Win32 structures and can sometimes set the ubiquitous cbSize member. Now, as long as there isn't a virtual function table for the memset call to destroy, is this a safe practice? | You can simply value-initialize the base, and all its members will be zero'ed out. This is guaranteed struct MY_STRUCT{ int n1; int n2;};class CMyStruct : public MY_STRUCT{public: CMyStruct():MY_STRUCT() { }}; For this to work, there should be no user declared constructor in the base class, like in your example. No nasty memset for that. It's not guaranteed that memset works in your code, even though it should work in practice. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/112085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
]
} |
112,093 | I have a simple list I am using for a horizontal menu: <ul> <h1>Menu</h1> <li> <a href="/" class="selected">Home</a> </li> <li> <a href="/Home">Forum</a> </li></ul> When I add a background color to the selected class, only the text gets the color, I want it to stretch the entire distance of the section. Hope this makes sense. | The a element is an inline element, meaning it only applies to the text it encloses. If you want the background color to stretch across horizontally, apply the selected class to a block level element. Applying the class to the li element should work fine. Alternatively, you could add this to the selected class' CSS: display: block; Which will make the a element display like a block element. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/112093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
]
} |
112,121 | I'm writing a desktop application that communicates with a web service. Would you name all web-service functions that that fetch data Load XXXX, since they take a while to execute. Or would you use Get XXXX, for instance when getting just a single object. | Use MyObject.GetXXXX() when the method returns XXXX. Use MyObject.LoadXXXX() when XXXX will be loaded into MyObject, in other words, when MyObject keeps control of XXXX. The same applies to webservices, I guess. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/112121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20075/"
]
} |
112,158 | On my team, we usually do string concatentation like this: var url = // some dynamically generated URLvar sb = new StringBuffer();sb.append("<a href='").append(url).append("'>click here</a>"); Obviously the following is much more readable: var url = // some dynamically generated URLvar sb = "<a href='" + url + "'>click here</a>"; But the JS experts claim that the + operator is less performant than StringBuffer.append() . Is this really true? | Your example is not a good one in that it is very unlikely that the performance will be signficantly different. In your example readability should trump performance because the performance gain of one vs the other is negligable. The benefits of an array (StringBuffer) are only apparent when you are doing many concatentations. Even then your mileage can very depending on your browser. Here is a detailed performance analysis that shows performance using all the different JavaScript concatenation methods across many different browsers; String Performance an Analysis More: Ajaxian >> String Performance in IE: Array.join vs += continued | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/112158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
]
} |
112,190 | My ISP account requires that I send a username & password for outbound SMTP mail. How do I get PHP to use this when executing php.mail()? The php.ini file only contains entries for the server (SMTP= ) and From: (sendmail_from= ) . | PHP mail() command does not support authentication. Your options: PHPMailer - Tutorial PEAR - Tutorial Custom functions - See various solutions in the notes section: http://php.net/manual/en/ref.mail.php | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/112190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17560/"
]
} |
112,197 | I want to create a hidden field and create a link in one helper and then output both to my erb. <%= my_cool_helper "something", form %> Should out put the results of link_to "something", a_pathform.hidden_field "something".tableize, :value => "something" What would the definition of the helper look like? The details of what link_to and the form.hidden_field don't really matter. What matters is, how do I return the output from two different calls. | There are several ways to do this. Remember that the existing rails helpers like link_to , etc, just output strings. You can concatenate the strings together and return that (which is what I do most of the time, if things are simple). EG: link_to( "something", something_path ) + #NOTE THE PLUS FOR STRING CONCAT form.hidden_field('something'.tableize, :value=>'something') If you're doing things which are more complicated, you could just put that code in a partial, and have your helper call render :partial . If you're doing more complicated stuff than even that, then you may want to look at errtheblog's block_to_partial helper, which is pretty cool | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/112197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1681/"
]
} |
112,224 | I made a panel and set it to fill the screen, now I can see the windows under it but I want it to be click through, meaning they could click a file or see a tool tip of another object through the transparency. RE: This may be too obvious, but have you tried sending the panel to the back by right clicking and choosing "Send to Back"? I mean like the desktop or firefox, not something within my project. | Creating a top level form that is transparent is very easy. Just make it fill the screen, or required area, and define it to have a TransparenyKey color and BackColor of the same value. Getting it to ignore the mouse is simple enough, you just need to override the WndProc and tell the WM_HITTEST that all mouse positions are to be treated as transparent. Thus causing the mouse to interact with whatever happens to be underneath the window. Something like this... protected override void WndProc(ref Message m) { if (m.Msg == (int)WM_NCHITTEST) m.Result = (IntPtr)HTTRANSPARENT; else base.WndProc(ref m); } | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/112224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18309/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.